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
1c3187680e2e73d86ac561213b8c3e93990f9bf8
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/empty_match_bug.lean
65f8d5d8488999e09c1dacf92f39df59f7fa326a
[ "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
190
lean
open nat inductive Fin : nat → Type | fz : Π n, Fin (succ n) | fs : Π {n}, Fin n → Fin (succ n) open Fin definition case0 {C : Fin 0 → Type} (f : Fin 0) : C f := match f with end
62da02050c588872b9dbcdac883eea0be9937480
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/combinatorics/simple_graph/regularity/bound.lean
6e2e8992eac1a2555a68dda7b89075f7f5457a59
[ "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
10,341
lean
/- Copyright (c) 2022 Yaël Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import algebra.order.chebyshev import analysis.special_functions.pow.real import order.partition.equipartition /-! # Numerical bounds for Szemerédi Regularity Lemma > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file gathers the numerical facts required by the proof of Szemerédi's regularity lemma. This entire file is internal to the proof of Szemerédi Regularity Lemma. ## Main declarations * `szemeredi_regularity.step_bound`: During the inductive step, a partition of size `n` is blown to size at most `step_bound n`. * `szemeredi_regularity.initial_bound`: The size of the partition we start the induction with. * `szemeredi_regularity.bound`: The upper bound on the size of the partition produced by our version of Szemerédi's regularity lemma. ## References [Yaël Dillies, Bhavik Mehta, *Formalising Szemerédi’s Regularity Lemma in Lean*][srl_itp] -/ open finset fintype function real open_locale big_operators namespace szemeredi_regularity /-- Auxiliary function for Szemerédi's regularity lemma. Blowing up a partition of size `n` during the induction results in a partition of size at most `step_bound n`. -/ def step_bound (n : ℕ) : ℕ := n * 4 ^ n lemma le_step_bound : id ≤ step_bound := λ n, nat.le_mul_of_pos_right $ pow_pos (by norm_num) n lemma step_bound_mono : monotone step_bound := λ a b h, nat.mul_le_mul h $ nat.pow_le_pow_of_le_right (by norm_num) h lemma step_bound_pos_iff {n : ℕ} : 0 < step_bound n ↔ 0 < n := zero_lt_mul_right $ by positivity alias step_bound_pos_iff ↔ _ step_bound_pos end szemeredi_regularity open szemeredi_regularity variables {α : Type*} [decidable_eq α] [fintype α] {P : finpartition (univ : finset α)} {u : finset α} {ε : ℝ} local notation `m` := (card α/step_bound P.parts.card : ℕ) local notation `a` := (card α/P.parts.card - m * 4^P.parts.card : ℕ) namespace tactic open positivity private lemma eps_pos {ε : ℝ} {n : ℕ} (h : 100 ≤ 4 ^ n * ε^5) : 0 < ε := pow_bit1_pos_iff.1 $ pos_of_mul_pos_right (h.trans_lt' $ by norm_num) $ by positivity private lemma m_pos [nonempty α] (hPα : P.parts.card * 16^P.parts.card ≤ card α) : 0 < m := nat.div_pos ((nat.mul_le_mul_left _ $ nat.pow_le_pow_of_le_left (by norm_num) _).trans hPα) $ step_bound_pos (P.parts_nonempty $ univ_nonempty.ne_empty).card_pos /-- Local extension for the `positivity` tactic: A few facts that are needed many times for the proof of Szemerédi's regularity lemma. -/ meta def positivity_szemeredi_regularity : expr → tactic strictness | `(%%n / step_bound (finpartition.parts %%P).card) := do p ← to_expr ``((finpartition.parts %%P).card * 16^(finpartition.parts %%P).card ≤ %%n) >>= find_assumption, positive <$> mk_app ``m_pos [p] | ε := do typ ← infer_type ε, unify typ `(ℝ), p ← to_expr ``(100 ≤ 4 ^ _ * %%ε ^ 5) >>= find_assumption, positive <$> mk_app ``eps_pos [p] end tactic local attribute [positivity] tactic.positivity_szemeredi_regularity namespace szemeredi_regularity lemma m_pos [nonempty α] (hPα : P.parts.card * 16^P.parts.card ≤ card α) : 0 < m := by positivity lemma coe_m_add_one_pos : 0 < (m : ℝ) + 1 := by positivity lemma one_le_m_coe [nonempty α] (hPα : P.parts.card * 16^P.parts.card ≤ card α) : (1 : ℝ) ≤ m := nat.one_le_cast.2 $ m_pos hPα lemma eps_pow_five_pos (hPε : 100 ≤ 4^P.parts.card * ε^5) : 0 < ε^5 := pos_of_mul_pos_right ((by norm_num : (0 : ℝ) < 100).trans_le hPε) $ pow_nonneg (by norm_num) _ lemma eps_pos (hPε : 100 ≤ 4^P.parts.card * ε^5) : 0 < ε := pow_bit1_pos_iff.1 $ eps_pow_five_pos hPε lemma hundred_div_ε_pow_five_le_m [nonempty α] (hPα : P.parts.card * 16^P.parts.card ≤ card α) (hPε : 100 ≤ 4^P.parts.card * ε^5) : 100 / ε^5 ≤ m := (div_le_of_nonneg_of_le_mul (eps_pow_five_pos hPε).le (by positivity) hPε).trans begin norm_cast, rwa [nat.le_div_iff_mul_le'(step_bound_pos (P.parts_nonempty $ univ_nonempty.ne_empty).card_pos), step_bound, mul_left_comm, ←mul_pow], end lemma hundred_le_m [nonempty α] (hPα : P.parts.card * 16^P.parts.card ≤ card α) (hPε : 100 ≤ 4^P.parts.card * ε^5) (hε : ε ≤ 1) : 100 ≤ m := by exact_mod_cast (hundred_div_ε_pow_five_le_m hPα hPε).trans' (le_div_self (by norm_num) (by positivity) $ pow_le_one _ (by positivity) hε) lemma a_add_one_le_four_pow_parts_card : a + 1 ≤ 4^P.parts.card := begin have h : 1 ≤ 4^P.parts.card := one_le_pow_of_one_le (by norm_num) _, rw [step_bound, ←nat.div_div_eq_div_mul, ←nat.le_sub_iff_right h, tsub_le_iff_left, ←nat.add_sub_assoc h], exact nat.le_pred_of_lt (nat.lt_div_mul_add h), end lemma card_aux₁ (hucard : u.card = m * 4^P.parts.card + a) : (4^P.parts.card - a) * m + a * (m + 1) = u.card := by rw [hucard, mul_add, mul_one, ←add_assoc, ←add_mul, nat.sub_add_cancel ((nat.le_succ _).trans a_add_one_le_four_pow_parts_card), mul_comm] lemma card_aux₂ (hP : P.is_equipartition) (hu : u ∈ P.parts) (hucard : ¬u.card = m * 4^P.parts.card + a) : (4^P.parts.card - (a + 1)) * m + (a + 1) * (m + 1) = u.card := begin have : m * 4 ^ P.parts.card ≤ card α / P.parts.card, { rw [step_bound, ←nat.div_div_eq_div_mul], exact nat.div_mul_le_self _ _ }, rw nat.add_sub_of_le this at hucard, rw [(hP.card_parts_eq_average hu).resolve_left hucard, mul_add, mul_one, ←add_assoc, ←add_mul, nat.sub_add_cancel a_add_one_le_four_pow_parts_card, ←add_assoc, mul_comm, nat.add_sub_of_le this, card_univ], end lemma pow_mul_m_le_card_part (hP : P.is_equipartition) (hu : u ∈ P.parts) : (4 : ℝ) ^ P.parts.card * m ≤ u.card := begin norm_cast, rw [step_bound, ←nat.div_div_eq_div_mul], exact (nat.mul_div_le _ _).trans (hP.average_le_card_part hu), end variables (P ε) (l : ℕ) /-- Auxiliary function for Szemerédi's regularity lemma. The size of the partition by which we start blowing. -/ noncomputable def initial_bound : ℕ := max 7 $ max l $ ⌊log (100 / ε^5) / log 4⌋₊ + 1 lemma le_initial_bound : l ≤ initial_bound ε l := (le_max_left _ _).trans $ le_max_right _ _ lemma seven_le_initial_bound : 7 ≤ initial_bound ε l := le_max_left _ _ lemma initial_bound_pos : 0 < initial_bound ε l := nat.succ_pos'.trans_le $ seven_le_initial_bound _ _ lemma hundred_lt_pow_initial_bound_mul {ε : ℝ} (hε : 0 < ε) (l : ℕ) : 100 < 4^initial_bound ε l * ε^5 := begin rw [←rpow_nat_cast 4, ←div_lt_iff (pow_pos hε 5), lt_rpow_iff_log_lt _ zero_lt_four, ←div_lt_iff, initial_bound, nat.cast_max, nat.cast_max], { push_cast, exact lt_max_of_lt_right (lt_max_of_lt_right $ nat.lt_floor_add_one _) }, { exact log_pos (by norm_num) }, { exact div_pos (by norm_num) (pow_pos hε 5) } end /-- An explicit bound on the size of the equipartition whose existence is given by Szemerédi's regularity lemma. -/ noncomputable def bound : ℕ := (step_bound^[⌊4 / ε^5⌋₊] $ initial_bound ε l) * 16 ^ (step_bound^[⌊4 / ε^5⌋₊] $ initial_bound ε l) lemma initial_bound_le_bound : initial_bound ε l ≤ bound ε l := (id_le_iterate_of_id_le le_step_bound _ _).trans $ nat.le_mul_of_pos_right $ by positivity lemma le_bound : l ≤ bound ε l := (le_initial_bound ε l).trans $ initial_bound_le_bound ε l lemma bound_pos : 0 < bound ε l := (initial_bound_pos ε l).trans_le $ initial_bound_le_bound ε l variables {ι 𝕜 : Type*} [linear_ordered_field 𝕜] (r : ι → ι → Prop) [decidable_rel r] {s t : finset ι} {x : 𝕜} lemma mul_sq_le_sum_sq (hst : s ⊆ t) (f : ι → 𝕜) (hs : x^2 ≤ ((∑ i in s, f i) / s.card) ^ 2) (hs' : (s.card : 𝕜) ≠ 0) : (s.card : 𝕜) * x ^ 2 ≤ ∑ i in t, f i ^ 2 := (mul_le_mul_of_nonneg_left (hs.trans sum_div_card_sq_le_sum_sq_div_card) $ nat.cast_nonneg _).trans $ (mul_div_cancel' _ hs').le.trans $ sum_le_sum_of_subset_of_nonneg hst $ λ i _ _, sq_nonneg _ lemma add_div_le_sum_sq_div_card (hst : s ⊆ t) (f : ι → 𝕜) (d : 𝕜) (hx : 0 ≤ x) (hs : x ≤ |(∑ i in s, f i)/s.card - (∑ i in t, f i)/t.card|) (ht : d ≤ ((∑ i in t, f i)/t.card)^2) : d + s.card/t.card * x^2 ≤ (∑ i in t, f i^2)/t.card := begin obtain hscard | hscard := (s.card.cast_nonneg : (0 : 𝕜) ≤ s.card).eq_or_lt, { simpa [←hscard] using ht.trans sum_div_card_sq_le_sum_sq_div_card }, have htcard : (0:𝕜) < t.card := hscard.trans_le (nat.cast_le.2 (card_le_of_subset hst)), have h₁ : x^2 ≤ ((∑ i in s, f i)/s.card - (∑ i in t, f i)/t.card)^2 := sq_le_sq.2 (by rwa [abs_of_nonneg hx]), have h₂ : x^2 ≤ ((∑ i in s, (f i - (∑ j in t, f j)/t.card))/s.card)^2, { apply h₁.trans, rw [sum_sub_distrib, sum_const, nsmul_eq_mul, sub_div, mul_div_cancel_left _ hscard.ne'] }, apply (add_le_add_right ht _).trans, rw [←mul_div_right_comm, le_div_iff htcard, add_mul, div_mul_cancel _ htcard.ne'], have h₃ := mul_sq_le_sum_sq hst (λ i, f i - (∑ j in t, f j) / t.card) h₂ hscard.ne', apply (add_le_add_left h₃ _).trans, simp [←mul_div_right_comm _ (t.card : 𝕜), sub_div' _ _ _ htcard.ne', ←sum_div, ←add_div, mul_pow, div_le_iff (sq_pos_of_ne_zero _ htcard.ne'), sub_sq, sum_add_distrib, ←sum_mul, ←mul_sum], ring_nf, end end szemeredi_regularity namespace tactic open positivity szemeredi_regularity /-- Extension for the `positivity` tactic: `szemeredi_regularity.initial_bound` and `szemeredi_regularity.bound` are always positive. -/ @[positivity] meta def positivity_szemeredi_regularity_bound : expr → tactic strictness | `(szemeredi_regularity.initial_bound %%ε %%l) := positive <$> mk_app ``initial_bound_pos [ε, l] | `(szemeredi_regularity.bound %%ε %%l) := positive <$> mk_app ``bound_pos [ε, l] | e := pp e >>= fail ∘ format.bracket "The expression `" "` isn't of the form `szemeredi_regularity.initial_bound ε l` nor `szemeredi_regularity.bound ε l`" example (ε : ℝ) (l : ℕ) : 0 < szemeredi_regularity.initial_bound ε l := by positivity example (ε : ℝ) (l : ℕ) : 0 < szemeredi_regularity.bound ε l := by positivity end tactic
e336f3ce340fbf73ed00693a5990e7fa57927654
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/tactic/omega/prove_unsats.lean
94233a94f6cf7402ae64462e1c914aef7600b8cf
[ "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
2,086
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Seul Baek -/ /- A tactic which constructs exprs to discharge goals of the form `clauses.unsat cs`. -/ import tactic.omega.find_ees import tactic.omega.find_scalars import tactic.omega.lin_comb namespace omega open tactic /-- Return expr of proof that given int is negative -/ meta def prove_neg : int → tactic expr | (int.of_nat _) := failed | -[1+ m] := return `(int.neg_succ_lt_zero %%`(m)) lemma forall_mem_repeat_zero_eq_zero (m : nat) : (∀ x ∈ (list.repeat (0 : int) m), x = (0 : int)) := λ x, list.eq_of_mem_repeat /-- Return expr of proof that elements of (repeat 0 is.length) are all 0 -/ meta def prove_forall_mem_eq_zero (is : list int) : tactic expr := return `(forall_mem_repeat_zero_eq_zero is.length) /-- Return expr of proof that the combination of linear constraints represented by ks and ts is unsatisfiable -/ meta def prove_unsat_lin_comb (ks : list nat) (ts : list term) : tactic expr := let ⟨b,as⟩ := lin_comb ks ts in do x1 ← prove_neg b, x2 ← prove_forall_mem_eq_zero as, to_expr ``(unsat_lin_comb_of %%`(ks) %%`(ts) %%x1 %%x2) /-- Given a (([],les) : clause), return the expr of a term (t : clause.unsat ([],les)). -/ meta def prove_unsat_ef : clause → tactic expr | ((_::_), _) := failed | ([], les) := do ks ← find_scalars les, x ← prove_unsat_lin_comb ks les, return `(unsat_of_unsat_lin_comb %%`(ks) %%`(les) %%x) /-- Given a (c : clause), return the expr of a term (t : clause.unsat c) -/ meta def prove_unsat (c : clause) : tactic expr := do ee ← find_ees c, x ← prove_unsat_ef (eq_elim ee c), return `(unsat_of_unsat_eq_elim %%`(ee) %%`(c) %%x) /-- Given a (cs : list clause), return the expr of a term (t : clauses.unsat cs) -/ meta def prove_unsats : list clause → tactic expr | [] := return `(clauses.unsat_nil) | (p::ps) := do x ← prove_unsat p, xs ← prove_unsats ps, to_expr ``(clauses.unsat_cons %%`(p) %%`(ps) %%x %%xs) end omega
facaeffea119adc309e4822d41b6d7cef763c37c
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/stage0/src/Lean/Elab/Frontend.lean
0b9f3f42b9aba0bd636ad36c6199ee57239ff729
[ "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
4,493
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Elab.Import import Lean.Elab.Command import Lean.Util.Profile namespace Lean.Elab.Frontend structure State where commandState : Command.State parserState : Parser.ModuleParserState cmdPos : String.Pos commands : Array Syntax := #[] structure Context where inputCtx : Parser.InputContext abbrev FrontendM := ReaderT Context $ StateRefT State IO def setCommandState (commandState : Command.State) : FrontendM Unit := modify fun s => { s with commandState := commandState } @[inline] def runCommandElabM (x : Command.CommandElabM Unit) : FrontendM Unit := do let ctx ← read let s ← get let cmdCtx : Command.Context := { cmdPos := s.cmdPos, fileName := ctx.inputCtx.fileName, fileMap := ctx.inputCtx.fileMap } let sNew? ← liftM $ EIO.toIO (fun _ => IO.Error.userError "unexpected error") (do let (_, s) ← (x cmdCtx).run s.commandState; pure $ some s) match sNew? with | some sNew => setCommandState sNew | none => pure () def elabCommandAtFrontend (stx : Syntax) : FrontendM Unit := do runCommandElabM (Command.elabCommand stx) def updateCmdPos : FrontendM Unit := do modify fun s => { s with cmdPos := s.parserState.pos } def getParserState : FrontendM Parser.ModuleParserState := do pure (← get).parserState def getCommandState : FrontendM Command.State := do pure (← get).commandState def setParserState (ps : Parser.ModuleParserState) : FrontendM Unit := modify fun s => { s with parserState := ps } def setMessages (msgs : MessageLog) : FrontendM Unit := modify fun s => { s with commandState := { s.commandState with messages := msgs } } def getInputContext : FrontendM Parser.InputContext := do pure (← read).inputCtx def processCommand : FrontendM Bool := do updateCmdPos let cmdState ← getCommandState let ictx ← getInputContext let pstate ← getParserState let scope := cmdState.scopes.head! let pmctx := { env := cmdState.env, options := scope.opts, currNamespace := scope.currNamespace, openDecls := scope.openDecls } let pos := ictx.fileMap.toPosition pstate.pos match profileit "parsing" scope.opts fun _ => Parser.parseCommand ictx pmctx pstate cmdState.messages with | (cmd, ps, messages) => modify fun s => { s with commands := s.commands.push cmd } setParserState ps setMessages messages if Parser.isEOI cmd || Parser.isExitCommand cmd then pure true -- Done else profileitM IO.Error "elaboration" scope.opts <| elabCommandAtFrontend cmd pure false partial def processCommands : FrontendM Unit := do let done ← processCommand unless done do processCommands end Frontend open Frontend def IO.processCommands (inputCtx : Parser.InputContext) (parserState : Parser.ModuleParserState) (commandState : Command.State) : IO State := do let (_, s) ← (Frontend.processCommands.run { inputCtx := inputCtx }).run { commandState := commandState, parserState := parserState, cmdPos := parserState.pos } pure s def process (input : String) (env : Environment) (opts : Options) (fileName : Option String := none) : IO (Environment × MessageLog) := do let fileName := fileName.getD "<input>" let inputCtx := Parser.mkInputContext input fileName let s ← IO.processCommands inputCtx { : Parser.ModuleParserState } (Command.mkState env {} opts) pure (s.commandState.env, s.commandState.messages) builtin_initialize registerOption `printMessageEndPos { defValue := false, descr := "print end position of each message in addition to start position" } def getPrintMessageEndPos (opts : Options) : Bool := opts.getBool `printMessageEndPos false @[export lean_run_frontend] def runFrontend (input : String) (opts : Options) (fileName : String) (mainModuleName : Name) : IO (Environment × Bool) := do let inputCtx := Parser.mkInputContext input fileName let (header, parserState, messages) ← Parser.parseHeader inputCtx let (env, messages) ← processHeader header opts messages inputCtx let env := env.setMainModule mainModuleName let s ← IO.processCommands inputCtx parserState (Command.mkState env messages opts) for msg in s.commandState.messages.toList do IO.print (← msg.toString (includeEndPos := getPrintMessageEndPos opts)) pure (s.commandState.env, !s.commandState.messages.hasErrors) end Lean.Elab
c9c6b8da007d8aab0c75bc4cd76d093d4c0dd27e
df561f413cfe0a88b1056655515399c546ff32a5
/8-inequality-world/l9.lean
25c4373d73fe4463ddba77225a0f68a9e278c016
[]
no_license
nicholaspun/natural-number-game-solutions
31d5158415c6f582694680044c5c6469032c2a06
1e2aed86d2e76a3f4a275c6d99e795ad30cf6df0
refs/heads/main
1,675,123,625,012
1,607,633,548,000
1,607,633,548,000
318,933,860
3
1
null
null
null
null
UTF-8
Lean
false
false
356
lean
theorem le_total (a b : mynat) : a ≤ b ∨ b ≤ a := begin induction a with k Pk, left, exact zero_le b, cases Pk, cases Pk with c hc, cases c, rw add_zero at hc, right, rw hc, use 1, refl, left, rw hc, repeat { rw ← add_one_eq_succ }, rw add_comm c 1, rw ← add_assoc k 1 c, use c, refl, right, rw add_one_eq_succ, exact (le_succ b k) Pk, end
d196fdf133b5ff8fc7e6bca764713e04260fea23
0c9c1ff8e5013c525bf1d72338b62db639374733
/library/init/logic.lean
2c4b7b982413545f3be4c6f489c749ce8b899a2b
[ "Apache-2.0" ]
permissive
semorrison/lean
1f2bb450c3400098666ff6e43aa29b8e1e3cdc3a
85dcb385d5219f2fca8c73b2ebca270fe81337e0
refs/heads/master
1,638,526,143,586
1,634,825,588,000
1,634,825,588,000
258,650,844
0
0
Apache-2.0
1,587,772,955,000
1,587,772,954,000
null
UTF-8
Lean
false
false
39,062
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Floris van Doorn -/ prelude import init.core universes u v w @[simp] lemma opt_param_eq (α : Sort u) (default : α) : opt_param α default = α := rfl @[inline] def id {α : Sort u} (a : α) : α := a def flip {α : Sort u} {β : Sort v} {φ : Sort w} (f : α → β → φ) : β → α → φ := λ b a, f a b /- implication -/ def implies (a b : Prop) := a → b /-- Implication `→` is transitive. If `P → Q` and `Q → R` then `P → R`. -/ @[trans] lemma implies.trans {p q r : Prop} (h₁ : implies p q) (h₂ : implies q r) : implies p r := assume hp, h₂ (h₁ hp) lemma trivial : true := ⟨⟩ /-- We can't have `a` and `¬a`, that would be absurd!-/ @[inline] def absurd {a : Prop} {b : Sort v} (h₁ : a) (h₂ : ¬a) : b := false.rec b (h₂ h₁) lemma not.intro {a : Prop} (h : a → false) : ¬ a := h /-- Modus tollens. If an implication is true, then so is its contrapositive. -/ lemma mt {a b : Prop} (h₁ : a → b) (h₂ : ¬b) : ¬a := assume ha : a, h₂ (h₁ ha) /- not -/ lemma not_false : ¬false := id def non_contradictory (a : Prop) : Prop := ¬¬a lemma non_contradictory_intro {a : Prop} (ha : a) : ¬¬a := assume hna : ¬a, absurd ha hna /- false -/ @[inline] def false.elim {C : Sort u} (h : false) : C := false.rec C h /- eq -/ -- proof irrelevance is built in lemma proof_irrel {a : Prop} (h₁ h₂ : a) : h₁ = h₂ := rfl @[simp] lemma id.def {α : Sort u} (a : α) : id a = a := rfl @[inline] def eq.mp {α β : Sort u} : (α = β) → α → β := eq.rec_on @[inline] def eq.mpr {α β : Sort u} : (α = β) → β → α := λ h₁ h₂, eq.rec_on (eq.symm h₁) h₂ @[elab_as_eliminator] lemma eq.substr {α : Sort u} {p : α → Prop} {a b : α} (h₁ : b = a) : p a → p b := eq.subst (eq.symm h₁) lemma congr {α : Sort u} {β : Sort v} {f₁ f₂ : α → β} {a₁ a₂ : α} (h₁ : f₁ = f₂) (h₂ : a₁ = a₂) : f₁ a₁ = f₂ a₂ := eq.subst h₁ (eq.subst h₂ rfl) lemma congr_fun {α : Sort u} {β : α → Sort v} {f g : Π x, β x} (h : f = g) (a : α) : f a = g a := eq.subst h (eq.refl (f a)) lemma congr_arg {α : Sort u} {β : Sort v} {a₁ a₂ : α} (f : α → β) : a₁ = a₂ → f a₁ = f a₂ := congr rfl lemma trans_rel_left {α : Sort u} {a b c : α} (r : α → α → Prop) (h₁ : r a b) (h₂ : b = c) : r a c := h₂ ▸ h₁ lemma trans_rel_right {α : Sort u} {a b c : α} (r : α → α → Prop) (h₁ : a = b) (h₂ : r b c) : r a c := h₁.symm ▸ h₂ lemma of_eq_true {p : Prop} (h : p = true) : p := h.symm ▸ trivial lemma not_of_eq_false {p : Prop} (h : p = false) : ¬p := assume hp, h ▸ hp @[inline] def cast {α β : Sort u} (h : α = β) (a : α) : β := eq.rec a h lemma cast_proof_irrel {α β : Sort u} (h₁ h₂ : α = β) (a : α) : cast h₁ a = cast h₂ a := rfl lemma cast_eq {α : Sort u} (h : α = α) (a : α) : cast h a = a := rfl /- ne -/ @[reducible] def ne {α : Sort u} (a b : α) := ¬(a = b) infix ` ≠ `:50 := ne @[simp] lemma ne.def {α : Sort u} (a b : α) : a ≠ b = ¬ (a = b) := rfl namespace ne variable {α : Sort u} variables {a b : α} lemma intro (h : a = b → false) : a ≠ b := h lemma elim (h : a ≠ b) : a = b → false := h lemma irrefl (h : a ≠ a) : false := h rfl lemma symm (h : a ≠ b) : b ≠ a := assume (h₁ : b = a), h (h₁.symm) end ne lemma false_of_ne {α : Sort u} {a : α} : a ≠ a → false := ne.irrefl section variables {p : Prop} lemma ne_false_of_self : p → p ≠ false := assume (hp : p) (heq : p = false), heq ▸ hp lemma ne_true_of_not : ¬p → p ≠ true := assume (hnp : ¬p) (heq : p = true), (heq ▸ hnp) trivial lemma true_ne_false : ¬true = false := ne_false_of_self trivial end attribute [refl] heq.refl section variables {α β φ : Sort u} {a a' : α} {b b' : β} {c : φ} def heq.elim {α : Sort u} {a : α} {p : α → Sort v} {b : α} (h₁ : a == b) : p a → p b := eq.rec_on (eq_of_heq h₁) lemma heq.subst {p : ∀ T : Sort u, T → Prop} : a == b → p α a → p β b := heq.rec_on @[symm] lemma heq.symm (h : a == b) : b == a := heq.rec_on h (heq.refl a) lemma heq_of_eq (h : a = a') : a == a' := eq.subst h (heq.refl a) @[trans] lemma heq.trans (h₁ : a == b) (h₂ : b == c) : a == c := heq.subst h₂ h₁ @[trans] lemma heq_of_heq_of_eq (h₁ : a == b) (h₂ : b = b') : a == b' := heq.trans h₁ (heq_of_eq h₂) @[trans] lemma heq_of_eq_of_heq (h₁ : a = a') (h₂ : a' == b) : a == b := heq.trans (heq_of_eq h₁) h₂ lemma type_eq_of_heq (h : a == b) : α = β := heq.rec_on h (eq.refl α) end lemma eq_rec_heq {α : Sort u} {φ : α → Sort v} : ∀ {a a' : α} (h : a = a') (p : φ a), (eq.rec_on h p : φ a') == p | a _ rfl p := heq.refl p lemma heq_of_eq_rec_left {α : Sort u} {φ : α → Sort v} : ∀ {a a' : α} {p₁ : φ a} {p₂ : φ a'} (e : a = a') (h₂ : (eq.rec_on e p₁ : φ a') = p₂), p₁ == p₂ | a _ p₁ p₂ rfl h := eq.rec_on h (heq.refl p₁) lemma heq_of_eq_rec_right {α : Sort u} {φ : α → Sort v} : ∀ {a a' : α} {p₁ : φ a} {p₂ : φ a'} (e : a' = a) (h₂ : p₁ = eq.rec_on e p₂), p₁ == p₂ | a _ p₁ p₂ rfl h := have p₁ = p₂, from h, this ▸ heq.refl p₁ lemma of_heq_true {a : Prop} (h : a == true) : a := of_eq_true (eq_of_heq h) lemma eq_rec_compose : ∀ {α β φ : Sort u} (p₁ : β = φ) (p₂ : α = β) (a : α), (eq.rec_on p₁ (eq.rec_on p₂ a : β) : φ) = eq.rec_on (eq.trans p₂ p₁) a | α _ _ rfl rfl a := rfl lemma cast_heq : ∀ {α β : Sort u} (h : α = β) (a : α), cast h a == a | α _ rfl a := heq.refl a /- and -/ infixr ` /\ `:35 := and infixr ` ∧ `:35 := and variables {a b c d : Prop} lemma and.elim (h₁ : a ∧ b) (h₂ : a → b → c) : c := and.rec h₂ h₁ lemma and.swap : a ∧ b → b ∧ a := assume ⟨ha, hb⟩, ⟨hb, ha⟩ lemma and.symm : a ∧ b → b ∧ a := and.swap /- or -/ infixr ` \/ `:30 := or infixr ` ∨ `:30 := or namespace or lemma elim (h₁ : a ∨ b) (h₂ : a → c) (h₃ : b → c) : c := or.rec h₂ h₃ h₁ end or lemma non_contradictory_em (a : Prop) : ¬¬(a ∨ ¬a) := assume not_em : ¬(a ∨ ¬a), have neg_a : ¬a, from assume pos_a : a, absurd (or.inl pos_a) not_em, absurd (or.inr neg_a) not_em lemma or.swap : a ∨ b → b ∨ a := or.rec or.inr or.inl lemma or.symm : a ∨ b → b ∨ a := or.swap /- xor -/ def xor (a b : Prop) := (a ∧ ¬ b) ∨ (b ∧ ¬ a) /- iff -/ /-- `iff P Q`, with notation `P ↔ Q`, is the proposition asserting that `P` and `Q` are equivalent, that is, have the same truth value. -/ structure iff (a b : Prop) : Prop := intro :: (mp : a → b) (mpr : b → a) infix ` <-> `:20 := iff infix ` ↔ `:20 := iff lemma iff.elim : ((a → b) → (b → a) → c) → (a ↔ b) → c := iff.rec attribute [recursor 5] iff.elim lemma iff.elim_left : (a ↔ b) → a → b := iff.mp lemma iff.elim_right : (a ↔ b) → b → a := iff.mpr lemma iff_iff_implies_and_implies (a b : Prop) : (a ↔ b) ↔ (a → b) ∧ (b → a) := iff.intro (λ h, and.intro h.mp h.mpr) (λ h, iff.intro h.left h.right) @[refl] lemma iff.refl (a : Prop) : a ↔ a := iff.intro (assume h, h) (assume h, h) lemma iff.rfl {a : Prop} : a ↔ a := iff.refl a @[trans] lemma iff.trans (h₁ : a ↔ b) (h₂ : b ↔ c) : a ↔ c := iff.intro (assume ha, iff.mp h₂ (iff.mp h₁ ha)) (assume hc, iff.mpr h₁ (iff.mpr h₂ hc)) @[symm] lemma iff.symm (h : a ↔ b) : b ↔ a := iff.intro (iff.elim_right h) (iff.elim_left h) lemma iff.comm : (a ↔ b) ↔ (b ↔ a) := iff.intro iff.symm iff.symm lemma eq.to_iff {a b : Prop} (h : a = b) : a ↔ b := eq.rec_on h iff.rfl lemma neq_of_not_iff {a b : Prop} : ¬(a ↔ b) → a ≠ b := λ h₁ h₂, have a ↔ b, from eq.subst h₂ (iff.refl a), absurd this h₁ lemma not_iff_not_of_iff (h₁ : a ↔ b) : ¬a ↔ ¬b := iff.intro (assume (hna : ¬ a) (hb : b), hna (iff.elim_right h₁ hb)) (assume (hnb : ¬ b) (ha : a), hnb (iff.elim_left h₁ ha)) lemma of_iff_true (h : a ↔ true) : a := iff.mp (iff.symm h) trivial lemma not_of_iff_false : (a ↔ false) → ¬a := iff.mp lemma iff_true_intro (h : a) : a ↔ true := iff.intro (λ hl, trivial) (λ hr, h) lemma iff_false_intro (h : ¬a) : a ↔ false := iff.intro h (false.rec a) lemma not_non_contradictory_iff_absurd (a : Prop) : ¬¬¬a ↔ ¬a := iff.intro (λ (hl : ¬¬¬a) (ha : a), hl (non_contradictory_intro ha)) absurd lemma imp_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : (a → b) ↔ (c → d) := iff.intro (λ hab hc, iff.mp h₂ (hab (iff.mpr h₁ hc))) (λ hcd ha, iff.mpr h₂ (hcd (iff.mp h₁ ha))) lemma imp_congr_ctx (h₁ : a ↔ c) (h₂ : c → (b ↔ d)) : (a → b) ↔ (c → d) := iff.intro (λ hab hc, have ha : a, from iff.mpr h₁ hc, have hb : b, from hab ha, iff.mp (h₂ hc) hb) (λ hcd ha, have hc : c, from iff.mp h₁ ha, have hd : d, from hcd hc, iff.mpr (h₂ hc) hd) lemma imp_congr_right (h : a → (b ↔ c)) : (a → b) ↔ (a → c) := iff.intro (assume hab ha, iff.elim_left (h ha) (hab ha)) (assume hab ha, iff.elim_right (h ha) (hab ha)) lemma not_not_intro (ha : a) : ¬¬a := assume hna : ¬a, hna ha lemma not_of_not_not_not (h : ¬¬¬a) : ¬a := λ ha, absurd (not_not_intro ha) h @[simp] lemma not_true : (¬ true) ↔ false := iff_false_intro (not_not_intro trivial) @[simp] lemma not_false_iff : (¬ false) ↔ true := iff_true_intro not_false @[congr] lemma not_congr (h : a ↔ b) : ¬a ↔ ¬b := iff.intro (λ h₁ h₂, h₁ (iff.mpr h h₂)) (λ h₁ h₂, h₁ (iff.mp h h₂)) lemma ne_self_iff_false {α : Sort u} (a : α) : (not (a = a)) ↔ false := iff.intro false_of_ne false.elim @[simp] lemma eq_self_iff_true {α : Sort u} (a : α) : (a = a) ↔ true := iff_true_intro rfl lemma heq_self_iff_true {α : Sort u} (a : α) : (a == a) ↔ true := iff_true_intro (heq.refl a) @[simp] lemma iff_not_self (a : Prop) : (a ↔ ¬a) ↔ false := iff_false_intro (λ h, have h' : ¬a, from (λ ha, (iff.mp h ha) ha), h' (iff.mpr h h')) @[simp] lemma not_iff_self (a : Prop) : (¬a ↔ a) ↔ false := iff_false_intro (λ h, have h' : ¬a, from (λ ha, (iff.mpr h ha) ha), h' (iff.mp h h')) lemma true_iff_false : (true ↔ false) ↔ false := iff_false_intro (λ h, iff.mp h trivial) lemma false_iff_true : (false ↔ true) ↔ false := iff_false_intro (λ h, iff.mpr h trivial) lemma false_of_true_iff_false : (true ↔ false) → false := assume h, iff.mp h trivial lemma false_of_true_eq_false : (true = false) → false := assume h, h ▸ trivial lemma true_eq_false_of_false : false → (true = false) := false.elim lemma eq_comm {α : Sort u} {a b : α} : a = b ↔ b = a := ⟨eq.symm, eq.symm⟩ /- and simp rules -/ lemma and.imp (hac : a → c) (hbd : b → d) : a ∧ b → c ∧ d := assume ⟨ha, hb⟩, ⟨hac ha, hbd hb⟩ lemma and_implies (hac : a → c) (hbd : b → d) : a ∧ b → c ∧ d := and.imp hac hbd @[congr] lemma and_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : (a ∧ b) ↔ (c ∧ d) := iff.intro (and.imp (iff.mp h₁) (iff.mp h₂)) (and.imp (iff.mpr h₁) (iff.mpr h₂)) lemma and_congr_right (h : a → (b ↔ c)) : (a ∧ b) ↔ (a ∧ c) := iff.intro (assume ⟨ha, hb⟩, ⟨ha, iff.elim_left (h ha) hb⟩) (assume ⟨ha, hc⟩, ⟨ha, iff.elim_right (h ha) hc⟩) lemma and.comm : a ∧ b ↔ b ∧ a := iff.intro and.swap and.swap lemma and_comm (a b : Prop) : a ∧ b ↔ b ∧ a := and.comm lemma and.assoc : (a ∧ b) ∧ c ↔ a ∧ (b ∧ c) := iff.intro (assume ⟨⟨ha, hb⟩, hc⟩, ⟨ha, ⟨hb, hc⟩⟩) (assume ⟨ha, ⟨hb, hc⟩⟩, ⟨⟨ha, hb⟩, hc⟩) lemma and_assoc (a b : Prop) : (a ∧ b) ∧ c ↔ a ∧ (b ∧ c) := and.assoc lemma and.left_comm : a ∧ (b ∧ c) ↔ b ∧ (a ∧ c) := iff.trans (iff.symm and.assoc) (iff.trans (and_congr and.comm (iff.refl c)) and.assoc) lemma and_iff_left {a b : Prop} (hb : b) : (a ∧ b) ↔ a := iff.intro and.left (λ ha, ⟨ha, hb⟩) lemma and_iff_right {a b : Prop} (ha : a) : (a ∧ b) ↔ b := iff.intro and.right (and.intro ha) @[simp] lemma and_true (a : Prop) : a ∧ true ↔ a := and_iff_left trivial @[simp] lemma true_and (a : Prop) : true ∧ a ↔ a := and_iff_right trivial @[simp] lemma and_false (a : Prop) : a ∧ false ↔ false := iff_false_intro and.right @[simp] lemma false_and (a : Prop) : false ∧ a ↔ false := iff_false_intro and.left @[simp] lemma not_and_self (a : Prop) : (¬a ∧ a) ↔ false := iff_false_intro (λ h, and.elim h (λ h₁ h₂, absurd h₂ h₁)) @[simp] lemma and_not_self (a : Prop) : (a ∧ ¬a) ↔ false := iff_false_intro (assume ⟨h₁, h₂⟩, absurd h₁ h₂) @[simp] lemma and_self (a : Prop) : a ∧ a ↔ a := iff.intro and.left (assume h, ⟨h, h⟩) /- or simp rules -/ lemma or.imp (h₂ : a → c) (h₃ : b → d) : a ∨ b → c ∨ d := or.rec (λ h, or.inl (h₂ h)) (λ h, or.inr (h₃ h)) lemma or.imp_left (h : a → b) : a ∨ c → b ∨ c := or.imp h id lemma or.imp_right (h : a → b) : c ∨ a → c ∨ b := or.imp id h @[congr] lemma or_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : (a ∨ b) ↔ (c ∨ d) := iff.intro (or.imp (iff.mp h₁) (iff.mp h₂)) (or.imp (iff.mpr h₁) (iff.mpr h₂)) lemma or.comm : a ∨ b ↔ b ∨ a := iff.intro or.swap or.swap lemma or_comm (a b : Prop) : a ∨ b ↔ b ∨ a := or.comm lemma or.assoc : (a ∨ b) ∨ c ↔ a ∨ (b ∨ c) := iff.intro (or.rec (or.imp_right or.inl) (λ h, or.inr (or.inr h))) (or.rec (λ h, or.inl (or.inl h)) (or.imp_left or.inr)) lemma or_assoc (a b : Prop) : (a ∨ b) ∨ c ↔ a ∨ (b ∨ c) := or.assoc lemma or.left_comm : a ∨ (b ∨ c) ↔ b ∨ (a ∨ c) := iff.trans (iff.symm or.assoc) (iff.trans (or_congr or.comm (iff.refl c)) or.assoc) theorem or_iff_right_of_imp (ha : a → b) : (a ∨ b) ↔ b := iff.intro (or.rec ha id) or.inr theorem or_iff_left_of_imp (hb : b → a) : (a ∨ b) ↔ a := iff.intro (or.rec id hb) or.inl @[simp] lemma or_true (a : Prop) : a ∨ true ↔ true := iff_true_intro (or.inr trivial) @[simp] lemma true_or (a : Prop) : true ∨ a ↔ true := iff_true_intro (or.inl trivial) @[simp] lemma or_false (a : Prop) : a ∨ false ↔ a := iff.intro (or.rec id false.elim) or.inl @[simp] lemma false_or (a : Prop) : false ∨ a ↔ a := iff.trans or.comm (or_false a) @[simp] lemma or_self (a : Prop) : a ∨ a ↔ a := iff.intro (or.rec id id) or.inl lemma not_or {a b : Prop} : ¬ a → ¬ b → ¬ (a ∨ b) | hna hnb (or.inl ha) := absurd ha hna | hna hnb (or.inr hb) := absurd hb hnb /- or resolution rulse -/ lemma or.resolve_left {a b : Prop} (h : a ∨ b) (na : ¬ a) : b := or.elim h (λ ha, absurd ha na) id lemma or.neg_resolve_left {a b : Prop} (h : ¬ a ∨ b) (ha : a) : b := or.elim h (λ na, absurd ha na) id lemma or.resolve_right {a b : Prop} (h : a ∨ b) (nb : ¬ b) : a := or.elim h id (λ hb, absurd hb nb) lemma or.neg_resolve_right {a b : Prop} (h : a ∨ ¬ b) (hb : b) : a := or.elim h id (λ nb, absurd hb nb) /- iff simp rules -/ @[simp] lemma iff_true (a : Prop) : (a ↔ true) ↔ a := iff.intro (assume h, iff.mpr h trivial) iff_true_intro @[simp] lemma true_iff (a : Prop) : (true ↔ a) ↔ a := iff.trans iff.comm (iff_true a) @[simp] lemma iff_false (a : Prop) : (a ↔ false) ↔ ¬ a := iff.intro iff.mp iff_false_intro @[simp] lemma false_iff (a : Prop) : (false ↔ a) ↔ ¬ a := iff.trans iff.comm (iff_false a) @[simp] lemma iff_self (a : Prop) : (a ↔ a) ↔ true := iff_true_intro iff.rfl @[congr] lemma iff_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : (a ↔ b) ↔ (c ↔ d) := (iff_iff_implies_and_implies a b).trans ((and_congr (imp_congr h₁ h₂) (imp_congr h₂ h₁)).trans (iff_iff_implies_and_implies c d).symm) /- implies simp rule -/ @[simp] lemma implies_true_iff (α : Sort u) : (α → true) ↔ true := iff.intro (λ h, trivial) (λ ha h, trivial) lemma false_implies_iff (a : Prop) : (false → a) ↔ true := iff.intro (λ h, trivial) (λ ha h, false.elim h) theorem true_implies_iff (α : Prop) : (true → α) ↔ α := iff.intro (λ h, h trivial) (λ h h', h) /-- The existential quantifier. To prove a goal of the form `⊢ ∃ x, p x`, you can provide a witness `y` with the tactic `existsi y`. If you are working in a project that depends on mathlib, then we recommend the `use` tactic instead. You'll then be left with the goal `⊢ p y`. To extract a witness `x` and proof `hx : p x` from a hypothesis `h : ∃ x, p x`, use the tactic `cases h with x hx`. See also the mathlib tactics `obtain` and `rcases`. -/ inductive Exists {α : Sort u} (p : α → Prop) : Prop | intro (w : α) (h : p w) : Exists attribute [intro] Exists.intro notation `exists` binders `, ` r:(scoped P, Exists P) := r notation `∃` binders `, ` r:(scoped P, Exists P) := r /- This is a `def`, so that it can be used as pattern in the equation compiler. -/ @[pattern] def exists.intro {α : Sort u} {p : α → Prop} (w : α) (h : p w) : ∃ x, p x := ⟨w, h⟩ lemma exists.elim {α : Sort u} {p : α → Prop} {b : Prop} (h₁ : ∃ x, p x) (h₂ : ∀ (a : α), p a → b) : b := Exists.rec h₂ h₁ /- exists unique -/ def exists_unique {α : Sort u} (p : α → Prop) := ∃ x, p x ∧ ∀ y, p y → y = x notation `∃!` binders `, ` r:(scoped P, exists_unique P) := r @[intro] lemma exists_unique.intro {α : Sort u} {p : α → Prop} (w : α) (h₁ : p w) (h₂ : ∀ y, p y → y = w) : ∃! x, p x := exists.intro w ⟨h₁, h₂⟩ attribute [recursor 4] lemma exists_unique.elim {α : Sort u} {p : α → Prop} {b : Prop} (h₂ : ∃! x, p x) (h₁ : ∀ x, p x → (∀ y, p y → y = x) → b) : b := exists.elim h₂ (λ w hw, h₁ w (and.left hw) (and.right hw)) lemma exists_unique_of_exists_of_unique {α : Sort u} {p : α → Prop} (hex : ∃ x, p x) (hunique : ∀ y₁ y₂, p y₁ → p y₂ → y₁ = y₂) : ∃! x, p x := exists.elim hex (λ x px, exists_unique.intro x px (assume y, assume : p y, hunique y x this px)) lemma exists_of_exists_unique {α : Sort u} {p : α → Prop} (h : ∃! x, p x) : ∃ x, p x := exists.elim h (λ x hx, ⟨x, and.left hx⟩) lemma unique_of_exists_unique {α : Sort u} {p : α → Prop} (h : ∃! x, p x) {y₁ y₂ : α} (py₁ : p y₁) (py₂ : p y₂) : y₁ = y₂ := exists_unique.elim h (assume x, assume : p x, assume unique : ∀ y, p y → y = x, show y₁ = y₂, from eq.trans (unique _ py₁) (eq.symm (unique _ py₂))) /- exists, forall, exists unique congruences -/ @[congr] lemma forall_congr {α : Sort u} {p q : α → Prop} (h : ∀ a, (p a ↔ q a)) : (∀ a, p a) ↔ ∀ a, q a := iff.intro (λ p a, iff.mp (h a) (p a)) (λ q a, iff.mpr (h a) (q a)) lemma exists_imp_exists {α : Sort u} {p q : α → Prop} (h : ∀ a, (p a → q a)) (p : ∃ a, p a) : ∃ a, q a := exists.elim p (λ a hp, ⟨a, h a hp⟩) @[congr] lemma exists_congr {α : Sort u} {p q : α → Prop} (h : ∀ a, (p a ↔ q a)) : (Exists p) ↔ ∃ a, q a := iff.intro (exists_imp_exists (λ a, iff.mp (h a))) (exists_imp_exists (λ a, iff.mpr (h a))) @[congr] lemma exists_unique_congr {α : Sort u} {p₁ p₂ : α → Prop} (h : ∀ x, p₁ x ↔ p₂ x) : (exists_unique p₁) ↔ (∃! x, p₂ x) := -- exists_congr (λ x, and_congr (h x) (forall_congr (λ y, imp_congr (h y) iff.rfl))) lemma forall_not_of_not_exists {α : Sort u} {p : α → Prop} : ¬(∃ x, p x) → (∀ x, ¬p x) := λ hne x hp, hne ⟨x, hp⟩ /- decidable -/ def decidable.to_bool (p : Prop) [h : decidable p] : bool := decidable.cases_on h (λ h₁, bool.ff) (λ h₂, bool.tt) export decidable (is_true is_false to_bool) @[simp] lemma to_bool_true_eq_tt (h : decidable true) : @to_bool true h = tt := decidable.cases_on h (λ h, false.elim (iff.mp not_true h)) (λ _, rfl) @[simp] lemma to_bool_false_eq_ff (h : decidable false) : @to_bool false h = ff := decidable.cases_on h (λ h, rfl) (λ h, false.elim h) instance decidable.true : decidable true := is_true trivial instance decidable.false : decidable false := is_false not_false -- We use "dependent" if-then-else to be able to communicate the if-then-else condition -- to the branches @[inline] def dite {α : Sort u} (c : Prop) [h : decidable c] : (c → α) → (¬ c → α) → α := λ t e, decidable.rec_on h e t /- if-then-else -/ @[inline] def ite {α : Sort u} (c : Prop) [h : decidable c] (t e : α) : α := decidable.rec_on h (λ hnc, e) (λ hc, t) namespace decidable variables {p q : Prop} def rec_on_true [h : decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} (h₃ : p) (h₄ : h₁ h₃) : decidable.rec_on h h₂ h₁ := decidable.rec_on h (λ h, false.rec _ (h h₃)) (λ h, h₄) def rec_on_false [h : decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} (h₃ : ¬p) (h₄ : h₂ h₃) : decidable.rec_on h h₂ h₁ := decidable.rec_on h (λ h, h₄) (λ h, false.rec _ (h₃ h)) def by_cases {q : Sort u} [φ : decidable p] : (p → q) → (¬p → q) → q := dite _ /-- Law of Excluded Middle. -/ lemma em (p : Prop) [decidable p] : p ∨ ¬p := by_cases or.inl or.inr lemma by_contradiction [decidable p] (h : ¬p → false) : p := if h₁ : p then h₁ else false.rec _ (h h₁) lemma of_not_not [decidable p] : ¬ ¬ p → p := λ hnn, by_contradiction (λ hn, absurd hn hnn) lemma not_not_iff (p) [decidable p] : (¬ ¬ p) ↔ p := iff.intro of_not_not not_not_intro lemma not_and_iff_or_not (p q : Prop) [d₁ : decidable p] [d₂ : decidable q] : ¬ (p ∧ q) ↔ ¬ p ∨ ¬ q := iff.intro (λ h, match d₁ with | is_true h₁ := match d₂ with | is_true h₂ := absurd (and.intro h₁ h₂) h | is_false h₂ := or.inr h₂ end | is_false h₁ := or.inl h₁ end) (λ h ⟨hp, hq⟩, or.elim h (λ h, h hp) (λ h, h hq)) lemma not_or_iff_and_not (p q) [d₁ : decidable p] [d₂ : decidable q] : ¬ (p ∨ q) ↔ ¬ p ∧ ¬ q := iff.intro (λ h, match d₁ with | is_true h₁ := false.elim $ h (or.inl h₁) | is_false h₁ := match d₂ with | is_true h₂ := false.elim $ h (or.inr h₂) | is_false h₂ := ⟨h₁, h₂⟩ end end) (λ ⟨np, nq⟩ h, or.elim h np nq) end decidable section variables {p q : Prop} def decidable_of_decidable_of_iff (hp : decidable p) (h : p ↔ q) : decidable q := if hp : p then is_true (iff.mp h hp) else is_false (iff.mp (not_iff_not_of_iff h) hp) def decidable_of_decidable_of_eq (hp : decidable p) (h : p = q) : decidable q := decidable_of_decidable_of_iff hp h.to_iff protected def or.by_cases [decidable p] [decidable q] {α : Sort u} (h : p ∨ q) (h₁ : p → α) (h₂ : q → α) : α := if hp : p then h₁ hp else if hq : q then h₂ hq else false.rec _ (or.elim h hp hq) end section variables {p q : Prop} instance [decidable p] [decidable q] : decidable (p ∧ q) := if hp : p then if hq : q then is_true ⟨hp, hq⟩ else is_false (assume h : p ∧ q, hq (and.right h)) else is_false (assume h : p ∧ q, hp (and.left h)) instance [decidable p] [decidable q] : decidable (p ∨ q) := if hp : p then is_true (or.inl hp) else if hq : q then is_true (or.inr hq) else is_false (or.rec hp hq) instance [decidable p] : decidable (¬p) := if hp : p then is_false (absurd hp) else is_true hp instance implies.decidable [decidable p] [decidable q] : decidable (p → q) := if hp : p then if hq : q then is_true (assume h, hq) else is_false (assume h : p → q, absurd (h hp) hq) else is_true (assume h, absurd h hp) instance [decidable p] [decidable q] : decidable (p ↔ q) := if hp : p then if hq : q then is_true ⟨λ_, hq, λ_, hp⟩ else is_false $ λh, hq (h.1 hp) else if hq : q then is_false $ λh, hp (h.2 hq) else is_true $ ⟨λh, absurd h hp, λh, absurd h hq⟩ instance [decidable p] [decidable q] : decidable (xor p q) := if hp : p then if hq : q then is_false (or.rec (λ ⟨_, h⟩, h hq : ¬(p ∧ ¬ q)) (λ ⟨_, h⟩, h hp : ¬(q ∧ ¬ p))) else is_true $ or.inl ⟨hp, hq⟩ else if hq : q then is_true $ or.inr ⟨hq, hp⟩ else is_false (or.rec (λ ⟨h, _⟩, hp h : ¬(p ∧ ¬ q)) (λ ⟨h, _⟩, hq h : ¬(q ∧ ¬ p))) instance exists_prop_decidable {p} (P : p → Prop) [Dp : decidable p] [DP : ∀ h, decidable (P h)] : decidable (∃ h, P h) := if h : p then decidable_of_decidable_of_iff (DP h) ⟨λ h2, ⟨h, h2⟩, λ⟨h', h2⟩, h2⟩ else is_false (mt (λ⟨h, _⟩, h) h) instance forall_prop_decidable {p} (P : p → Prop) [Dp : decidable p] [DP : ∀ h, decidable (P h)] : decidable (∀ h, P h) := if h : p then decidable_of_decidable_of_iff (DP h) ⟨λ h2 _, h2, λal, al h⟩ else is_true (λ h2, absurd h2 h) end instance {α : Sort u} [decidable_eq α] (a b : α) : decidable (a ≠ b) := implies.decidable lemma bool.ff_ne_tt : ff = tt → false . def is_dec_eq {α : Sort u} (p : α → α → bool) : Prop := ∀ ⦃x y : α⦄, p x y = tt → x = y def is_dec_refl {α : Sort u} (p : α → α → bool) : Prop := ∀ x, p x x = tt open decidable instance : decidable_eq bool | ff ff := is_true rfl | ff tt := is_false bool.ff_ne_tt | tt ff := is_false (ne.symm bool.ff_ne_tt) | tt tt := is_true rfl def decidable_eq_of_bool_pred {α : Sort u} {p : α → α → bool} (h₁ : is_dec_eq p) (h₂ : is_dec_refl p) : decidable_eq α := assume x y : α, if hp : p x y = tt then is_true (h₁ hp) else is_false (assume hxy : x = y, absurd (h₂ y) (@eq.rec_on _ _ (λ z, ¬p z y = tt) _ hxy hp)) lemma decidable_eq_inl_refl {α : Sort u} [h : decidable_eq α] (a : α) : h a a = is_true (eq.refl a) := match (h a a) with | (is_true e) := rfl | (is_false n) := absurd rfl n end lemma decidable_eq_inr_neg {α : Sort u} [h : decidable_eq α] {a b : α} : Π n : a ≠ b, h a b = is_false n := assume n, match (h a b) with | (is_true e) := absurd e n | (is_false n₁) := proof_irrel n n₁ ▸ eq.refl (is_false n) end /- inhabited -/ class inhabited (α : Sort u) := (default [] : α) export inhabited (default) @[inline, irreducible] def arbitrary (α : Sort u) [inhabited α] : α := default α instance prop.inhabited : inhabited Prop := ⟨true⟩ instance pi.inhabited (α : Sort u) {β : α → Sort v} [Π x, inhabited (β x)] : inhabited (Π x, β x) := ⟨λ a, default (β a)⟩ instance : inhabited bool := ⟨ff⟩ instance : inhabited true := ⟨trivial⟩ class inductive nonempty (α : Sort u) : Prop | intro (val : α) : nonempty protected lemma nonempty.elim {α : Sort u} {p : Prop} (h₁ : nonempty α) (h₂ : α → p) : p := nonempty.rec h₂ h₁ @[priority 100] instance nonempty_of_inhabited {α : Sort u} [inhabited α] : nonempty α := ⟨default α⟩ lemma nonempty_of_exists {α : Sort u} {p : α → Prop} : (∃ x, p x) → nonempty α | ⟨w, h⟩ := ⟨w⟩ /- subsingleton -/ class inductive subsingleton (α : Sort u) : Prop | intro (h : ∀ a b : α, a = b) : subsingleton protected lemma subsingleton.elim {α : Sort u} [h : subsingleton α] : ∀ (a b : α), a = b := subsingleton.rec (λ p, p) h protected lemma subsingleton.helim {α β : Sort u} [h : subsingleton α] (h : α = β) : ∀ (a : α) (b : β), a == b := eq.rec_on h (λ a b : α, heq_of_eq (subsingleton.elim a b)) instance subsingleton_prop (p : Prop) : subsingleton p := ⟨λ a b, proof_irrel a b⟩ instance (p : Prop) : subsingleton (decidable p) := subsingleton.intro (λ d₁, match d₁ with | (is_true t₁) := (λ d₂, match d₂ with | (is_true t₂) := eq.rec_on (proof_irrel t₁ t₂) rfl | (is_false f₂) := absurd t₁ f₂ end) | (is_false f₁) := (λ d₂, match d₂ with | (is_true t₂) := absurd t₂ f₁ | (is_false f₂) := eq.rec_on (proof_irrel f₁ f₂) rfl end) end) protected lemma rec_subsingleton {p : Prop} [h : decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} [h₃ : Π (h : p), subsingleton (h₁ h)] [h₄ : Π (h : ¬p), subsingleton (h₂ h)] : subsingleton (decidable.rec_on h h₂ h₁) := match h with | (is_true h) := h₃ h | (is_false h) := h₄ h end lemma if_pos {c : Prop} [h : decidable c] (hc : c) {α : Sort u} {t e : α} : (ite c t e) = t := match h with | (is_true hc) := rfl | (is_false hnc) := absurd hc hnc end lemma if_neg {c : Prop} [h : decidable c] (hnc : ¬c) {α : Sort u} {t e : α} : (ite c t e) = e := match h with | (is_true hc) := absurd hc hnc | (is_false hnc) := rfl end @[simp] lemma if_t_t (c : Prop) [h : decidable c] {α : Sort u} (t : α) : (ite c t t) = t := match h with | (is_true hc) := rfl | (is_false hnc) := rfl end lemma implies_of_if_pos {c t e : Prop} [decidable c] (h : ite c t e) : c → t := assume hc, eq.rec_on (if_pos hc : ite c t e = t) h lemma implies_of_if_neg {c t e : Prop} [decidable c] (h : ite c t e) : ¬c → e := assume hnc, eq.rec_on (if_neg hnc : ite c t e = e) h lemma if_ctx_congr {α : Sort u} {b c : Prop} [dec_b : decidable b] [dec_c : decidable c] {x y u v : α} (h_c : b ↔ c) (h_t : c → x = u) (h_e : ¬c → y = v) : ite b x y = ite c u v := match dec_b, dec_c with | (is_false h₁), (is_false h₂) := h_e h₂ | (is_true h₁), (is_true h₂) := h_t h₂ | (is_false h₁), (is_true h₂) := absurd h₂ (iff.mp (not_iff_not_of_iff h_c) h₁) | (is_true h₁), (is_false h₂) := absurd h₁ (iff.mpr (not_iff_not_of_iff h_c) h₂) end @[congr] lemma if_congr {α : Sort u} {b c : Prop} [dec_b : decidable b] [dec_c : decidable c] {x y u v : α} (h_c : b ↔ c) (h_t : x = u) (h_e : y = v) : ite b x y = ite c u v := @if_ctx_congr α b c dec_b dec_c x y u v h_c (λ h, h_t) (λ h, h_e) @[simp] lemma if_true {α : Sort u} {h : decidable true} (t e : α) : (@ite α true h t e) = t := if_pos trivial @[simp] lemma if_false {α : Sort u} {h : decidable false} (t e : α) : (@ite α false h t e) = e := if_neg not_false lemma if_ctx_congr_prop {b c x y u v : Prop} [dec_b : decidable b] [dec_c : decidable c] (h_c : b ↔ c) (h_t : c → (x ↔ u)) (h_e : ¬c → (y ↔ v)) : ite b x y ↔ ite c u v := match dec_b, dec_c with | (is_false h₁), (is_false h₂) := h_e h₂ | (is_true h₁), (is_true h₂) := h_t h₂ | (is_false h₁), (is_true h₂) := absurd h₂ (iff.mp (not_iff_not_of_iff h_c) h₁) | (is_true h₁), (is_false h₂) := absurd h₁ (iff.mpr (not_iff_not_of_iff h_c) h₂) end @[congr] lemma if_congr_prop {b c x y u v : Prop} [dec_b : decidable b] [dec_c : decidable c] (h_c : b ↔ c) (h_t : x ↔ u) (h_e : y ↔ v) : ite b x y ↔ ite c u v := if_ctx_congr_prop h_c (λ h, h_t) (λ h, h_e) lemma if_ctx_simp_congr_prop {b c x y u v : Prop} [dec_b : decidable b] (h_c : b ↔ c) (h_t : c → (x ↔ u)) (h_e : ¬c → (y ↔ v)) : ite b x y ↔ (@ite Prop c (decidable_of_decidable_of_iff dec_b h_c) u v) := @if_ctx_congr_prop b c x y u v dec_b (decidable_of_decidable_of_iff dec_b h_c) h_c h_t h_e @[congr] lemma if_simp_congr_prop {b c x y u v : Prop} [dec_b : decidable b] (h_c : b ↔ c) (h_t : x ↔ u) (h_e : y ↔ v) : ite b x y ↔ (@ite Prop c (decidable_of_decidable_of_iff dec_b h_c) u v) := @if_ctx_simp_congr_prop b c x y u v dec_b h_c (λ h, h_t) (λ h, h_e) @[simp] lemma dif_pos {c : Prop} [h : decidable c] (hc : c) {α : Sort u} {t : c → α} {e : ¬ c → α} : dite c t e = t hc := match h with | (is_true hc) := rfl | (is_false hnc) := absurd hc hnc end @[simp] lemma dif_neg {c : Prop} [h : decidable c] (hnc : ¬c) {α : Sort u} {t : c → α} {e : ¬ c → α} : dite c t e = e hnc := match h with | (is_true hc) := absurd hc hnc | (is_false hnc) := rfl end @[congr] lemma dif_ctx_congr {α : Sort u} {b c : Prop} [dec_b : decidable b] [dec_c : decidable c] {x : b → α} {u : c → α} {y : ¬b → α} {v : ¬c → α} (h_c : b ↔ c) (h_t : ∀ (h : c), x (iff.mpr h_c h) = u h) (h_e : ∀ (h : ¬c), y (iff.mpr (not_iff_not_of_iff h_c) h) = v h) : (@dite α b dec_b x y) = (@dite α c dec_c u v) := match dec_b, dec_c with | (is_false h₁), (is_false h₂) := h_e h₂ | (is_true h₁), (is_true h₂) := h_t h₂ | (is_false h₁), (is_true h₂) := absurd h₂ (iff.mp (not_iff_not_of_iff h_c) h₁) | (is_true h₁), (is_false h₂) := absurd h₁ (iff.mpr (not_iff_not_of_iff h_c) h₂) end lemma dif_ctx_simp_congr {α : Sort u} {b c : Prop} [dec_b : decidable b] {x : b → α} {u : c → α} {y : ¬b → α} {v : ¬c → α} (h_c : b ↔ c) (h_t : ∀ (h : c), x (iff.mpr h_c h) = u h) (h_e : ∀ (h : ¬c), y (iff.mpr (not_iff_not_of_iff h_c) h) = v h) : (@dite α b dec_b x y) = (@dite α c (decidable_of_decidable_of_iff dec_b h_c) u v) := @dif_ctx_congr α b c dec_b (decidable_of_decidable_of_iff dec_b h_c) x u y v h_c h_t h_e -- Remark: dite and ite are "defally equal" when we ignore the proofs. lemma dif_eq_if (c : Prop) [h : decidable c] {α : Sort u} (t : α) (e : α) : dite c (λ h, t) (λ h, e) = ite c t e := match h with | (is_true hc) := rfl | (is_false hnc) := rfl end instance {c t e : Prop} [d_c : decidable c] [d_t : decidable t] [d_e : decidable e] : decidable (if c then t else e) := match d_c with | (is_true hc) := d_t | (is_false hc) := d_e end instance {c : Prop} {t : c → Prop} {e : ¬c → Prop} [d_c : decidable c] [d_t : ∀ h, decidable (t h)] [d_e : ∀ h, decidable (e h)] : decidable (if h : c then t h else e h) := match d_c with | (is_true hc) := d_t hc | (is_false hc) := d_e hc end def as_true (c : Prop) [decidable c] : Prop := if c then true else false def as_false (c : Prop) [decidable c] : Prop := if c then false else true lemma of_as_true {c : Prop} [h₁ : decidable c] (h₂ : as_true c) : c := match h₁, h₂ with | (is_true h_c), h₂ := h_c | (is_false h_c), h₂ := false.elim h₂ end /-- Universe lifting operation -/ structure {r s} ulift (α : Type s) : Type (max s r) := up :: (down : α) namespace ulift /- Bijection between α and ulift.{v} α -/ lemma up_down {α : Type u} : ∀ (b : ulift.{v} α), up (down b) = b | (up a) := rfl lemma down_up {α : Type u} (a : α) : down (up.{v} a) = a := rfl end ulift /-- Universe lifting operation from Sort to Type -/ structure plift (α : Sort u) : Type u := up :: (down : α) namespace plift /- Bijection between α and plift α -/ lemma up_down {α : Sort u} : ∀ (b : plift α), up (down b) = b | (up a) := rfl lemma down_up {α : Sort u} (a : α) : down (up a) = a := rfl end plift /- Equalities for rewriting let-expressions -/ lemma let_value_eq {α : Sort u} {β : Sort v} {a₁ a₂ : α} (b : α → β) : a₁ = a₂ → (let x : α := a₁ in b x) = (let x : α := a₂ in b x) := λ h, eq.rec_on h rfl lemma let_value_heq {α : Sort v} {β : α → Sort u} {a₁ a₂ : α} (b : Π x : α, β x) : a₁ = a₂ → (let x : α := a₁ in b x) == (let x : α := a₂ in b x) := λ h, eq.rec_on h (heq.refl (b a₁)) lemma let_body_eq {α : Sort v} {β : α → Sort u} (a : α) {b₁ b₂ : Π x : α, β x} : (∀ x, b₁ x = b₂ x) → (let x : α := a in b₁ x) = (let x : α := a in b₂ x) := λ h, h a lemma let_eq {α : Sort v} {β : Sort u} {a₁ a₂ : α} {b₁ b₂ : α → β} : a₁ = a₂ → (∀ x, b₁ x = b₂ x) → (let x : α := a₁ in b₁ x) = (let x : α := a₂ in b₂ x) := λ h₁ h₂, eq.rec_on h₁ (h₂ a₁) section relation variables {α : Sort u} {β : Sort v} (r : β → β → Prop) local infix `≺`:50 := r def reflexive := ∀ x, x ≺ x def symmetric := ∀ ⦃x y⦄, x ≺ y → y ≺ x def transitive := ∀ ⦃x y z⦄, x ≺ y → y ≺ z → x ≺ z def equivalence := reflexive r ∧ symmetric r ∧ transitive r def total := ∀ x y, x ≺ y ∨ y ≺ x lemma mk_equivalence (rfl : reflexive r) (symm : symmetric r) (trans : transitive r) : equivalence r := ⟨rfl, symm, trans⟩ def irreflexive := ∀ x, ¬ x ≺ x def anti_symmetric := ∀ ⦃x y⦄, x ≺ y → y ≺ x → x = y def empty_relation := λ a₁ a₂ : α, false def subrelation (q r : β → β → Prop) := ∀ ⦃x y⦄, q x y → r x y def inv_image (f : α → β) : α → α → Prop := λ a₁ a₂, f a₁ ≺ f a₂ lemma inv_image.trans (f : α → β) (h : transitive r) : transitive (inv_image r f) := λ (a₁ a₂ a₃ : α) (h₁ : inv_image r f a₁ a₂) (h₂ : inv_image r f a₂ a₃), h h₁ h₂ lemma inv_image.irreflexive (f : α → β) (h : irreflexive r) : irreflexive (inv_image r f) := λ (a : α) (h₁ : inv_image r f a a), h (f a) h₁ inductive tc {α : Sort u} (r : α → α → Prop) : α → α → Prop | base : ∀ a b, r a b → tc a b | trans : ∀ a b c, tc a b → tc b c → tc a c end relation section binary variables {α : Type u} {β : Type v} variable f : α → α → α variable inv : α → α variable one : α local notation a * b := f a b local notation a ⁻¹ := inv a variable g : α → α → α local notation a + b := g a b def commutative := ∀ a b, a * b = b * a def associative := ∀ a b c, (a * b) * c = a * (b * c) def left_identity := ∀ a, one * a = a def right_identity := ∀ a, a * one = a def right_inverse := ∀ a, a * a⁻¹ = one def left_cancelative := ∀ a b c, a * b = a * c → b = c def right_cancelative := ∀ a b c, a * b = c * b → a = c def left_distributive := ∀ a b c, a * (b + c) = a * b + a * c def right_distributive := ∀ a b c, (a + b) * c = a * c + b * c def right_commutative (h : β → α → β) := ∀ b a₁ a₂, h (h b a₁) a₂ = h (h b a₂) a₁ def left_commutative (h : α → β → β) := ∀ a₁ a₂ b, h a₁ (h a₂ b) = h a₂ (h a₁ b) lemma left_comm : commutative f → associative f → left_commutative f := assume hcomm hassoc, assume a b c, calc a*(b*c) = (a*b)*c : eq.symm (hassoc a b c) ... = (b*a)*c : hcomm a b ▸ rfl ... = b*(a*c) : hassoc b a c lemma right_comm : commutative f → associative f → right_commutative f := assume hcomm hassoc, assume a b c, calc (a*b)*c = a*(b*c) : hassoc a b c ... = a*(c*b) : hcomm b c ▸ rfl ... = (a*c)*b : eq.symm (hassoc a c b) end binary
43f32555d0bf42fb6f599c5057b7c842c5ac838d
0c1546a496eccfb56620165cad015f88d56190c5
/tests/lean/def2.lean
a0e957bf6e85311428316865bd84c2f3a4b56be2
[ "Apache-2.0" ]
permissive
Solertis/lean
491e0939957486f664498fbfb02546e042699958
84188c5aa1673fdf37a082b2de8562dddf53df3f
refs/heads/master
1,610,174,257,606
1,486,263,620,000
1,486,263,620,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
130
lean
axiom val : nat definition foo : nat := val noncomputable definition foo2 : nat := val noncomputable definition bla : nat := 2
83b019efbe5b3d148200db6cbe20babada4fe0a6
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/polynomial/degree/definitions.lean
87273d4ba7f5fbdb0624106bbab0dd348799d0f4
[ "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
49,046
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.nat.with_bot import data.polynomial.induction import data.polynomial.monomial /-! # Theory of univariate polynomials The definitions include `degree`, `monic`, `leading_coeff` Results include - `degree_mul` : The degree of the product is the sum of degrees - `leading_coeff_add_of_degree_eq` and `leading_coeff_add_of_degree_lt` : The leading_coefficient of a sum is determined by the leading coefficients and degrees -/ noncomputable theory open finsupp finset open_locale big_operators classical polynomial namespace polynomial universes u v variables {R : Type u} {S : Type v} {a b c d : R} {n m : ℕ} section semiring variables [semiring R] {p q r : R[X]} /-- `degree p` is the degree of the polynomial `p`, i.e. the largest `X`-exponent in `p`. `degree p = some n` when `p ≠ 0` and `n` is the highest power of `X` that appears in `p`, otherwise `degree 0 = ⊥`. -/ def degree (p : R[X]) : with_bot ℕ := p.support.max lemma degree_lt_wf : well_founded (λp q : R[X], degree p < degree q) := inv_image.wf degree (with_bot.well_founded_lt nat.lt_wf) instance : has_well_founded R[X] := ⟨_, degree_lt_wf⟩ /-- `nat_degree p` forces `degree p` to ℕ, by defining nat_degree 0 = 0. -/ def nat_degree (p : R[X]) : ℕ := (degree p).get_or_else 0 /-- `leading_coeff p` gives the coefficient of the highest power of `X` in `p`-/ def leading_coeff (p : R[X]) : R := coeff p (nat_degree p) /-- a polynomial is `monic` if its leading coefficient is 1 -/ def monic (p : R[X]) := leading_coeff p = (1 : R) @[nontriviality] lemma monic_of_subsingleton [subsingleton R] (p : R[X]) : monic p := subsingleton.elim _ _ lemma monic.def : monic p ↔ leading_coeff p = 1 := iff.rfl instance monic.decidable [decidable_eq R] : decidable (monic p) := by unfold monic; apply_instance @[simp] lemma monic.leading_coeff {p : R[X]} (hp : p.monic) : leading_coeff p = 1 := hp lemma monic.coeff_nat_degree {p : R[X]} (hp : p.monic) : p.coeff p.nat_degree = 1 := hp @[simp] lemma degree_zero : degree (0 : R[X]) = ⊥ := rfl @[simp] lemma nat_degree_zero : nat_degree (0 : R[X]) = 0 := rfl @[simp] lemma coeff_nat_degree : coeff p (nat_degree p) = leading_coeff p := rfl lemma degree_eq_bot : degree p = ⊥ ↔ p = 0 := ⟨λ h, support_eq_empty.1 (finset.max_eq_bot.1 h), λ h, h.symm ▸ rfl⟩ @[nontriviality] lemma degree_of_subsingleton [subsingleton R] : degree p = ⊥ := by rw [subsingleton.elim p 0, degree_zero] @[nontriviality] lemma nat_degree_of_subsingleton [subsingleton R] : nat_degree p = 0 := by rw [subsingleton.elim p 0, nat_degree_zero] lemma degree_eq_nat_degree (hp : p ≠ 0) : degree p = (nat_degree p : with_bot ℕ) := let ⟨n, hn⟩ := not_forall.1 (mt option.eq_none_iff_forall_not_mem.2 (mt degree_eq_bot.1 hp)) in have hn : degree p = some n := not_not.1 hn, by rw [nat_degree, hn]; refl lemma degree_eq_iff_nat_degree_eq {p : R[X]} {n : ℕ} (hp : p ≠ 0) : p.degree = n ↔ p.nat_degree = n := by rw [degree_eq_nat_degree hp, with_bot.coe_eq_coe] lemma degree_eq_iff_nat_degree_eq_of_pos {p : R[X]} {n : ℕ} (hn : 0 < n) : p.degree = n ↔ p.nat_degree = n := begin split, { intro H, rwa ← degree_eq_iff_nat_degree_eq, rintro rfl, rw degree_zero at H, exact option.no_confusion H }, { intro H, rwa degree_eq_iff_nat_degree_eq, rintro rfl, rw nat_degree_zero at H, rw H at hn, exact lt_irrefl _ hn } end lemma nat_degree_eq_of_degree_eq_some {p : R[X]} {n : ℕ} (h : degree p = n) : nat_degree p = n := have hp0 : p ≠ 0, from λ hp0, by rw hp0 at h; exact option.no_confusion h, option.some_inj.1 $ show (nat_degree p : with_bot ℕ) = n, by rwa [← degree_eq_nat_degree hp0] @[simp] lemma degree_le_nat_degree : degree p ≤ nat_degree p := with_bot.gi_get_or_else_bot.gc.le_u_l _ lemma nat_degree_eq_of_degree_eq [semiring S] {q : S[X]} (h : degree p = degree q) : nat_degree p = nat_degree q := by unfold nat_degree; rw h lemma le_degree_of_ne_zero (h : coeff p n ≠ 0) : (n : with_bot ℕ) ≤ degree p := show @has_le.le (with_bot ℕ) _ (some n : with_bot ℕ) (p.support.sup some : with_bot ℕ), from finset.le_sup (mem_support_iff.2 h) lemma le_nat_degree_of_ne_zero (h : coeff p n ≠ 0) : n ≤ nat_degree p := begin rw [← with_bot.coe_le_coe, ← degree_eq_nat_degree], exact le_degree_of_ne_zero h, { assume h, subst h, exact h rfl } end lemma le_nat_degree_of_mem_supp (a : ℕ) : a ∈ p.support → a ≤ nat_degree p:= le_nat_degree_of_ne_zero ∘ mem_support_iff.mp lemma degree_eq_of_le_of_coeff_ne_zero (pn : p.degree ≤ n) (p1 : p.coeff n ≠ 0) : p.degree = n := pn.antisymm (le_degree_of_ne_zero p1) lemma nat_degree_eq_of_le_of_coeff_ne_zero (pn : p.nat_degree ≤ n) (p1 : p.coeff n ≠ 0) : p.nat_degree = n := pn.antisymm (le_nat_degree_of_ne_zero p1) lemma degree_mono [semiring S] {f : R[X]} {g : S[X]} (h : f.support ⊆ g.support) : f.degree ≤ g.degree := finset.sup_mono h lemma supp_subset_range (h : nat_degree p < m) : p.support ⊆ finset.range m := λ n hn, mem_range.2 $ (le_nat_degree_of_mem_supp _ hn).trans_lt h lemma supp_subset_range_nat_degree_succ : p.support ⊆ finset.range (nat_degree p + 1) := supp_subset_range (nat.lt_succ_self _) lemma degree_le_degree (h : coeff q (nat_degree p) ≠ 0) : degree p ≤ degree q := begin by_cases hp : p = 0, { rw hp, exact bot_le }, { rw degree_eq_nat_degree hp, exact le_degree_of_ne_zero h } end lemma degree_ne_of_nat_degree_ne {n : ℕ} : p.nat_degree ≠ n → degree p ≠ n := mt $ λ h, by rw [nat_degree, h, option.get_or_else_coe] theorem nat_degree_le_iff_degree_le {n : ℕ} : nat_degree p ≤ n ↔ degree p ≤ n := with_bot.get_or_else_bot_le_iff lemma nat_degree_lt_iff_degree_lt (hp : p ≠ 0) : p.nat_degree < n ↔ p.degree < ↑n := with_bot.get_or_else_bot_lt_iff $ degree_eq_bot.not.mpr hp alias nat_degree_le_iff_degree_le ↔ .. lemma nat_degree_le_nat_degree [semiring S] {q : S[X]} (hpq : p.degree ≤ q.degree) : p.nat_degree ≤ q.nat_degree := with_bot.gi_get_or_else_bot.gc.monotone_l hpq @[simp] lemma degree_C (ha : a ≠ 0) : degree (C a) = (0 : with_bot ℕ) := by rw [degree, ← monomial_zero_left, support_monomial 0 ha, max_eq_sup_coe, sup_singleton, with_bot.coe_zero] lemma degree_C_le : degree (C a) ≤ 0 := begin by_cases h : a = 0, { rw [h, C_0], exact bot_le }, { rw [degree_C h], exact le_rfl } end lemma degree_C_lt : degree (C a) < 1 := degree_C_le.trans_lt $ with_bot.coe_lt_coe.mpr zero_lt_one lemma degree_one_le : degree (1 : R[X]) ≤ (0 : with_bot ℕ) := by rw [← C_1]; exact degree_C_le @[simp] lemma nat_degree_C (a : R) : nat_degree (C a) = 0 := begin by_cases ha : a = 0, { have : C a = 0, { rw [ha, C_0] }, rw [nat_degree, degree_eq_bot.2 this], refl }, { rw [nat_degree, degree_C ha], refl } end @[simp] lemma nat_degree_one : nat_degree (1 : R[X]) = 0 := nat_degree_C 1 @[simp] lemma nat_degree_nat_cast (n : ℕ) : nat_degree (n : R[X]) = 0 := by simp only [←C_eq_nat_cast, nat_degree_C] @[simp] lemma degree_monomial (n : ℕ) (ha : a ≠ 0) : degree (monomial n a) = n := by rw [degree, support_monomial n ha]; refl @[simp] lemma degree_C_mul_X_pow (n : ℕ) (ha : a ≠ 0) : degree (C a * X ^ n) = n := by rw [← monomial_eq_C_mul_X, degree_monomial n ha] lemma degree_C_mul_X (ha : a ≠ 0) : degree (C a * X) = 1 := by simpa only [pow_one] using degree_C_mul_X_pow 1 ha lemma degree_monomial_le (n : ℕ) (a : R) : degree (monomial n a) ≤ n := if h : a = 0 then by rw [h, (monomial n).map_zero]; exact bot_le else le_of_eq (degree_monomial n h) lemma degree_C_mul_X_pow_le (n : ℕ) (a : R) : degree (C a * X ^ n) ≤ n := by { rw C_mul_X_pow_eq_monomial, apply degree_monomial_le } lemma degree_C_mul_X_le (a : R) : degree (C a * X) ≤ 1 := by simpa only [pow_one] using degree_C_mul_X_pow_le 1 a @[simp] lemma nat_degree_C_mul_X_pow (n : ℕ) (a : R) (ha : a ≠ 0) : nat_degree (C a * X ^ n) = n := nat_degree_eq_of_degree_eq_some (degree_C_mul_X_pow n ha) @[simp] lemma nat_degree_C_mul_X (a : R) (ha : a ≠ 0) : nat_degree (C a * X) = 1 := by simpa only [pow_one] using nat_degree_C_mul_X_pow 1 a ha @[simp] lemma nat_degree_monomial [decidable_eq R] (i : ℕ) (r : R) : nat_degree (monomial i r) = if r = 0 then 0 else i := begin split_ifs with hr, { simp [hr] }, { rw [← C_mul_X_pow_eq_monomial, nat_degree_C_mul_X_pow i r hr] } end lemma nat_degree_monomial_le (a : R) {m : ℕ} : (monomial m a).nat_degree ≤ m := begin rw polynomial.nat_degree_monomial, split_ifs, exacts [nat.zero_le _, rfl.le], end lemma nat_degree_monomial_eq (i : ℕ) {r : R} (r0 : r ≠ 0) : (monomial i r).nat_degree = i := eq.trans (nat_degree_monomial _ _) (if_neg r0) lemma coeff_eq_zero_of_degree_lt (h : degree p < n) : coeff p n = 0 := not_not.1 (mt le_degree_of_ne_zero (not_le_of_gt h)) lemma coeff_eq_zero_of_nat_degree_lt {p : R[X]} {n : ℕ} (h : p.nat_degree < n) : p.coeff n = 0 := begin apply coeff_eq_zero_of_degree_lt, by_cases hp : p = 0, { subst hp, exact with_bot.bot_lt_coe n }, { rwa [degree_eq_nat_degree hp, with_bot.coe_lt_coe] } end @[simp] lemma coeff_nat_degree_succ_eq_zero {p : R[X]} : p.coeff (p.nat_degree + 1) = 0 := coeff_eq_zero_of_nat_degree_lt (lt_add_one _) -- We need the explicit `decidable` argument here because an exotic one shows up in a moment! lemma ite_le_nat_degree_coeff (p : R[X]) (n : ℕ) (I : decidable (n < 1 + nat_degree p)) : @ite _ (n < 1 + nat_degree p) I (coeff p n) 0 = coeff p n := begin split_ifs, { refl }, { exact (coeff_eq_zero_of_nat_degree_lt (not_le.1 (λ w, h (nat.lt_one_add_iff.2 w)))).symm, } end lemma as_sum_support (p : R[X]) : p = ∑ i in p.support, monomial i (p.coeff i) := (sum_monomial_eq p).symm lemma as_sum_support_C_mul_X_pow (p : R[X]) : p = ∑ i in p.support, C (p.coeff i) * X^i := trans p.as_sum_support $ by simp only [C_mul_X_pow_eq_monomial] /-- We can reexpress a sum over `p.support` as a sum over `range n`, for any `n` satisfying `p.nat_degree < n`. -/ lemma sum_over_range' [add_comm_monoid S] (p : R[X]) {f : ℕ → R → S} (h : ∀ n, f n 0 = 0) (n : ℕ) (w : p.nat_degree < n) : p.sum f = ∑ (a : ℕ) in range n, f a (coeff p a) := begin rcases p, have := supp_subset_range w, simp only [polynomial.sum, support, coeff, nat_degree, degree] at ⊢ this, exact finsupp.sum_of_support_subset _ this _ (λ n hn, h n) end /-- We can reexpress a sum over `p.support` as a sum over `range (p.nat_degree + 1)`. -/ lemma sum_over_range [add_comm_monoid S] (p : R[X]) {f : ℕ → R → S} (h : ∀ n, f n 0 = 0) : p.sum f = ∑ (a : ℕ) in range (p.nat_degree + 1), f a (coeff p a) := sum_over_range' p h (p.nat_degree + 1) (lt_add_one _) -- TODO this is essentially a duplicate of `sum_over_range`, and should be removed. lemma sum_fin [add_comm_monoid S] (f : ℕ → R → S) (hf : ∀ i, f i 0 = 0) {n : ℕ} {p : R[X]} (hn : p.degree < n) : ∑ (i : fin n), f i (p.coeff i) = p.sum f := begin by_cases hp : p = 0, { rw [hp, sum_zero_index, finset.sum_eq_zero], intros i _, exact hf i }, rw [sum_over_range' _ hf n ((nat_degree_lt_iff_degree_lt hp).mpr hn), fin.sum_univ_eq_sum_range (λ i, f i (p.coeff i))], end lemma as_sum_range' (p : R[X]) (n : ℕ) (w : p.nat_degree < n) : p = ∑ i in range n, monomial i (coeff p i) := p.sum_monomial_eq.symm.trans $ p.sum_over_range' monomial_zero_right _ w lemma as_sum_range (p : R[X]) : p = ∑ i in range (p.nat_degree + 1), monomial i (coeff p i) := p.sum_monomial_eq.symm.trans $ p.sum_over_range $ monomial_zero_right lemma as_sum_range_C_mul_X_pow (p : R[X]) : p = ∑ i in range (p.nat_degree + 1), C (coeff p i) * X ^ i := p.as_sum_range.trans $ by simp only [C_mul_X_pow_eq_monomial] lemma coeff_ne_zero_of_eq_degree (hn : degree p = n) : coeff p n ≠ 0 := λ h, mem_support_iff.mp (mem_of_max hn) h lemma eq_X_add_C_of_degree_le_one (h : degree p ≤ 1) : p = C (p.coeff 1) * X + C (p.coeff 0) := ext (λ n, nat.cases_on n (by simp) (λ n, nat.cases_on n (by simp [coeff_C]) (λ m, have degree p < m.succ.succ, from lt_of_le_of_lt h dec_trivial, by simp [coeff_eq_zero_of_degree_lt this, coeff_C, nat.succ_ne_zero, coeff_X, nat.succ_inj', @eq_comm ℕ 0]))) lemma eq_X_add_C_of_degree_eq_one (h : degree p = 1) : p = C (p.leading_coeff) * X + C (p.coeff 0) := (eq_X_add_C_of_degree_le_one (show degree p ≤ 1, from h ▸ le_rfl)).trans (by simp [leading_coeff, nat_degree_eq_of_degree_eq_some h]) lemma eq_X_add_C_of_nat_degree_le_one (h : nat_degree p ≤ 1) : p = C (p.coeff 1) * X + C (p.coeff 0) := eq_X_add_C_of_degree_le_one $ degree_le_of_nat_degree_le h lemma exists_eq_X_add_C_of_nat_degree_le_one (h : nat_degree p ≤ 1) : ∃ a b, p = C a * X + C b := ⟨p.coeff 1, p.coeff 0, eq_X_add_C_of_nat_degree_le_one h⟩ theorem degree_X_pow_le (n : ℕ) : degree (X^n : R[X]) ≤ n := by simpa only [C_1, one_mul] using degree_C_mul_X_pow_le n (1:R) theorem degree_X_le : degree (X : R[X]) ≤ 1 := degree_monomial_le _ _ lemma nat_degree_X_le : (X : R[X]).nat_degree ≤ 1 := nat_degree_le_of_degree_le degree_X_le lemma mem_support_C_mul_X_pow {n a : ℕ} {c : R} (h : a ∈ (C c * X ^ n).support) : a = n := mem_singleton.1 $ support_C_mul_X_pow' n c h lemma card_support_C_mul_X_pow_le_one {c : R} {n : ℕ} : (C c * X ^ n).support.card ≤ 1 := begin rw ← card_singleton n, apply card_le_of_subset (support_C_mul_X_pow' n c), end lemma card_supp_le_succ_nat_degree (p : R[X]) : p.support.card ≤ p.nat_degree + 1 := begin rw ← finset.card_range (p.nat_degree + 1), exact finset.card_le_of_subset supp_subset_range_nat_degree_succ, end lemma le_degree_of_mem_supp (a : ℕ) : a ∈ p.support → ↑a ≤ degree p := le_degree_of_ne_zero ∘ mem_support_iff.mp lemma nonempty_support_iff : p.support.nonempty ↔ p ≠ 0 := by rw [ne.def, nonempty_iff_ne_empty, ne.def, ← support_eq_empty] end semiring section nonzero_semiring variables [semiring R] [nontrivial R] {p q : R[X]} @[simp] lemma degree_one : degree (1 : R[X]) = (0 : with_bot ℕ) := degree_C (show (1 : R) ≠ 0, from zero_ne_one.symm) @[simp] lemma degree_X : degree (X : R[X]) = 1 := degree_monomial _ one_ne_zero @[simp] lemma nat_degree_X : (X : R[X]).nat_degree = 1 := nat_degree_eq_of_degree_eq_some degree_X end nonzero_semiring section ring variables [ring R] lemma coeff_mul_X_sub_C {p : R[X]} {r : R} {a : ℕ} : coeff (p * (X - C r)) (a + 1) = coeff p a - coeff p (a + 1) * r := by simp [mul_sub] @[simp] lemma degree_neg (p : R[X]) : degree (-p) = degree p := by unfold degree; rw support_neg @[simp] lemma nat_degree_neg (p : R[X]) : nat_degree (-p) = nat_degree p := by simp [nat_degree] @[simp] lemma nat_degree_int_cast (n : ℤ) : nat_degree (n : R[X]) = 0 := by rw [←C_eq_int_cast, nat_degree_C] @[simp] lemma leading_coeff_neg (p : R[X]) : (-p).leading_coeff = -p.leading_coeff := by rw [leading_coeff, leading_coeff, nat_degree_neg, coeff_neg] end ring section semiring variables [semiring R] /-- The second-highest coefficient, or 0 for constants -/ def next_coeff (p : R[X]) : R := if p.nat_degree = 0 then 0 else p.coeff (p.nat_degree - 1) @[simp] lemma next_coeff_C_eq_zero (c : R) : next_coeff (C c) = 0 := by { rw next_coeff, simp } lemma next_coeff_of_pos_nat_degree (p : R[X]) (hp : 0 < p.nat_degree) : next_coeff p = p.coeff (p.nat_degree - 1) := by { rw [next_coeff, if_neg], contrapose! hp, simpa } variables {p q : R[X]} {ι : Type*} lemma coeff_nat_degree_eq_zero_of_degree_lt (h : degree p < degree q) : coeff p (nat_degree q) = 0 := coeff_eq_zero_of_degree_lt (lt_of_lt_of_le h degree_le_nat_degree) lemma ne_zero_of_degree_gt {n : with_bot ℕ} (h : n < degree p) : p ≠ 0 := mt degree_eq_bot.2 (ne.symm (ne_of_lt (lt_of_le_of_lt bot_le h))) lemma ne_zero_of_degree_ge_degree (hpq : p.degree ≤ q.degree) (hp : p ≠ 0) : q ≠ 0 := polynomial.ne_zero_of_degree_gt (lt_of_lt_of_le (bot_lt_iff_ne_bot.mpr (by rwa [ne.def, polynomial.degree_eq_bot])) hpq : q.degree > ⊥) lemma ne_zero_of_nat_degree_gt {n : ℕ} (h : n < nat_degree p) : p ≠ 0 := λ H, by simpa [H, nat.not_lt_zero] using h lemma degree_lt_degree (h : nat_degree p < nat_degree q) : degree p < degree q := begin by_cases hp : p = 0, { simp [hp], rw bot_lt_iff_ne_bot, intro hq, simpa [hp, degree_eq_bot.mp hq, lt_irrefl] using h }, { rw [degree_eq_nat_degree hp, degree_eq_nat_degree $ ne_zero_of_nat_degree_gt h], exact_mod_cast h } end lemma nat_degree_lt_nat_degree_iff (hp : p ≠ 0) : nat_degree p < nat_degree q ↔ degree p < degree q := ⟨degree_lt_degree, begin intro h, have hq : q ≠ 0 := ne_zero_of_degree_gt h, rw [degree_eq_nat_degree hp, degree_eq_nat_degree hq] at h, exact_mod_cast h end⟩ lemma eq_C_of_degree_le_zero (h : degree p ≤ 0) : p = C (coeff p 0) := begin ext (_|n), { simp }, rw [coeff_C, if_neg (nat.succ_ne_zero _), coeff_eq_zero_of_degree_lt], exact h.trans_lt (with_bot.some_lt_some.2 n.succ_pos), end lemma eq_C_of_degree_eq_zero (h : degree p = 0) : p = C (coeff p 0) := eq_C_of_degree_le_zero (h ▸ le_rfl) lemma degree_le_zero_iff : degree p ≤ 0 ↔ p = C (coeff p 0) := ⟨eq_C_of_degree_le_zero, λ h, h.symm ▸ degree_C_le⟩ lemma degree_add_le (p q : R[X]) : degree (p + q) ≤ max (degree p) (degree q) := calc degree (p + q) = ((p + q).support).sup some : rfl ... ≤ (p.support ∪ q.support).sup some : sup_mono support_add ... = p.support.sup some ⊔ q.support.sup some : sup_union lemma degree_add_le_of_degree_le {p q : R[X]} {n : ℕ} (hp : degree p ≤ n) (hq : degree q ≤ n) : degree (p + q) ≤ n := (degree_add_le p q).trans $ max_le hp hq lemma nat_degree_add_le (p q : R[X]) : nat_degree (p + q) ≤ max (nat_degree p) (nat_degree q) := begin cases le_max_iff.1 (degree_add_le p q); simp [nat_degree_le_nat_degree h] end lemma nat_degree_add_le_of_degree_le {p q : R[X]} {n : ℕ} (hp : nat_degree p ≤ n) (hq : nat_degree q ≤ n) : nat_degree (p + q) ≤ n := (nat_degree_add_le p q).trans $ max_le hp hq @[simp] lemma leading_coeff_zero : leading_coeff (0 : R[X]) = 0 := rfl @[simp] lemma leading_coeff_eq_zero : leading_coeff p = 0 ↔ p = 0 := ⟨λ h, by_contradiction $ λ hp, mt mem_support_iff.1 (not_not.2 h) (mem_of_max (degree_eq_nat_degree hp)), λ h, h.symm ▸ leading_coeff_zero⟩ lemma leading_coeff_ne_zero : leading_coeff p ≠ 0 ↔ p ≠ 0 := by rw [ne.def, leading_coeff_eq_zero] lemma leading_coeff_eq_zero_iff_deg_eq_bot : leading_coeff p = 0 ↔ degree p = ⊥ := by rw [leading_coeff_eq_zero, degree_eq_bot] lemma nat_degree_mem_support_of_nonzero (H : p ≠ 0) : p.nat_degree ∈ p.support := by { rw mem_support_iff, exact (not_congr leading_coeff_eq_zero).mpr H } lemma nat_degree_eq_support_max' (h : p ≠ 0) : p.nat_degree = p.support.max' (nonempty_support_iff.mpr h) := (le_max' _ _ $ nat_degree_mem_support_of_nonzero h).antisymm $ max'_le _ _ _ le_nat_degree_of_mem_supp lemma nat_degree_C_mul_X_pow_le (a : R) (n : ℕ) : nat_degree (C a * X ^ n) ≤ n := nat_degree_le_iff_degree_le.2 $ degree_C_mul_X_pow_le _ _ lemma degree_add_eq_left_of_degree_lt (h : degree q < degree p) : degree (p + q) = degree p := le_antisymm (max_eq_left_of_lt h ▸ degree_add_le _ _) $ degree_le_degree $ begin rw [coeff_add, coeff_nat_degree_eq_zero_of_degree_lt h, add_zero], exact mt leading_coeff_eq_zero.1 (ne_zero_of_degree_gt h) end lemma degree_add_eq_right_of_degree_lt (h : degree p < degree q) : degree (p + q) = degree q := by rw [add_comm, degree_add_eq_left_of_degree_lt h] lemma nat_degree_add_eq_left_of_nat_degree_lt (h : nat_degree q < nat_degree p) : nat_degree (p + q) = nat_degree p := nat_degree_eq_of_degree_eq (degree_add_eq_left_of_degree_lt (degree_lt_degree h)) lemma nat_degree_add_eq_right_of_nat_degree_lt (h : nat_degree p < nat_degree q) : nat_degree (p + q) = nat_degree q := nat_degree_eq_of_degree_eq (degree_add_eq_right_of_degree_lt (degree_lt_degree h)) lemma degree_add_C (hp : 0 < degree p) : degree (p + C a) = degree p := add_comm (C a) p ▸ degree_add_eq_right_of_degree_lt $ lt_of_le_of_lt degree_C_le hp lemma degree_add_eq_of_leading_coeff_add_ne_zero (h : leading_coeff p + leading_coeff q ≠ 0) : degree (p + q) = max p.degree q.degree := le_antisymm (degree_add_le _ _) $ match lt_trichotomy (degree p) (degree q) with | or.inl hlt := by rw [degree_add_eq_right_of_degree_lt hlt, max_eq_right_of_lt hlt]; exact le_rfl | or.inr (or.inl heq) := le_of_not_gt $ assume hlt : max (degree p) (degree q) > degree (p + q), h $ show leading_coeff p + leading_coeff q = 0, begin rw [heq, max_self] at hlt, rw [leading_coeff, leading_coeff, nat_degree_eq_of_degree_eq heq, ← coeff_add], exact coeff_nat_degree_eq_zero_of_degree_lt hlt end | or.inr (or.inr hlt) := by rw [degree_add_eq_left_of_degree_lt hlt, max_eq_left_of_lt hlt]; exact le_rfl end lemma degree_erase_le (p : R[X]) (n : ℕ) : degree (p.erase n) ≤ degree p := by { rcases p, simp only [erase, degree, coeff, support], convert sup_mono (erase_subset _ _) } lemma degree_erase_lt (hp : p ≠ 0) : degree (p.erase (nat_degree p)) < degree p := begin apply lt_of_le_of_ne (degree_erase_le _ _), rw [degree_eq_nat_degree hp, degree, support_erase], exact λ h, not_mem_erase _ _ (mem_of_max h), end lemma degree_update_le (p : R[X]) (n : ℕ) (a : R) : degree (p.update n a) ≤ max (degree p) n := begin rw [degree, support_update], split_ifs, { exact (finset.max_mono (erase_subset _ _)).trans (le_max_left _ _) }, { rw [max_insert, max_comm], exact le_rfl }, end lemma degree_sum_le (s : finset ι) (f : ι → R[X]) : degree (∑ i in s, f i) ≤ s.sup (λ b, degree (f b)) := finset.induction_on s (by simp only [sum_empty, sup_empty, degree_zero, le_refl]) $ assume a s has ih, calc degree (∑ i in insert a s, f i) ≤ max (degree (f a)) (degree (∑ i in s, f i)) : by rw sum_insert has; exact degree_add_le _ _ ... ≤ _ : by rw [sup_insert, sup_eq_max]; exact max_le_max le_rfl ih lemma degree_mul_le (p q : R[X]) : degree (p * q) ≤ degree p + degree q := calc degree (p * q) ≤ (p.support).sup (λi, degree (sum q (λj a, C (coeff p i * a) * X ^ (i + j)))) : begin simp only [monomial_eq_C_mul_X.symm], convert degree_sum_le _ _, exact mul_eq_sum_sum end ... ≤ p.support.sup (λi, q.support.sup (λj, degree (C (coeff p i * coeff q j) * X ^ (i + j)))) : finset.sup_mono_fun (assume i hi, degree_sum_le _ _) ... ≤ degree p + degree q : begin refine finset.sup_le (λ a ha, finset.sup_le (λ b hb, le_trans (degree_C_mul_X_pow_le _ _) _)), rw [with_bot.coe_add], rw mem_support_iff at ha hb, exact add_le_add (le_degree_of_ne_zero ha) (le_degree_of_ne_zero hb) end lemma degree_pow_le (p : R[X]) : ∀ (n : ℕ), degree (p ^ n) ≤ n • (degree p) | 0 := by rw [pow_zero, zero_nsmul]; exact degree_one_le | (n+1) := calc degree (p ^ (n + 1)) ≤ degree p + degree (p ^ n) : by rw pow_succ; exact degree_mul_le _ _ ... ≤ _ : by rw succ_nsmul; exact add_le_add le_rfl (degree_pow_le _) @[simp] lemma leading_coeff_monomial (a : R) (n : ℕ) : leading_coeff (monomial n a) = a := begin by_cases ha : a = 0, { simp only [ha, (monomial n).map_zero, leading_coeff_zero] }, { rw [leading_coeff, nat_degree_monomial, if_neg ha, coeff_monomial], simp } end lemma leading_coeff_C_mul_X_pow (a : R) (n : ℕ) : leading_coeff (C a * X ^ n) = a := by rw [C_mul_X_pow_eq_monomial, leading_coeff_monomial] lemma leading_coeff_C_mul_X (a : R) : leading_coeff (C a * X) = a := by simpa only [pow_one] using leading_coeff_C_mul_X_pow a 1 @[simp] lemma leading_coeff_C (a : R) : leading_coeff (C a) = a := leading_coeff_monomial a 0 @[simp] lemma leading_coeff_X_pow (n : ℕ) : leading_coeff ((X : R[X]) ^ n) = 1 := by simpa only [C_1, one_mul] using leading_coeff_C_mul_X_pow (1 : R) n @[simp] lemma leading_coeff_X : leading_coeff (X : R[X]) = 1 := by simpa only [pow_one] using @leading_coeff_X_pow R _ 1 @[simp] lemma monic_X_pow (n : ℕ) : monic (X ^ n : R[X]) := leading_coeff_X_pow n @[simp] lemma monic_X : monic (X : R[X]) := leading_coeff_X @[simp] lemma leading_coeff_one : leading_coeff (1 : R[X]) = 1 := leading_coeff_C 1 @[simp] lemma monic_one : monic (1 : R[X]) := leading_coeff_C _ lemma monic.ne_zero {R : Type*} [semiring R] [nontrivial R] {p : R[X]} (hp : p.monic) : p ≠ 0 := by { rintro rfl, simpa [monic] using hp } lemma monic.ne_zero_of_ne (h : (0:R) ≠ 1) {p : R[X]} (hp : p.monic) : p ≠ 0 := by { nontriviality R, exact hp.ne_zero } lemma monic_of_nat_degree_le_of_coeff_eq_one (n : ℕ) (pn : p.nat_degree ≤ n) (p1 : p.coeff n = 1) : monic p := begin nontriviality, refine (congr_arg _ $ nat_degree_eq_of_le_of_coeff_ne_zero pn _).trans p1, exact ne_of_eq_of_ne p1 one_ne_zero, end lemma monic_of_degree_le_of_coeff_eq_one (n : ℕ) (pn : p.degree ≤ n) (p1 : p.coeff n = 1) : monic p := monic_of_nat_degree_le_of_coeff_eq_one n (nat_degree_le_of_degree_le pn) p1 lemma monic.ne_zero_of_polynomial_ne {r} (hp : monic p) (hne : q ≠ r) : p ≠ 0 := by { haveI := nontrivial.of_polynomial_ne hne, exact hp.ne_zero } lemma leading_coeff_add_of_degree_lt (h : degree p < degree q) : leading_coeff (p + q) = leading_coeff q := have coeff p (nat_degree q) = 0, from coeff_nat_degree_eq_zero_of_degree_lt h, by simp only [leading_coeff, nat_degree_eq_of_degree_eq (degree_add_eq_right_of_degree_lt h), this, coeff_add, zero_add] lemma leading_coeff_add_of_degree_eq (h : degree p = degree q) (hlc : leading_coeff p + leading_coeff q ≠ 0) : leading_coeff (p + q) = leading_coeff p + leading_coeff q := have nat_degree (p + q) = nat_degree p, by apply nat_degree_eq_of_degree_eq; rw [degree_add_eq_of_leading_coeff_add_ne_zero hlc, h, max_self], by simp only [leading_coeff, this, nat_degree_eq_of_degree_eq h, coeff_add] @[simp] lemma coeff_mul_degree_add_degree (p q : R[X]) : coeff (p * q) (nat_degree p + nat_degree q) = leading_coeff p * leading_coeff q := calc coeff (p * q) (nat_degree p + nat_degree q) = ∑ x in nat.antidiagonal (nat_degree p + nat_degree q), coeff p x.1 * coeff q x.2 : coeff_mul _ _ _ ... = coeff p (nat_degree p) * coeff q (nat_degree q) : begin refine finset.sum_eq_single (nat_degree p, nat_degree q) _ _, { rintro ⟨i,j⟩ h₁ h₂, rw nat.mem_antidiagonal at h₁, by_cases H : nat_degree p < i, { rw [coeff_eq_zero_of_degree_lt (lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 H)), zero_mul] }, { rw not_lt_iff_eq_or_lt at H, cases H, { subst H, rw add_left_cancel_iff at h₁, dsimp at h₁, subst h₁, exfalso, exact h₂ rfl }, { suffices : nat_degree q < j, { rw [coeff_eq_zero_of_degree_lt (lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 this)), mul_zero] }, { by_contra H', rw not_lt at H', exact ne_of_lt (nat.lt_of_lt_of_le (nat.add_lt_add_right H j) (nat.add_le_add_left H' _)) h₁ } } } }, { intro H, exfalso, apply H, rw nat.mem_antidiagonal } end lemma degree_mul' (h : leading_coeff p * leading_coeff q ≠ 0) : degree (p * q) = degree p + degree q := have hp : p ≠ 0 := by refine mt _ h; exact λ hp, by rw [hp, leading_coeff_zero, zero_mul], have hq : q ≠ 0 := by refine mt _ h; exact λ hq, by rw [hq, leading_coeff_zero, mul_zero], le_antisymm (degree_mul_le _ _) begin rw [degree_eq_nat_degree hp, degree_eq_nat_degree hq], refine le_degree_of_ne_zero _, rwa coeff_mul_degree_add_degree end lemma monic.degree_mul (hq : monic q) : degree (p * q) = degree p + degree q := if hp : p = 0 then by simp [hp] else degree_mul' $ by rwa [hq.leading_coeff, mul_one, ne.def, leading_coeff_eq_zero] lemma nat_degree_mul' (h : leading_coeff p * leading_coeff q ≠ 0) : nat_degree (p * q) = nat_degree p + nat_degree q := have hp : p ≠ 0 := mt leading_coeff_eq_zero.2 (λ h₁, h $ by rw [h₁, zero_mul]), have hq : q ≠ 0 := mt leading_coeff_eq_zero.2 (λ h₁, h $ by rw [h₁, mul_zero]), nat_degree_eq_of_degree_eq_some $ by rw [degree_mul' h, with_bot.coe_add, degree_eq_nat_degree hp, degree_eq_nat_degree hq] lemma leading_coeff_mul' (h : leading_coeff p * leading_coeff q ≠ 0) : leading_coeff (p * q) = leading_coeff p * leading_coeff q := begin unfold leading_coeff, rw [nat_degree_mul' h, coeff_mul_degree_add_degree], refl end lemma monomial_nat_degree_leading_coeff_eq_self (h : p.support.card ≤ 1) : monomial p.nat_degree p.leading_coeff = p := begin rcases card_support_le_one_iff_monomial.1 h with ⟨n, a, rfl⟩, by_cases ha : a = 0; simp [ha] end lemma C_mul_X_pow_eq_self (h : p.support.card ≤ 1) : C p.leading_coeff * X^p.nat_degree = p := by rw [C_mul_X_pow_eq_monomial, monomial_nat_degree_leading_coeff_eq_self h] lemma leading_coeff_pow' : leading_coeff p ^ n ≠ 0 → leading_coeff (p ^ n) = leading_coeff p ^ n := nat.rec_on n (by simp) $ λ n ih h, have h₁ : leading_coeff p ^ n ≠ 0 := λ h₁, h $ by rw [pow_succ, h₁, mul_zero], have h₂ : leading_coeff p * leading_coeff (p ^ n) ≠ 0 := by rwa [pow_succ, ← ih h₁] at h, by rw [pow_succ, pow_succ, leading_coeff_mul' h₂, ih h₁] lemma degree_pow' : ∀ {n : ℕ}, leading_coeff p ^ n ≠ 0 → degree (p ^ n) = n • (degree p) | 0 := λ h, by rw [pow_zero, ← C_1] at *; rw [degree_C h, zero_nsmul] | (n+1) := λ h, have h₁ : leading_coeff p ^ n ≠ 0 := λ h₁, h $ by rw [pow_succ, h₁, mul_zero], have h₂ : leading_coeff p * leading_coeff (p ^ n) ≠ 0 := by rwa [pow_succ, ← leading_coeff_pow' h₁] at h, by rw [pow_succ, degree_mul' h₂, succ_nsmul, degree_pow' h₁] lemma nat_degree_pow' {n : ℕ} (h : leading_coeff p ^ n ≠ 0) : nat_degree (p ^ n) = n * nat_degree p := if hp0 : p = 0 then if hn0 : n = 0 then by simp * else by rw [hp0, zero_pow (nat.pos_of_ne_zero hn0)]; simp else have hpn : p ^ n ≠ 0, from λ hpn0, have h1 : _ := h, by rw [← leading_coeff_pow' h1, hpn0, leading_coeff_zero] at h; exact h rfl, option.some_inj.1 $ show (nat_degree (p ^ n) : with_bot ℕ) = (n * nat_degree p : ℕ), by rw [← degree_eq_nat_degree hpn, degree_pow' h, degree_eq_nat_degree hp0, ← with_bot.coe_nsmul]; simp theorem leading_coeff_monic_mul {p q : R[X]} (hp : monic p) : leading_coeff (p * q) = leading_coeff q := begin rcases eq_or_ne q 0 with rfl|H, { simp }, { rw [leading_coeff_mul', hp.leading_coeff, one_mul], rwa [hp.leading_coeff, one_mul, ne.def, leading_coeff_eq_zero] } end theorem leading_coeff_mul_monic {p q : R[X]} (hq : monic q) : leading_coeff (p * q) = leading_coeff p := decidable.by_cases (λ H : leading_coeff p = 0, by rw [H, leading_coeff_eq_zero.1 H, zero_mul, leading_coeff_zero]) (λ H : leading_coeff p ≠ 0, by rw [leading_coeff_mul', hq.leading_coeff, mul_one]; rwa [hq.leading_coeff, mul_one]) @[simp] theorem leading_coeff_mul_X_pow {p : R[X]} {n : ℕ} : leading_coeff (p * X ^ n) = leading_coeff p := leading_coeff_mul_monic (monic_X_pow n) @[simp] theorem leading_coeff_mul_X {p : R[X]} : leading_coeff (p * X) = leading_coeff p := leading_coeff_mul_monic monic_X lemma nat_degree_mul_le {p q : R[X]} : nat_degree (p * q) ≤ nat_degree p + nat_degree q := begin apply nat_degree_le_of_degree_le, apply le_trans (degree_mul_le p q), rw with_bot.coe_add, refine add_le_add _ _; apply degree_le_nat_degree, end lemma nat_degree_pow_le {p : R[X]} {n : ℕ} : (p ^ n).nat_degree ≤ n * p.nat_degree := begin induction n with i hi, { simp }, { rw [pow_succ, nat.succ_mul, add_comm], apply le_trans nat_degree_mul_le, exact add_le_add_left hi _ } end @[simp] lemma coeff_pow_mul_nat_degree (p : R[X]) (n : ℕ) : (p ^ n).coeff (n * p.nat_degree) = p.leading_coeff ^ n := begin induction n with i hi, { simp }, { rw [pow_succ', pow_succ', nat.succ_mul], by_cases hp1 : p.leading_coeff ^ i = 0, { rw [hp1, zero_mul], by_cases hp2 : p ^ i = 0, { rw [hp2, zero_mul, coeff_zero] }, { apply coeff_eq_zero_of_nat_degree_lt, have h1 : (p ^ i).nat_degree < i * p.nat_degree, { apply lt_of_le_of_ne nat_degree_pow_le (λ h, hp2 _), rw [←h, hp1] at hi, exact leading_coeff_eq_zero.mp hi }, calc (p ^ i * p).nat_degree ≤ (p ^ i).nat_degree + p.nat_degree : nat_degree_mul_le ... < i * p.nat_degree + p.nat_degree : add_lt_add_right h1 _ } }, { rw [←nat_degree_pow' hp1, ←leading_coeff_pow' hp1], exact coeff_mul_degree_add_degree _ _ } } end lemma zero_le_degree_iff {p : R[X]} : 0 ≤ degree p ↔ p ≠ 0 := by rw [ne.def, ← degree_eq_bot]; cases degree p; exact dec_trivial lemma degree_nonneg_iff_ne_zero : 0 ≤ degree p ↔ p ≠ 0 := by simp [degree_eq_bot, ← not_lt] lemma nat_degree_eq_zero_iff_degree_le_zero : p.nat_degree = 0 ↔ p.degree ≤ 0 := by rw [← nonpos_iff_eq_zero, nat_degree_le_iff_degree_le, with_bot.coe_zero] theorem degree_le_iff_coeff_zero (f : R[X]) (n : with_bot ℕ) : degree f ≤ n ↔ ∀ m : ℕ, n < m → coeff f m = 0 := by simp only [degree, finset.max, finset.sup_le_iff, mem_support_iff, ne.def, ← not_le, not_imp_comm] theorem degree_lt_iff_coeff_zero (f : R[X]) (n : ℕ) : degree f < n ↔ ∀ m : ℕ, n ≤ m → coeff f m = 0 := begin refine ⟨λ hf m hm, coeff_eq_zero_of_degree_lt (lt_of_lt_of_le hf (with_bot.coe_le_coe.2 hm)), _⟩, simp only [degree, finset.sup_lt_iff (with_bot.bot_lt_coe n), mem_support_iff, with_bot.some_eq_coe, with_bot.coe_lt_coe, ← @not_le ℕ, max_eq_sup_coe], exact λ h m, mt (h m), end lemma degree_smul_le (a : R) (p : R[X]) : degree (a • p) ≤ degree p := begin apply (degree_le_iff_coeff_zero _ _).2 (λ m hm, _), rw degree_lt_iff_coeff_zero at hm, simp [hm m le_rfl], end lemma nat_degree_smul_le (a : R) (p : R[X]) : nat_degree (a • p) ≤ nat_degree p := nat_degree_le_nat_degree (degree_smul_le a p) lemma degree_lt_degree_mul_X (hp : p ≠ 0) : p.degree < (p * X).degree := by haveI := nontrivial.of_polynomial_ne hp; exact have leading_coeff p * leading_coeff X ≠ 0, by simpa, by erw [degree_mul' this, degree_eq_nat_degree hp, degree_X, ← with_bot.coe_one, ← with_bot.coe_add, with_bot.coe_lt_coe]; exact nat.lt_succ_self _ lemma nat_degree_pos_iff_degree_pos : 0 < nat_degree p ↔ 0 < degree p := lt_iff_lt_of_le_iff_le nat_degree_le_iff_degree_le lemma eq_C_of_nat_degree_le_zero (h : nat_degree p ≤ 0) : p = C (coeff p 0) := eq_C_of_degree_le_zero $ degree_le_of_nat_degree_le h lemma eq_C_of_nat_degree_eq_zero (h : nat_degree p = 0) : p = C (coeff p 0) := eq_C_of_nat_degree_le_zero h.le lemma ne_zero_of_coe_le_degree (hdeg : ↑n ≤ p.degree) : p ≠ 0 := degree_nonneg_iff_ne_zero.mp $ (with_bot.coe_le_coe.mpr n.zero_le).trans hdeg lemma le_nat_degree_of_coe_le_degree (hdeg : ↑n ≤ p.degree) : n ≤ p.nat_degree := with_bot.coe_le_coe.mp ((degree_eq_nat_degree $ ne_zero_of_coe_le_degree hdeg) ▸ hdeg) lemma degree_sum_fin_lt {n : ℕ} (f : fin n → R) : degree (∑ i : fin n, C (f i) * X ^ (i : ℕ)) < n := begin haveI : is_commutative (with_bot ℕ) max := ⟨max_comm⟩, haveI : is_associative (with_bot ℕ) max := ⟨max_assoc⟩, calc (∑ i, C (f i) * X ^ (i : ℕ)).degree ≤ finset.univ.fold (⊔) ⊥ (λ i, (C (f i) * X ^ (i : ℕ)).degree) : degree_sum_le _ _ ... = finset.univ.fold max ⊥ (λ i, (C (f i) * X ^ (i : ℕ)).degree) : rfl ... < n : (finset.fold_max_lt (n : with_bot ℕ)).mpr ⟨with_bot.bot_lt_coe _, _⟩, rintros ⟨i, hi⟩ -, calc (C (f ⟨i, hi⟩) * X ^ i).degree ≤ (C _).degree + (X ^ i).degree : degree_mul_le _ _ ... ≤ 0 + i : add_le_add degree_C_le (degree_X_pow_le i) ... = i : zero_add _ ... < n : with_bot.some_lt_some.mpr hi, end lemma degree_linear_le : degree (C a * X + C b) ≤ 1 := degree_add_le_of_degree_le (degree_C_mul_X_le _) $ le_trans degree_C_le nat.with_bot.coe_nonneg lemma degree_linear_lt : degree (C a * X + C b) < 2 := degree_linear_le.trans_lt $ with_bot.coe_lt_coe.mpr one_lt_two lemma degree_C_lt_degree_C_mul_X (ha : a ≠ 0) : degree (C b) < degree (C a * X) := by simpa only [degree_C_mul_X ha] using degree_C_lt @[simp] lemma degree_linear (ha : a ≠ 0) : degree (C a * X + C b) = 1 := by rw [degree_add_eq_left_of_degree_lt $ degree_C_lt_degree_C_mul_X ha, degree_C_mul_X ha] lemma nat_degree_linear_le : nat_degree (C a * X + C b) ≤ 1 := nat_degree_le_of_degree_le degree_linear_le @[simp] lemma nat_degree_linear (ha : a ≠ 0) : nat_degree (C a * X + C b) = 1 := nat_degree_eq_of_degree_eq_some $ degree_linear ha @[simp] lemma leading_coeff_linear (ha : a ≠ 0): leading_coeff (C a * X + C b) = a := by rw [add_comm, leading_coeff_add_of_degree_lt (degree_C_lt_degree_C_mul_X ha), leading_coeff_C_mul_X] lemma degree_quadratic_le : degree (C a * X ^ 2 + C b * X + C c) ≤ 2 := by simpa only [add_assoc] using degree_add_le_of_degree_le (degree_C_mul_X_pow_le 2 a) (le_trans degree_linear_le $ with_bot.coe_le_coe.mpr one_le_two) lemma degree_quadratic_lt : degree (C a * X ^ 2 + C b * X + C c) < 3 := degree_quadratic_le.trans_lt $ with_bot.coe_lt_coe.mpr $ lt_add_one 2 lemma degree_linear_lt_degree_C_mul_X_sq (ha : a ≠ 0) : degree (C b * X + C c) < degree (C a * X ^ 2) := by simpa only [degree_C_mul_X_pow 2 ha] using degree_linear_lt @[simp] lemma degree_quadratic (ha : a ≠ 0) : degree (C a * X ^ 2 + C b * X + C c) = 2 := begin rw [add_assoc, degree_add_eq_left_of_degree_lt $ degree_linear_lt_degree_C_mul_X_sq ha, degree_C_mul_X_pow 2 ha], refl end lemma nat_degree_quadratic_le : nat_degree (C a * X ^ 2 + C b * X + C c) ≤ 2 := nat_degree_le_of_degree_le degree_quadratic_le @[simp] lemma nat_degree_quadratic (ha : a ≠ 0) : nat_degree (C a * X ^ 2 + C b * X + C c) = 2 := nat_degree_eq_of_degree_eq_some $ degree_quadratic ha @[simp] lemma leading_coeff_quadratic (ha : a ≠ 0) : leading_coeff (C a * X ^ 2 + C b * X + C c) = a := by rw [add_assoc, add_comm, leading_coeff_add_of_degree_lt $ degree_linear_lt_degree_C_mul_X_sq ha, leading_coeff_C_mul_X_pow] lemma degree_cubic_le : degree (C a * X ^ 3 + C b * X ^ 2 + C c * X + C d) ≤ 3 := by simpa only [add_assoc] using degree_add_le_of_degree_le (degree_C_mul_X_pow_le 3 a) (le_trans degree_quadratic_le $ with_bot.coe_le_coe.mpr $ nat.le_succ 2) lemma degree_cubic_lt : degree (C a * X ^ 3 + C b * X ^ 2 + C c * X + C d) < 4 := degree_cubic_le.trans_lt $ with_bot.coe_lt_coe.mpr $ lt_add_one 3 lemma degree_quadratic_lt_degree_C_mul_X_cb (ha : a ≠ 0) : degree (C b * X ^ 2 + C c * X + C d) < degree (C a * X ^ 3) := by simpa only [degree_C_mul_X_pow 3 ha] using degree_quadratic_lt @[simp] lemma degree_cubic (ha : a ≠ 0) : degree (C a * X ^ 3 + C b * X ^ 2 + C c * X + C d) = 3 := begin rw [add_assoc, add_assoc, ← add_assoc (C b * X ^ 2), degree_add_eq_left_of_degree_lt $ degree_quadratic_lt_degree_C_mul_X_cb ha, degree_C_mul_X_pow 3 ha], refl end lemma nat_degree_cubic_le : nat_degree (C a * X ^ 3 + C b * X ^ 2 + C c * X + C d) ≤ 3 := nat_degree_le_of_degree_le degree_cubic_le @[simp] lemma nat_degree_cubic (ha : a ≠ 0) : nat_degree (C a * X ^ 3 + C b * X ^ 2 + C c * X + C d) = 3 := nat_degree_eq_of_degree_eq_some $ degree_cubic ha @[simp] lemma leading_coeff_cubic (ha : a ≠ 0): leading_coeff (C a * X ^ 3 + C b * X ^ 2 + C c * X + C d) = a := by rw [add_assoc, add_assoc, ← add_assoc (C b * X ^ 2), add_comm, leading_coeff_add_of_degree_lt $ degree_quadratic_lt_degree_C_mul_X_cb ha, leading_coeff_C_mul_X_pow] end semiring section nontrivial_semiring variables [semiring R] [nontrivial R] {p q : R[X]} @[simp] lemma degree_X_pow (n : ℕ) : degree ((X : R[X]) ^ n) = n := by rw [X_pow_eq_monomial, degree_monomial _ (@one_ne_zero R _ _)] @[simp] lemma nat_degree_X_pow (n : ℕ) : nat_degree ((X : R[X]) ^ n) = n := nat_degree_eq_of_degree_eq_some (degree_X_pow n) /- This lemma explicitly does not require the `nontrivial R` assumption. -/ lemma nat_degree_X_pow_le {R : Type*} [semiring R] (n : ℕ) : (X ^ n : R[X]).nat_degree ≤ n := begin nontriviality R, rwa polynomial.nat_degree_X_pow, end theorem not_is_unit_X : ¬ is_unit (X : R[X]) := λ ⟨⟨_, g, hfg, hgf⟩, rfl⟩, @zero_ne_one R _ _ $ by { change g * monomial 1 1 = 1 at hgf, rw [← coeff_one_zero, ← hgf], simp } @[simp] lemma degree_mul_X : degree (p * X) = degree p + 1 := by simp [monic_X.degree_mul] @[simp] lemma degree_mul_X_pow : degree (p * X ^ n) = degree p + n := by simp [(monic_X_pow n).degree_mul] end nontrivial_semiring section ring variables [ring R] {p q : R[X]} lemma degree_sub_le (p q : R[X]) : degree (p - q) ≤ max (degree p) (degree q) := by simpa only [sub_eq_add_neg, degree_neg q] using degree_add_le p (-q) lemma degree_sub_lt (hd : degree p = degree q) (hp0 : p ≠ 0) (hlc : leading_coeff p = leading_coeff q) : degree (p - q) < degree p := have hp : monomial (nat_degree p) (leading_coeff p) + p.erase (nat_degree p) = p := monomial_add_erase _ _, have hq : monomial (nat_degree q) (leading_coeff q) + q.erase (nat_degree q) = q := monomial_add_erase _ _, have hd' : nat_degree p = nat_degree q := by unfold nat_degree; rw hd, have hq0 : q ≠ 0 := mt degree_eq_bot.2 (hd ▸ mt degree_eq_bot.1 hp0), calc degree (p - q) = degree (erase (nat_degree q) p + -erase (nat_degree q) q) : by conv { to_lhs, rw [← hp, ← hq, hlc, hd', add_sub_add_left_eq_sub, sub_eq_add_neg] } ... ≤ max (degree (erase (nat_degree q) p)) (degree (erase (nat_degree q) q)) : degree_neg (erase (nat_degree q) q) ▸ degree_add_le _ _ ... < degree p : max_lt_iff.2 ⟨hd' ▸ degree_erase_lt hp0, hd.symm ▸ degree_erase_lt hq0⟩ lemma degree_X_sub_C_le (r : R) : (X - C r).degree ≤ 1 := (degree_sub_le _ _).trans (max_le degree_X_le (degree_C_le.trans zero_le_one)) lemma nat_degree_X_sub_C_le (r : R) : (X - C r).nat_degree ≤ 1 := nat_degree_le_iff_degree_le.2 $ degree_X_sub_C_le r lemma degree_sub_eq_left_of_degree_lt (h : degree q < degree p) : degree (p - q) = degree p := by { rw ← degree_neg q at h, rw [sub_eq_add_neg, degree_add_eq_left_of_degree_lt h] } lemma degree_sub_eq_right_of_degree_lt (h : degree p < degree q) : degree (p - q) = degree q := by { rw ← degree_neg q at h, rw [sub_eq_add_neg, degree_add_eq_right_of_degree_lt h, degree_neg] } end ring section nonzero_ring variables [nontrivial R] section semiring variable [semiring R] @[simp] lemma degree_X_add_C (a : R) : degree (X + C a) = 1 := have degree (C a) < degree (X : R[X]), from calc degree (C a) ≤ 0 : degree_C_le ... < 1 : with_bot.some_lt_some.mpr zero_lt_one ... = degree X : degree_X.symm, by rw [degree_add_eq_left_of_degree_lt this, degree_X] @[simp] lemma nat_degree_X_add_C (x : R) : (X + C x).nat_degree = 1 := nat_degree_eq_of_degree_eq_some $ degree_X_add_C x @[simp] lemma next_coeff_X_add_C [semiring S] (c : S) : next_coeff (X + C c) = c := begin nontriviality S, simp [next_coeff_of_pos_nat_degree] end lemma degree_X_pow_add_C {n : ℕ} (hn : 0 < n) (a : R) : degree ((X : R[X]) ^ n + C a) = n := have degree (C a) < degree ((X : R[X]) ^ n), from calc degree (C a) ≤ 0 : degree_C_le ... < degree ((X : R[X]) ^ n) : by rwa [degree_X_pow]; exact with_bot.coe_lt_coe.2 hn, by rw [degree_add_eq_left_of_degree_lt this, degree_X_pow] lemma X_pow_add_C_ne_zero {n : ℕ} (hn : 0 < n) (a : R) : (X : R[X]) ^ n + C a ≠ 0 := mt degree_eq_bot.2 (show degree ((X : R[X]) ^ n + C a) ≠ ⊥, by rw degree_X_pow_add_C hn a; exact dec_trivial) theorem X_add_C_ne_zero (r : R) : X + C r ≠ 0 := pow_one (X : R[X]) ▸ X_pow_add_C_ne_zero zero_lt_one r theorem zero_nmem_multiset_map_X_add_C {α : Type*} (m : multiset α) (f : α → R) : (0 : R[X]) ∉ m.map (λ a, X + C (f a)) := λ mem, let ⟨a, _, ha⟩ := multiset.mem_map.mp mem in X_add_C_ne_zero _ ha lemma nat_degree_X_pow_add_C {n : ℕ} {r : R} : (X ^ n + C r).nat_degree = n := begin by_cases hn : n = 0, { rw [hn, pow_zero, ←C_1, ←ring_hom.map_add, nat_degree_C] }, { exact nat_degree_eq_of_degree_eq_some (degree_X_pow_add_C (pos_iff_ne_zero.mpr hn) r) }, end end semiring end nonzero_ring section semiring variable [semiring R] @[simp] lemma leading_coeff_X_pow_add_C {n : ℕ} (hn : 0 < n) {r : R} : (X ^ n + C r).leading_coeff = 1 := begin nontriviality R, rw [leading_coeff, nat_degree_X_pow_add_C, coeff_add, coeff_X_pow_self, coeff_C, if_neg (pos_iff_ne_zero.mp hn), add_zero] end @[simp] lemma leading_coeff_X_add_C [semiring S] (r : S) : (X + C r).leading_coeff = 1 := by rw [←pow_one (X : S[X]), leading_coeff_X_pow_add_C zero_lt_one] @[simp] lemma leading_coeff_X_pow_add_one {n : ℕ} (hn : 0 < n) : (X ^ n + 1 : R[X]).leading_coeff = 1 := leading_coeff_X_pow_add_C hn @[simp] lemma leading_coeff_pow_X_add_C (r : R) (i : ℕ) : leading_coeff ((X + C r) ^ i) = 1 := by { nontriviality, rw leading_coeff_pow'; simp } end semiring section ring variable [ring R] @[simp] lemma leading_coeff_X_pow_sub_C {n : ℕ} (hn : 0 < n) {r : R} : (X ^ n - C r).leading_coeff = 1 := by rw [sub_eq_add_neg, ←map_neg C r, leading_coeff_X_pow_add_C hn]; apply_instance @[simp] lemma leading_coeff_X_pow_sub_one {n : ℕ} (hn : 0 < n) : (X ^ n - 1 : R[X]).leading_coeff = 1 := leading_coeff_X_pow_sub_C hn variables [nontrivial R] @[simp] lemma degree_X_sub_C (a : R) : degree (X - C a) = 1 := by rw [sub_eq_add_neg, ←map_neg C a, degree_X_add_C] @[simp] lemma nat_degree_X_sub_C (x : R) : (X - C x).nat_degree = 1 := nat_degree_eq_of_degree_eq_some $ degree_X_sub_C x @[simp] lemma next_coeff_X_sub_C [ring S] (c : S) : next_coeff (X - C c) = - c := by rw [sub_eq_add_neg, ←map_neg C c, next_coeff_X_add_C] lemma degree_X_pow_sub_C {n : ℕ} (hn : 0 < n) (a : R) : degree ((X : R[X]) ^ n - C a) = n := by rw [sub_eq_add_neg, ←map_neg C a, degree_X_pow_add_C hn]; apply_instance lemma X_pow_sub_C_ne_zero {n : ℕ} (hn : 0 < n) (a : R) : (X : R[X]) ^ n - C a ≠ 0 := by { rw [sub_eq_add_neg, ←map_neg C a], exact X_pow_add_C_ne_zero hn _ } theorem X_sub_C_ne_zero (r : R) : X - C r ≠ 0 := pow_one (X : R[X]) ▸ X_pow_sub_C_ne_zero zero_lt_one r theorem zero_nmem_multiset_map_X_sub_C {α : Type*} (m : multiset α) (f : α → R) : (0 : R[X]) ∉ m.map (λ a, X - C (f a)) := λ mem, let ⟨a, _, ha⟩ := multiset.mem_map.mp mem in X_sub_C_ne_zero _ ha lemma nat_degree_X_pow_sub_C {n : ℕ} {r : R} : (X ^ n - C r).nat_degree = n := by rw [sub_eq_add_neg, ←map_neg C r, nat_degree_X_pow_add_C] @[simp] lemma leading_coeff_X_sub_C [ring S] (r : S) : (X - C r).leading_coeff = 1 := by rw [sub_eq_add_neg, ←map_neg C r, leading_coeff_X_add_C] end ring section no_zero_divisors variables [semiring R] [no_zero_divisors R] {p q : R[X]} @[simp] lemma degree_mul : degree (p * q) = degree p + degree q := if hp0 : p = 0 then by simp only [hp0, degree_zero, zero_mul, with_bot.bot_add] else if hq0 : q = 0 then by simp only [hq0, degree_zero, mul_zero, with_bot.add_bot] else degree_mul' $ mul_ne_zero (mt leading_coeff_eq_zero.1 hp0) (mt leading_coeff_eq_zero.1 hq0) /-- `degree` as a monoid homomorphism between `R[X]` and `multiplicative (with_bot ℕ)`. This is useful to prove results about multiplication and degree. -/ def degree_monoid_hom [nontrivial R] : R[X] →* multiplicative (with_bot ℕ) := { to_fun := degree, map_one' := degree_one, map_mul' := λ _ _, degree_mul } @[simp] lemma degree_pow [nontrivial R] (p : R[X]) (n : ℕ) : degree (p ^ n) = n • (degree p) := map_pow (@degree_monoid_hom R _ _ _) _ _ @[simp] lemma leading_coeff_mul (p q : R[X]) : leading_coeff (p * q) = leading_coeff p * leading_coeff q := begin by_cases hp : p = 0, { simp only [hp, zero_mul, leading_coeff_zero] }, { by_cases hq : q = 0, { simp only [hq, mul_zero, leading_coeff_zero] }, { rw [leading_coeff_mul'], exact mul_ne_zero (mt leading_coeff_eq_zero.1 hp) (mt leading_coeff_eq_zero.1 hq) } } end /-- `polynomial.leading_coeff` bundled as a `monoid_hom` when `R` has `no_zero_divisors`, and thus `leading_coeff` is multiplicative -/ def leading_coeff_hom : R[X] →* R := { to_fun := leading_coeff, map_one' := by simp, map_mul' := leading_coeff_mul } @[simp] lemma leading_coeff_hom_apply (p : R[X]) : leading_coeff_hom p = leading_coeff p := rfl @[simp] lemma leading_coeff_pow (p : R[X]) (n : ℕ) : leading_coeff (p ^ n) = leading_coeff p ^ n := (leading_coeff_hom : R[X] →* R).map_pow p n end no_zero_divisors end polynomial
8a081a5333c4a8f5425cb89dd9bdcbc6d5208a52
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/stage0/src/Lean/Compiler/IR/SimpCase.lean
0560ebdaddb4e2f10014d2927724f06ea9540413
[ "Apache-2.0" ]
permissive
dupuisf/lean4
d082d13b01243e1de29ae680eefb476961221eef
6a39c65bd28eb0e28c3870188f348c8914502718
refs/heads/master
1,676,948,755,391
1,610,665,114,000
1,610,665,114,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,206
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.Compiler.IR.Basic import Lean.Compiler.IR.Format namespace Lean.IR def ensureHasDefault (alts : Array Alt) : Array Alt := if alts.any Alt.isDefault then alts else if alts.size < 2 then alts else let last := alts.back; let alts := alts.pop; alts.push (Alt.default last.body) private def getOccsOf (alts : Array Alt) (i : Nat) : Nat := do let aBody := (alts.get! i).body let mut n := 1 for j in [i+1:alts.size] do if alts[j].body == aBody then n := n+1 return n private def maxOccs (alts : Array Alt) : Alt × Nat := do let mut maxAlt := alts[0] let mut max := getOccsOf alts 0 for i in [1:alts.size] do let curr := getOccsOf alts i if curr > max then maxAlt := alts[i] max := curr return (maxAlt, max) private def addDefault (alts : Array Alt) : Array Alt := if alts.size <= 1 || alts.any Alt.isDefault then alts else let (max, noccs) := maxOccs alts; if noccs == 1 then alts else let alts := alts.filter $ (fun alt => alt.body != max.body); alts.push (Alt.default max.body) private def mkSimpCase (tid : Name) (x : VarId) (xType : IRType) (alts : Array Alt) : FnBody := let alts := alts.filter (fun alt => alt.body != FnBody.unreachable); let alts := addDefault alts; if alts.size == 0 then FnBody.unreachable else if alts.size == 1 then (alts.get! 0).body else FnBody.case tid x xType alts partial def FnBody.simpCase (b : FnBody) : FnBody := let (bs, term) := b.flatten; let bs := modifyJPs bs simpCase; match term with | FnBody.case tid x xType alts => let alts := alts.map $ fun alt => alt.modifyBody simpCase; reshape bs (mkSimpCase tid x xType alts) | other => reshape bs term /-- Simplify `case` - Remove unreachable branches. - Remove `case` if there is only one branch. - Merge most common branches using `Alt.default`. -/ def Decl.simpCase : Decl → Decl | Decl.fdecl f xs t b => Decl.fdecl f xs t b.simpCase | other => other end Lean.IR
a3937cfc576a6f56a0bdc95baf4ad10f09e21338
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/interval_cases.lean
264d1d23acfca4a5bc042d6f228ed49757a71a20
[]
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,408
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Scott Morrison Case bashing on variables in finite intervals. In particular, `interval_cases n` 1) inspects hypotheses looking for lower and upper bounds of the form `a ≤ n` and `n < b` (although in `ℕ`, `ℤ`, and `ℕ+` bounds of the form `a < n` and `n ≤ b` are also allowed), and also makes use of lower and upper bounds found via `le_top` and `bot_le` (so for example if `n : ℕ`, then the bound `0 ≤ n` is found automatically), then 2) calls `fin_cases` on the synthesised hypothesis `n ∈ set.Ico a b`, assuming an appropriate `fintype` instance can be found for the type of `n`. The variable `n` can belong to any type `α`, with the following restrictions: * only bounds on which `expr.to_rat` succeeds will be considered "explicit" (TODO: generalise this?) * an instance of `decidable_eq α` is available, * an explicit lower bound can be found amongst the hypotheses, or from `bot_le n`, * an explicit upper bound can be found amongst the hypotheses, or from `le_top n`, * if multiple bounds are located, an instance of `linear_order α` is available, and * an instance of `fintype set.Ico l u` is available for the relevant bounds. You can also explicitly specify a lower and upper bound to use, as `interval_cases using hl hu`. The hypotheses should be in the form `hl : a ≤ n` and `hu : n < b`, in which case `interval_cases` calls `fin_cases` on the resulting fact `n ∈ set.Ico a b`. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.fin_cases import Mathlib.data.fintype.intervals import Mathlib.PostPort universes u_1 namespace Mathlib namespace tactic namespace interval_cases /-- If `e` easily implies `(%%n < %%b)` for some explicit `b`, return that proof. -/ -- We use `expr.to_rat` merely to decide if an `expr` is an explicit number. -- It would be more natural to use `expr.to_int`, but that hasn't been implemented. /-- If `e` easily implies `(%%n ≥ %%b)` for some explicit `b`, return that proof. -/ /-- Combine two upper bounds. -/ /-- Combine two lower bounds. -/ /-- Inspect a given expression, using it to update a set of upper and lower bounds on `n`. -/ /-- Attempt to find a lower bound for the variable `n`, by evaluating `bot_le n`. -/ /-- Attempt to find an upper bound for the variable `n`, by evaluating `le_top n`. -/ /-- Inspect the local hypotheses for upper and lower bounds on a variable `n`. -/ /-- The finset of elements of a set `s` for which we have `fintype s`. -/ def set_elems {α : Type u_1} [DecidableEq α] (s : set α) [fintype ↥s] : finset α := finset.image subtype.val (fintype.elems ↥s) /-- Each element of `s` is a member of `set_elems s`. -/ theorem mem_set_elems {α : Type u_1} [DecidableEq α] (s : set α) [fintype ↥s] {a : α} (h : a ∈ s) : a ∈ set_elems s := iff.mpr finset.mem_image (Exists.intro { val := a, property := h } (Exists.intro (fintype.complete { val := a, property := h }) rfl)) end interval_cases /-- Call `fin_cases` on membership of the finset built from an `Ico` interval corresponding to a lower and an upper bound. Here `hl` should be an expression of the form `a ≤ n`, for some explicit `a`, and `hu` should be of the form `n < b`, for some explicit `b`. By default `interval_cases_using` automatically generates a name for the new hypothesis. The name can be specified via the optional argument `n`. -/ namespace interactive /-- `interval_cases n` searches for upper and lower bounds on a variable `n`, and if bounds are found, splits into separate cases for each possible value of `n`. As an example, in ``` example (n : ℕ) (w₁ : n ≥ 3) (w₂ : n < 5) : n = 3 ∨ n = 4 := begin interval_cases n, all_goals {simp} end ``` after `interval_cases n`, the goals are `3 = 3 ∨ 3 = 4` and `4 = 3 ∨ 4 = 4`. You can also explicitly specify a lower and upper bound to use, as `interval_cases using hl hu`. The hypotheses should be in the form `hl : a ≤ n` and `hu : n < b`, in which case `interval_cases` calls `fin_cases` on the resulting fact `n ∈ set.Ico a b`. You can specify a name `h` for the new hypothesis, as `interval_cases n with h` or `interval_cases n using hl hu with h`. -/ /-- `interval_cases n` searches for upper and lower bounds on a variable `n`,
152b0159f2cbf3d22d758afd728078a1694feffd
6b02ce66658141f3e0aa3dfa88cd30bbbb24d17b
/src/Lean/Elab/Do.lean
edec7eb49dc544f86055ea1b82b462e1eeb2784b
[ "Apache-2.0" ]
permissive
pbrinkmeier/lean4
d31991fd64095e64490cb7157bcc6803f9c48af4
32fd82efc2eaf1232299e930ec16624b370eac39
refs/heads/master
1,681,364,001,662
1,618,425,427,000
1,618,425,427,000
358,314,562
0
0
Apache-2.0
1,618,504,558,000
1,618,501,999,000
null
UTF-8
Lean
false
false
66,372
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.Term import Lean.Elab.Binders import Lean.Elab.Match import Lean.Elab.Quotation.Util import Lean.Parser.Do namespace Lean.Elab.Term open Lean.Parser.Term open Meta private def getDoSeqElems (doSeq : Syntax) : List Syntax := if doSeq.getKind == `Lean.Parser.Term.doSeqBracketed then doSeq[1].getArgs.toList.map fun arg => arg[0] else if doSeq.getKind == `Lean.Parser.Term.doSeqIndent then doSeq[0].getArgs.toList.map fun arg => arg[0] else [] private def getDoSeq (doStx : Syntax) : Syntax := doStx[1] @[builtinTermElab liftMethod] def elabLiftMethod : TermElab := fun stx _ => throwErrorAt stx "invalid use of `(<- ...)`, must be nested inside a 'do' expression" /-- Return true if we should not lift `(<- ...)` actions nested in the syntax nodes with the given kind. -/ private def liftMethodDelimiter (k : SyntaxNodeKind) : Bool := k == `Lean.Parser.Term.do || k == `Lean.Parser.Term.doSeqIndent || k == `Lean.Parser.Term.doSeqBracketed || k == `Lean.Parser.Term.termReturn || k == `Lean.Parser.Term.termUnless || k == `Lean.Parser.Term.termTry || k == `Lean.Parser.Term.termFor private partial def hasLiftMethod : Syntax → Bool | Syntax.node k args => if liftMethodDelimiter k then false -- NOTE: We don't check for lifts in quotations here, which doesn't break anything but merely makes this rare case a -- bit slower else if k == `Lean.Parser.Term.liftMethod then true else args.any hasLiftMethod | _ => false structure ExtractMonadResult where m : Expr α : Expr hasBindInst : Expr expectedType : Expr private def mkIdBindFor (type : Expr) : TermElabM ExtractMonadResult := do let u ← getDecLevel type let id := Lean.mkConst `Id [u] let idBindVal := Lean.mkConst `Id.hasBind [u] pure { m := id, hasBindInst := idBindVal, α := type, expectedType := mkApp id type } private def extractBind (expectedType? : Option Expr) : TermElabM ExtractMonadResult := do match expectedType? with | none => throwError "invalid 'do' notation, expected type is not available" | some expectedType => let type ← withReducible $ whnf expectedType if type.getAppFn.isMVar then throwError "invalid 'do' notation, expected type is not available" match type with | Expr.app m α _ => try let bindInstType ← mkAppM `Bind #[m] let bindInstVal ← synthesizeInst bindInstType pure { m := m, hasBindInst := bindInstVal, α := α, expectedType := expectedType } catch _ => mkIdBindFor type | _ => mkIdBindFor type namespace Do /- A `doMatch` alternative. `vars` is the array of variables declared by `patterns`. -/ structure Alt (σ : Type) where ref : Syntax vars : Array Name patterns : Syntax rhs : σ deriving Inhabited /- Auxiliary datastructure for representing a `do` code block, and compiling "reassignments" (e.g., `x := x + 1`). We convert `Code` into a `Syntax` term representing the: - `do`-block, or - the visitor argument for the `forIn` combinator. We say the following constructors are terminals: - `break`: for interrupting a `for x in s` - `continue`: for interrupting the current iteration of a `for x in s` - `return e`: for returning `e` as the result for the whole `do` computation block - `action a`: for executing action `a` as a terminal - `ite`: if-then-else - `match`: pattern matching - `jmp` a goto to a join-point We say the terminals `break`, `continue`, `action`, and `return` are "exit points" Note that, `return e` is not equivalent to `action (pure e)`. Here is an example: ``` def f (x : Nat) : IO Unit := do if x == 0 then return () IO.println "hello" ``` Executing `#eval f 0` will not print "hello". Now, consider ``` def g (x : Nat) : IO Unit := do if x == 0 then pure () IO.println "hello" ``` The `if` statement is essentially a noop, and "hello" is printed when we execute `g 0`. - `decl` represents all declaration-like `doElem`s (e.g., `let`, `have`, `let rec`). The field `stx` is the actual `doElem`, `vars` is the array of variables declared by it, and `cont` is the next instruction in the `do` code block. `vars` is an array since we have declarations such as `let (a, b) := s`. - `reassign` is an reassignment-like `doElem` (e.g., `x := x + 1`). - `joinpoint` is a join point declaration: an auxiliary `let`-declaration used to represent the control-flow. - `seq a k` executes action `a`, ignores its result, and then executes `k`. We also store the do-elements `dbg_trace` and `assert!` as actions in a `seq`. A code block `C` is well-formed if - For every `jmp ref j as` in `C`, there is a `joinpoint j ps b k` and `jmp ref j as` is in `k`, and `ps.size == as.size` -/ inductive Code where | decl (xs : Array Name) (doElem : Syntax) (k : Code) | reassign (xs : Array Name) (doElem : Syntax) (k : Code) /- The Boolean value in `params` indicates whether we should use `(x : typeof! x)` when generating term Syntax or not -/ | joinpoint (name : Name) (params : Array (Name × Bool)) (body : Code) (k : Code) | seq (action : Syntax) (k : Code) | action (action : Syntax) | «break» (ref : Syntax) | «continue» (ref : Syntax) | «return» (ref : Syntax) (val : Syntax) /- Recall that an if-then-else may declare a variable using `optIdent` for the branches `thenBranch` and `elseBranch`. We store the variable name at `var?`. -/ | ite (ref : Syntax) (h? : Option Name) (optIdent : Syntax) (cond : Syntax) (thenBranch : Code) (elseBranch : Code) | «match» (ref : Syntax) (discrs : Syntax) (optType : Syntax) (alts : Array (Alt Code)) | jmp (ref : Syntax) (jpName : Name) (args : Array Syntax) deriving Inhabited /- A code block, and the collection of variables updated by it. -/ structure CodeBlock where code : Code uvars : NameSet := {} -- set of variables updated by `code` private def nameSetToArray (s : NameSet) : Array Name := s.fold (fun (xs : Array Name) x => xs.push x) #[] private def varsToMessageData (vars : Array Name) : MessageData := MessageData.joinSep (vars.toList.map fun n => MessageData.ofName (n.simpMacroScopes)) " " partial def CodeBlocl.toMessageData (codeBlock : CodeBlock) : MessageData := let us := MessageData.ofList $ (nameSetToArray codeBlock.uvars).toList.map MessageData.ofName let rec loop : Code → MessageData | Code.decl xs _ k => m!"let {varsToMessageData xs} := ...\n{loop k}" | Code.reassign xs _ k => m!"{varsToMessageData xs} := ...\n{loop k}" | Code.joinpoint n ps body k => m!"let {n.simpMacroScopes} {varsToMessageData (ps.map Prod.fst)} := {indentD (loop body)}\n{loop k}" | Code.seq e k => m!"{e}\n{loop k}" | Code.action e => e | Code.ite _ _ _ c t e => m!"if {c} then {indentD (loop t)}\nelse{loop e}" | Code.jmp _ j xs => m!"jmp {j.simpMacroScopes} {xs.toList}" | Code.«break» _ => m!"break {us}" | Code.«continue» _ => m!"continue {us}" | Code.«return» _ v => m!"return {v} {us}" | Code.«match» _ ds t alts => m!"match {ds} with" ++ alts.foldl (init := m!"") fun acc alt => acc ++ m!"\n| {alt.patterns} => {loop alt.rhs}" loop codeBlock.code /- Return true if the give code contains an exit point that satisfies `p` -/ @[inline] partial def hasExitPointPred (c : Code) (p : Code → Bool) : Bool := let rec @[specialize] loop : Code → Bool | Code.decl _ _ k => loop k | Code.reassign _ _ k => loop k | Code.joinpoint _ _ b k => loop b || loop k | Code.seq _ k => loop k | Code.ite _ _ _ _ t e => loop t || loop e | Code.«match» _ _ _ alts => alts.any (loop ·.rhs) | Code.jmp _ _ _ => false | c => p c loop c def hasExitPoint (c : Code) : Bool := hasExitPointPred c fun c => true def hasReturn (c : Code) : Bool := hasExitPointPred c fun | Code.«return» _ _ => true | _ => false def hasTerminalAction (c : Code) : Bool := hasExitPointPred c fun | Code.«action» _ => true | _ => false def hasBreakContinue (c : Code) : Bool := hasExitPointPred c fun | Code.«break» _ => true | Code.«continue» _ => true | _ => false def hasBreakContinueReturn (c : Code) : Bool := hasExitPointPred c fun | Code.«break» _ => true | Code.«continue» _ => true | Code.«return» _ _ => true | _ => false def mkAuxDeclFor {m} [Monad m] [MonadQuotation m] (e : Syntax) (mkCont : Syntax → m Code) : m Code := withRef e <| withFreshMacroScope do let y ← `(y) let yName := y.getId let doElem ← `(doElem| let y ← $e:term) -- Add elaboration hint for producing sane error message let y ← `(ensureExpectedType% "type mismatch, result value" $y) let k ← mkCont y pure $ Code.decl #[yName] doElem k /- Convert `action _ e` instructions in `c` into `let y ← e; jmp _ jp (xs y)`. -/ partial def convertTerminalActionIntoJmp (code : Code) (jp : Name) (xs : Array Name) : MacroM Code := let rec loop : Code → MacroM Code | Code.decl xs stx k => do Code.decl xs stx (← loop k) | Code.reassign xs stx k => do Code.reassign xs stx (← loop k) | Code.joinpoint n ps b k => do Code.joinpoint n ps (← loop b) (← loop k) | Code.seq e k => do Code.seq e (← loop k) | Code.ite ref x? h c t e => do Code.ite ref x? h c (← loop t) (← loop e) | Code.«match» ref ds t alts => do Code.«match» ref ds t (← alts.mapM fun alt => do pure { alt with rhs := (← loop alt.rhs) }) | Code.action e => mkAuxDeclFor e fun y => let ref := e -- We jump to `jp` with xs **and** y let jmpArgs := xs.map $ mkIdentFrom ref let jmpArgs := jmpArgs.push y pure $ Code.jmp ref jp jmpArgs | c => pure c loop code structure JPDecl where name : Name params : Array (Name × Bool) body : Code def attachJP (jpDecl : JPDecl) (k : Code) : Code := Code.joinpoint jpDecl.name jpDecl.params jpDecl.body k def attachJPs (jpDecls : Array JPDecl) (k : Code) : Code := jpDecls.foldr attachJP k def mkFreshJP (ps : Array (Name × Bool)) (body : Code) : TermElabM JPDecl := do let ps ← if ps.isEmpty then let y ← mkFreshUserName `y pure #[(y, false)] else pure ps -- Remark: the compiler frontend implemented in C++ currently detects jointpoints created by -- the "do" notation by testing the name. See hack at method `visit_let` at `lcnf.cpp` -- We will remove this hack when we re-implement the compiler frontend in Lean. let name ← mkFreshUserName `_do_jp pure { name := name, params := ps, body := body } def mkFreshJP' (xs : Array Name) (body : Code) : TermElabM JPDecl := mkFreshJP (xs.map fun x => (x, true)) body def addFreshJP (ps : Array (Name × Bool)) (body : Code) : StateRefT (Array JPDecl) TermElabM Name := do let jp ← mkFreshJP ps body modify fun (jps : Array JPDecl) => jps.push jp pure jp.name def insertVars (rs : NameSet) (xs : Array Name) : NameSet := xs.foldl (·.insert ·) rs def eraseVars (rs : NameSet) (xs : Array Name) : NameSet := xs.foldl (·.erase ·) rs def eraseOptVar (rs : NameSet) (x? : Option Name) : NameSet := match x? with | none => rs | some x => rs.insert x /- Create a new jointpoint for `c`, and jump to it with the variables `rs` -/ def mkSimpleJmp (ref : Syntax) (rs : NameSet) (c : Code) : StateRefT (Array JPDecl) TermElabM Code := do let xs := nameSetToArray rs let jp ← addFreshJP (xs.map fun x => (x, true)) c if xs.isEmpty then let unit ← `(Unit.unit) return Code.jmp ref jp #[unit] else return Code.jmp ref jp (xs.map $ mkIdentFrom ref) /- Create a new joinpoint that takes `rs` and `val` as arguments. `val` must be syntax representing a pure value. The body of the joinpoint is created using `mkJPBody yFresh`, where `yFresh` is a fresh variable created by this method. -/ def mkJmp (ref : Syntax) (rs : NameSet) (val : Syntax) (mkJPBody : Syntax → MacroM Code) : StateRefT (Array JPDecl) TermElabM Code := do let xs := nameSetToArray rs let args := xs.map $ mkIdentFrom ref let args := args.push val let yFresh ← mkFreshUserName `y let ps := xs.map fun x => (x, true) let ps := ps.push (yFresh, false) let jpBody ← liftMacroM $ mkJPBody (mkIdentFrom ref yFresh) let jp ← addFreshJP ps jpBody pure $ Code.jmp ref jp args /- `pullExitPointsAux rs c` auxiliary method for `pullExitPoints`, `rs` is the set of update variable in the current path. -/ partial def pullExitPointsAux : NameSet → Code → StateRefT (Array JPDecl) TermElabM Code | rs, Code.decl xs stx k => do Code.decl xs stx (← pullExitPointsAux (eraseVars rs xs) k) | rs, Code.reassign xs stx k => do Code.reassign xs stx (← pullExitPointsAux (insertVars rs xs) k) | rs, Code.joinpoint j ps b k => do Code.joinpoint j ps (← pullExitPointsAux rs b) (← pullExitPointsAux rs k) | rs, Code.seq e k => do Code.seq e (← pullExitPointsAux rs k) | rs, Code.ite ref x? o c t e => do Code.ite ref x? o c (← pullExitPointsAux (eraseOptVar rs x?) t) (← pullExitPointsAux (eraseOptVar rs x?) e) | rs, Code.«match» ref ds t alts => do Code.«match» ref ds t (← alts.mapM fun alt => do pure { alt with rhs := (← pullExitPointsAux (eraseVars rs alt.vars) alt.rhs) }) | rs, c@(Code.jmp _ _ _) => pure c | rs, Code.«break» ref => mkSimpleJmp ref rs (Code.«break» ref) | rs, Code.«continue» ref => mkSimpleJmp ref rs (Code.«continue» ref) | rs, Code.«return» ref val => mkJmp ref rs val (fun y => pure $ Code.«return» ref y) | rs, Code.action e => -- We use `mkAuxDeclFor` because `e` is not pure. mkAuxDeclFor e fun y => let ref := e mkJmp ref rs y (fun yFresh => do pure $ Code.action (← `(Pure.pure $yFresh))) /- Auxiliary operation for adding new variables to the collection of updated variables in a CodeBlock. When a new variable is not already in the collection, but is shadowed by some declaration in `c`, we create auxiliary join points to make sure we preserve the semantics of the code block. Example: suppose we have the code block `print x; let x := 10; return x`. And we want to extend it with the reassignment `x := x + 1`. We first use `pullExitPoints` to create ``` let jp (x!1) := return x!1; print x; let x := 10; jmp jp x ``` and then we add the reassignment ``` x := x + 1 let jp (x!1) := return x!1; print x; let x := 10; jmp jp x ``` Note that we created a fresh variable `x!1` to avoid accidental name capture. As another example, consider ``` print x; let x := 10 y := y + 1; return x; ``` We transform it into ``` let jp (y x!1) := return x!1; print x; let x := 10 y := y + 1; jmp jp y x ``` and then we add the reassignment as in the previous example. We need to include `y` in the jump, because each exit point is implicitly returning the set of update variables. We implement the method as follows. Let `us` be `c.uvars`, then 1- for each `return _ y` in `c`, we create a join point `let j (us y!1) := return y!1` and replace the `return _ y` with `jmp us y` 2- for each `break`, we create a join point `let j (us) := break` and replace the `break` with `jmp us`. 3- Same as 2 for `continue`. -/ def pullExitPoints (c : Code) : TermElabM Code := do if hasExitPoint c then let (c, jpDecls) ← (pullExitPointsAux {} c).run #[] pure $ attachJPs jpDecls c else pure c partial def extendUpdatedVarsAux (c : Code) (ws : NameSet) : TermElabM Code := let rec update : Code → TermElabM Code | Code.joinpoint j ps b k => do Code.joinpoint j ps (← update b) (← update k) | Code.seq e k => do Code.seq e (← update k) | c@(Code.«match» ref ds t alts) => do if alts.any fun alt => alt.vars.any fun x => ws.contains x then -- If a pattern variable is shadowing a variable in ws, we `pullExitPoints` pullExitPoints c else Code.«match» ref ds t (← alts.mapM fun alt => do pure { alt with rhs := (← update alt.rhs) }) | Code.ite ref none o c t e => do Code.ite ref none o c (← update t) (← update e) | c@(Code.ite ref (some h) o cond t e) => do if ws.contains h then -- if the `h` at `if h:c then t else e` shadows a variable in `ws`, we `pullExitPoints` pullExitPoints c else Code.ite ref (some h) o cond (← update t) (← update e) | Code.reassign xs stx k => do Code.reassign xs stx (← update k) | c@(Code.decl xs stx k) => do if xs.any fun x => ws.contains x then -- One the declared variables is shadowing a variable in `ws` pullExitPoints c else Code.decl xs stx (← update k) | c => pure c update c /- Extend the set of updated variables. It assumes `ws` is a super set of `c.uvars`. We **cannot** simply update the field `c.uvars`, because `c` may have shadowed some variable in `ws`. See discussion at `pullExitPoints`. -/ partial def extendUpdatedVars (c : CodeBlock) (ws : NameSet) : TermElabM CodeBlock := do if ws.any fun x => !c.uvars.contains x then -- `ws` contains a variable that is not in `c.uvars`, but in `c.dvars` (i.e., it has been shadowed) pure { code := (← extendUpdatedVarsAux c.code ws), uvars := ws } else pure { c with uvars := ws } private def union (s₁ s₂ : NameSet) : NameSet := s₁.fold (·.insert ·) s₂ /- Given two code blocks `c₁` and `c₂`, make sure they have the same set of updated variables. Let `ws` the union of the updated variables in `c₁‵ and ‵c₂`. We use `extendUpdatedVars c₁ ws` and `extendUpdatedVars c₂ ws` -/ def homogenize (c₁ c₂ : CodeBlock) : TermElabM (CodeBlock × CodeBlock) := do let ws := union c₁.uvars c₂.uvars let c₁ ← extendUpdatedVars c₁ ws let c₂ ← extendUpdatedVars c₂ ws pure (c₁, c₂) /- Extending code blocks with variable declarations: `let x : t := v` and `let x : t ← v`. We remove `x` from the collection of updated varibles. Remark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables declared by it. It is an array because we have let-declarations that declare multiple variables. Example: `let (x, y) := t` -/ def mkVarDeclCore (xs : Array Name) (stx : Syntax) (c : CodeBlock) : CodeBlock := { code := Code.decl xs stx c.code, uvars := eraseVars c.uvars xs } /- Extending code blocks with reassignments: `x : t := v` and `x : t ← v`. Remark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables declared by it. It is an array because we have let-declarations that declare multiple variables. Example: `(x, y) ← t` -/ def mkReassignCore (xs : Array Name) (stx : Syntax) (c : CodeBlock) : TermElabM CodeBlock := do let us := c.uvars let ws := insertVars us xs -- If `xs` contains a new updated variable, then we must use `extendUpdatedVars`. -- See discussion at `pullExitPoints` let code ← if xs.any fun x => !us.contains x then extendUpdatedVarsAux c.code ws else pure c.code pure { code := Code.reassign xs stx code, uvars := ws } def mkSeq (action : Syntax) (c : CodeBlock) : CodeBlock := { c with code := Code.seq action c.code } def mkTerminalAction (action : Syntax) : CodeBlock := { code := Code.action action } def mkReturn (ref : Syntax) (val : Syntax) : CodeBlock := { code := Code.«return» ref val } def mkBreak (ref : Syntax) : CodeBlock := { code := Code.«break» ref } def mkContinue (ref : Syntax) : CodeBlock := { code := Code.«continue» ref } def mkIte (ref : Syntax) (optIdent : Syntax) (cond : Syntax) (thenBranch : CodeBlock) (elseBranch : CodeBlock) : TermElabM CodeBlock := do let x? := if optIdent.isNone then none else some optIdent[0].getId let (thenBranch, elseBranch) ← homogenize thenBranch elseBranch pure { code := Code.ite ref x? optIdent cond thenBranch.code elseBranch.code, uvars := thenBranch.uvars, } private def mkUnit : MacroM Syntax := `((⟨⟩ : PUnit)) private def mkPureUnit : MacroM Syntax := `(pure PUnit.unit) def mkPureUnitAction : MacroM CodeBlock := do mkTerminalAction (← mkPureUnit) def mkUnless (cond : Syntax) (c : CodeBlock) : MacroM CodeBlock := do let thenBranch ← mkPureUnitAction pure { c with code := Code.ite (← getRef) none mkNullNode cond thenBranch.code c.code } def mkMatch (ref : Syntax) (discrs : Syntax) (optType : Syntax) (alts : Array (Alt CodeBlock)) : TermElabM CodeBlock := do -- nary version of homogenize let ws := alts.foldl (union · ·.rhs.uvars) {} let alts ← alts.mapM fun alt => do let rhs ← extendUpdatedVars alt.rhs ws pure { ref := alt.ref, vars := alt.vars, patterns := alt.patterns, rhs := rhs.code : Alt Code } pure { code := Code.«match» ref discrs optType alts, uvars := ws } /- Return a code block that executes `terminal` and then `k` with the value produced by `terminal`. This method assumes `terminal` is a terminal -/ def concat (terminal : CodeBlock) (kRef : Syntax) (y? : Option Name) (k : CodeBlock) : TermElabM CodeBlock := do unless hasTerminalAction terminal.code do throwErrorAt kRef "'do' element is unreachable" let (terminal, k) ← homogenize terminal k let xs := nameSetToArray k.uvars let y ← match y? with | some y => pure y | none => mkFreshUserName `y let ps := xs.map fun x => (x, true) let ps := ps.push (y, false) let jpDecl ← mkFreshJP ps k.code let jp := jpDecl.name let terminal ← liftMacroM $ convertTerminalActionIntoJmp terminal.code jp xs pure { code := attachJP jpDecl terminal, uvars := k.uvars } def getLetIdDeclVar (letIdDecl : Syntax) : Name := letIdDecl[0].getId def getPatternVarNames (pvars : Array PatternVar) : Array Name := pvars.filterMap fun | PatternVar.localVar x => some x | _ => none -- support both regular and syntax match def getPatternVarsEx (pattern : Syntax) : TermElabM (Array Name) := getPatternVarNames <$> getPatternVars pattern <|> Array.map Syntax.getId <$> Quotation.getPatternVars pattern def getPatternsVarsEx (patterns : Array Syntax) : TermElabM (Array Name) := getPatternVarNames <$> getPatternsVars patterns <|> Array.map Syntax.getId <$> Quotation.getPatternsVars patterns def getLetPatDeclVars (letPatDecl : Syntax) : TermElabM (Array Name) := do let pattern := letPatDecl[0] getPatternVarsEx pattern def getLetEqnsDeclVar (letEqnsDecl : Syntax) : Name := letEqnsDecl[0].getId def getLetDeclVars (letDecl : Syntax) : TermElabM (Array Name) := do let arg := letDecl[0] if arg.getKind == `Lean.Parser.Term.letIdDecl then pure #[getLetIdDeclVar arg] else if arg.getKind == `Lean.Parser.Term.letPatDecl then getLetPatDeclVars arg else if arg.getKind == `Lean.Parser.Term.letEqnsDecl then pure #[getLetEqnsDeclVar arg] else throwError "unexpected kind of let declaration" def getDoLetVars (doLet : Syntax) : TermElabM (Array Name) := -- leading_parser "let " >> optional "mut " >> letDecl getLetDeclVars doLet[2] def getDoHaveVar (doHave : Syntax) : Name := /- `leading_parser "have " >> Term.haveDecl` where ``` haveDecl := leading_parser optIdent >> termParser >> (haveAssign <|> fromTerm <|> byTactic) optIdent := optional (try (ident >> " : ")) ``` -/ let optIdent := doHave[1][0] if optIdent.isNone then `this else optIdent[0].getId def getDoLetRecVars (doLetRec : Syntax) : TermElabM (Array Name) := do -- letRecDecls is an array of `(group (optional attributes >> letDecl))` let letRecDecls := doLetRec[1][0].getSepArgs let letDecls := letRecDecls.map fun p => p[2] let mut allVars := #[] for letDecl in letDecls do let vars ← getLetDeclVars letDecl allVars := allVars ++ vars pure allVars -- ident >> optType >> leftArrow >> termParser def getDoIdDeclVar (doIdDecl : Syntax) : Name := doIdDecl[0].getId -- termParser >> leftArrow >> termParser >> optional (" | " >> termParser) def getDoPatDeclVars (doPatDecl : Syntax) : TermElabM (Array Name) := do let pattern := doPatDecl[0] getPatternVarsEx pattern -- leading_parser "let " >> optional "mut " >> (doIdDecl <|> doPatDecl) def getDoLetArrowVars (doLetArrow : Syntax) : TermElabM (Array Name) := do let decl := doLetArrow[2] if decl.getKind == `Lean.Parser.Term.doIdDecl then pure #[getDoIdDeclVar decl] else if decl.getKind == `Lean.Parser.Term.doPatDecl then getDoPatDeclVars decl else throwError "unexpected kind of 'do' declaration" def getDoReassignVars (doReassign : Syntax) : TermElabM (Array Name) := do let arg := doReassign[0] if arg.getKind == `Lean.Parser.Term.letIdDecl then pure #[getLetIdDeclVar arg] else if arg.getKind == `Lean.Parser.Term.letPatDecl then getLetPatDeclVars arg else throwError "unexpected kind of reassignment" def mkDoSeq (doElems : Array Syntax) : Syntax := mkNode `Lean.Parser.Term.doSeqIndent #[mkNullNode $ doElems.map fun doElem => mkNullNode #[doElem, mkNullNode]] def mkSingletonDoSeq (doElem : Syntax) : Syntax := mkDoSeq #[doElem] /- If the given syntax is a `doIf`, return an equivalente `doIf` that has an `else` but no `else if`s or `if let`s. -/ private def expandDoIf? (stx : Syntax) : MacroM (Option Syntax) := match stx with | `(doElem|if $p:doIfProp then $t else $e) => pure none | `(doElem|if%$i $cond:doIfCond then $t $[else if%$is $conds:doIfCond then $ts]* $[else $e?]?) => withRef stx do let mut e := e?.getD (← `(doSeq|pure PUnit.unit)) let mut eIsSeq := true for (i, cond, t) in Array.zip (is.reverse.push i) (Array.zip (conds.reverse.push cond) (ts.reverse.push t)) do e ← if eIsSeq then e else `(doSeq|$e:doElem) e ← withRef cond <| match cond with | `(doIfCond|let $pat := $d) => `(doElem| match%$i $d:term with | $pat:term => $t | _ => $e) | `(doIfCond|let $pat ← $d) => `(doElem| match%$i ← $d with | $pat:term => $t | _ => $e) | `(doIfCond|$cond:doIfProp) => `(doElem| if%$i $cond:doIfProp then $t else $e) | _ => `(doElem| if%$i $(Syntax.missing) then $t else $e) eIsSeq := false return some e | _ => pure none structure DoIfView where ref : Syntax optIdent : Syntax cond : Syntax thenBranch : Syntax elseBranch : Syntax /- This method assumes `expandDoIf?` is not applicable. -/ private def mkDoIfView (doIf : Syntax) : MacroM DoIfView := do pure { ref := doIf, optIdent := doIf[1][0], cond := doIf[1][1], thenBranch := doIf[3], elseBranch := doIf[5][1] } /- We use `MProd` instead of `Prod` to group values when expanding the `do` notation. `MProd` is a universe monomorphic product. The motivation is to generate simpler universe constraints in code that was not written by the user. Note that we are not restricting the macro power since the `Bind.bind` combinator already forces values computed by monadic actions to be in the same universe. -/ private def mkTuple (elems : Array Syntax) : MacroM Syntax := do if elems.size == 0 then mkUnit else if elems.size == 1 then pure elems[0] else (elems.extract 0 (elems.size - 1)).foldrM (fun elem tuple => `(MProd.mk $elem $tuple)) (elems.back) /- Return `some action` if `doElem` is a `doExpr <action>`-/ def isDoExpr? (doElem : Syntax) : Option Syntax := if doElem.getKind == `Lean.Parser.Term.doExpr then some doElem[0] else none /-- Given `uvars := #[a_1, ..., a_n, a_{n+1}]` construct term ``` let a_1 := x.1 let x := x.2 let a_2 := x.1 let x := x.2 ... let a_n := x.1 let a_{n+1} := x.2 body ``` Special cases - `uvars := #[]` => `body` - `uvars := #[a]` => `let a := x; body` We use this method when expanding the `for-in` notation. -/ private def destructTuple (uvars : Array Name) (x : Syntax) (body : Syntax) : MacroM Syntax := do if uvars.size == 0 then return body else if uvars.size == 1 then `(let $(← mkIdentFromRef uvars[0]):ident := $x; $body) else destruct uvars.toList x body where destruct (as : List Name) (x : Syntax) (body : Syntax) : MacroM Syntax := do match as with | [a, b] => `(let $(← mkIdentFromRef a):ident := $x.1; let $(← mkIdentFromRef b):ident := $x.2; $body) | a :: as => withFreshMacroScope do let rest ← destruct as (← `(x)) body `(let $(← mkIdentFromRef a):ident := $x.1; let x := $x.2; $rest) | _ => unreachable! /- The procedure `ToTerm.run` converts a `CodeBlock` into a `Syntax` term. We use this method to convert 1- The `CodeBlock` for a root `do ...` term into a `Syntax` term. This kind of `CodeBlock` never contains `break` nor `continue`. Moreover, the collection of updated variables is not packed into the result. Thus, we have two kinds of exit points - `Code.action e` which is converted into `e` - `Code.return _ e` which is converted into `pure e` We use `Kind.regular` for this case. 2- The `CodeBlock` for `b` at `for x in xs do b`. In this case, we need to generate a `Syntax` term representing a function for the `xs.forIn` combinator. a) If `b` contain a `Code.return _ a` exit point. The generated `Syntax` term has type `m (ForInStep (Option α × σ))`, where `a : α`, and the `σ` is the type of the tuple of variables reassigned by `b`. We use `Kind.forInWithReturn` for this case b) If `b` does not contain a `Code.return _ a` exit point. Then, the generated `Syntax` term has type `m (ForInStep σ)`. We use `Kind.forIn` for this case. 3- The `CodeBlock` `c` for a `do` sequence nested in a monadic combinator (e.g., `MonadExcept.tryCatch`). The generated `Syntax` term for `c` must inform whether `c` "exited" using `Code.action`, `Code.return`, `Code.break` or `Code.continue`. We use the auxiliary types `DoResult`s for storing this information. For example, the auxiliary type `DoResultPBC α σ` is used for a code block that exits with `Code.action`, **and** `Code.break`/`Code.continue`, `α` is the type of values produced by the exit `action`, and `σ` is the type of the tuple of reassigned variables. The type `DoResult α β σ` is usedf for code blocks that exit with `Code.action`, `Code.return`, **and** `Code.break`/`Code.continue`, `β` is the type of the returned values. We don't use `DoResult α β σ` for all cases because: a) The elaborator would not be able to infer all type parameters without extra annotations. For example, if the code block does not contain `Code.return _ _`, the elaborator will not be able to infer `β`. b) We need to pattern match on the result produced by the combinator (e.g., `MonadExcept.tryCatch`), but we don't want to consider "unreachable" cases. We do not distinguish between cases that contain `break`, but not `continue`, and vice versa. When listing all cases, we use `a` to indicate the code block contains `Code.action _`, `r` for `Code.return _ _`, and `b/c` for a code block that contains `Code.break _` or `Code.continue _`. - `a`: `Kind.regular`, type `m (α × σ)` - `r`: `Kind.regular`, type `m (α × σ)` Note that the code that pattern matches on the result will behave differently in this case. It produces `return a` for this case, and `pure a` for the previous one. - `b/c`: `Kind.nestedBC`, type `m (DoResultBC σ)` - `a` and `r`: `Kind.nestedPR`, type `m (DoResultPR α β σ)` - `a` and `bc`: `Kind.nestedSBC`, type `m (DoResultSBC α σ)` - `r` and `bc`: `Kind.nestedSBC`, type `m (DoResultSBC α σ)` Again the code that pattern matches on the result will behave differently in this case and the previous one. It produces `return a` for the constructor `DoResultSPR.pureReturn a u` for this case, and `pure a` for the previous case. - `a`, `r`, `b/c`: `Kind.nestedPRBC`, type type `m (DoResultPRBC α β σ)` Here is the recipe for adding new combinators with nested `do`s. Example: suppose we want to support `repeat doSeq`. Assuming we have `repeat : m α → m α` 1- Convert `doSeq` into `codeBlock : CodeBlock` 2- Create term `term` using `mkNestedTerm code m uvars a r bc` where `code` is `codeBlock.code`, `uvars` is an array containing `codeBlock.uvars`, `m` is a `Syntax` representing the Monad, and `a` is true if `code` contains `Code.action _`, `r` is true if `code` contains `Code.return _ _`, `bc` is true if `code` contains `Code.break _` or `Code.continue _`. Remark: for combinators such as `repeat` that take a single `doSeq`, all arguments, but `m`, are extracted from `codeBlock`. 3- Create the term `repeat $term` 4- and then, convert it into a `doSeq` using `matchNestedTermResult ref (repeat $term) uvsar a r bc` -/ namespace ToTerm inductive Kind where | regular | forIn | forInWithReturn | nestedBC | nestedPR | nestedSBC | nestedPRBC instance : Inhabited Kind := ⟨Kind.regular⟩ def Kind.isRegular : Kind → Bool | Kind.regular => true | _ => false structure Context where m : Syntax -- Syntax to reference the monad associated with the do notation. uvars : Array Name kind : Kind abbrev M := ReaderT Context MacroM def mkUVarTuple : M Syntax := do let ctx ← read let uvarIdents ← ctx.uvars.mapM mkIdentFromRef mkTuple uvarIdents def returnToTerm (val : Syntax) : M Syntax := do let ctx ← read let u ← mkUVarTuple match ctx.kind with | Kind.regular => if ctx.uvars.isEmpty then `(Pure.pure $val) else `(Pure.pure (MProd.mk $val $u)) | Kind.forIn => `(Pure.pure (ForInStep.done $u)) | Kind.forInWithReturn => `(Pure.pure (ForInStep.done (MProd.mk (some $val) $u))) | Kind.nestedBC => unreachable! | Kind.nestedPR => `(Pure.pure (DoResultPR.«return» $val $u)) | Kind.nestedSBC => `(Pure.pure (DoResultSBC.«pureReturn» $val $u)) | Kind.nestedPRBC => `(Pure.pure (DoResultPRBC.«return» $val $u)) def continueToTerm : M Syntax := do let ctx ← read let u ← mkUVarTuple match ctx.kind with | Kind.regular => unreachable! | Kind.forIn => `(Pure.pure (ForInStep.yield $u)) | Kind.forInWithReturn => `(Pure.pure (ForInStep.yield (MProd.mk none $u))) | Kind.nestedBC => `(Pure.pure (DoResultBC.«continue» $u)) | Kind.nestedPR => unreachable! | Kind.nestedSBC => `(Pure.pure (DoResultSBC.«continue» $u)) | Kind.nestedPRBC => `(Pure.pure (DoResultPRBC.«continue» $u)) def breakToTerm : M Syntax := do let ctx ← read let u ← mkUVarTuple match ctx.kind with | Kind.regular => unreachable! | Kind.forIn => `(Pure.pure (ForInStep.done $u)) | Kind.forInWithReturn => `(Pure.pure (ForInStep.done (MProd.mk none $u))) | Kind.nestedBC => `(Pure.pure (DoResultBC.«break» $u)) | Kind.nestedPR => unreachable! | Kind.nestedSBC => `(Pure.pure (DoResultSBC.«break» $u)) | Kind.nestedPRBC => `(Pure.pure (DoResultPRBC.«break» $u)) def actionTerminalToTerm (action : Syntax) : M Syntax := withRef action <| withFreshMacroScope do let ctx ← read let u ← mkUVarTuple match ctx.kind with | Kind.regular => if ctx.uvars.isEmpty then pure action else `(Bind.bind $action fun y => Pure.pure (MProd.mk y $u)) | Kind.forIn => `(Bind.bind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield $u)) | Kind.forInWithReturn => `(Bind.bind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield (MProd.mk none $u))) | Kind.nestedBC => unreachable! | Kind.nestedPR => `(Bind.bind $action fun y => (Pure.pure (DoResultPR.«pure» y $u))) | Kind.nestedSBC => `(Bind.bind $action fun y => (Pure.pure (DoResultSBC.«pureReturn» y $u))) | Kind.nestedPRBC => `(Bind.bind $action fun y => (Pure.pure (DoResultPRBC.«pure» y $u))) def seqToTerm (action : Syntax) (k : Syntax) : M Syntax := withRef action <| withFreshMacroScope do if action.getKind == `Lean.Parser.Term.doDbgTrace then let msg := action[1] `(dbg_trace $msg; $k) else if action.getKind == `Lean.Parser.Term.doAssert then let cond := action[1] `(assert! $cond; $k) else let action ← withRef action `(($action : $((←read).m) PUnit)) `(Bind.bind $action (fun (_ : PUnit) => $k)) def declToTerm (decl : Syntax) (k : Syntax) : M Syntax := withRef decl <| withFreshMacroScope do let kind := decl.getKind if kind == `Lean.Parser.Term.doLet then let letDecl := decl[2] `(let $letDecl:letDecl; $k) else if kind == `Lean.Parser.Term.doLetRec then let letRecToken := decl[0] let letRecDecls := decl[1] pure $ mkNode `Lean.Parser.Term.letrec #[letRecToken, letRecDecls, mkNullNode, k] else if kind == `Lean.Parser.Term.doLetArrow then let arg := decl[2] let ref := arg if arg.getKind == `Lean.Parser.Term.doIdDecl then let id := arg[0] let type := expandOptType ref arg[1] let doElem := arg[3] -- `doElem` must be a `doExpr action`. See `doLetArrowToCode` match isDoExpr? doElem with | some action => let action ← withRef action `(($action : $((← read).m) $type)) `(Bind.bind $action (fun ($id:ident : $type) => $k)) | none => Macro.throwErrorAt decl "unexpected kind of 'do' declaration" else Macro.throwErrorAt decl "unexpected kind of 'do' declaration" else if kind == `Lean.Parser.Term.doHave then -- The `have` term is of the form `"have " >> haveDecl >> optSemicolon termParser` let args := decl.getArgs let args := args ++ #[mkNullNode /- optional ';' -/, k] pure $ mkNode `Lean.Parser.Term.«have» args else Macro.throwErrorAt decl "unexpected kind of 'do' declaration" def reassignToTerm (reassign : Syntax) (k : Syntax) : MacroM Syntax := withRef reassign <| withFreshMacroScope do let kind := reassign.getKind if kind == `Lean.Parser.Term.doReassign then -- doReassign := leading_parser (letIdDecl <|> letPatDecl) let arg := reassign[0] if arg.getKind == `Lean.Parser.Term.letIdDecl then -- letIdDecl := leading_parser ident >> many (ppSpace >> bracketedBinder) >> optType >> " := " >> termParser let x := arg[0] let val := arg[4] let newVal ← `(ensureTypeOf% $x $(quote "invalid reassignment, value") $val) let arg := arg.setArg 4 newVal let letDecl := mkNode `Lean.Parser.Term.letDecl #[arg] `(let $letDecl:letDecl; $k) else -- TODO: ensure the types did not change let letDecl := mkNode `Lean.Parser.Term.letDecl #[arg] `(let $letDecl:letDecl; $k) else -- Note that `doReassignArrow` is expanded by `doReassignArrowToCode Macro.throwErrorAt reassign "unexpected kind of 'do' reassignment" def mkIte (optIdent : Syntax) (cond : Syntax) (thenBranch : Syntax) (elseBranch : Syntax) : MacroM Syntax := do if optIdent.isNone then `(ite $cond $thenBranch $elseBranch) else let h := optIdent[0] `(dite $cond (fun $h => $thenBranch) (fun $h => $elseBranch)) def mkJoinPoint (j : Name) (ps : Array (Name × Bool)) (body : Syntax) (k : Syntax) : M Syntax := withRef body <| withFreshMacroScope do let pTypes ← ps.mapM fun ⟨id, useTypeOf⟩ => do if useTypeOf then `(typeOf% $(← mkIdentFromRef id)) else `(_) let ps ← ps.mapM fun ⟨id, useTypeOf⟩ => mkIdentFromRef id /- We use `let_delayed` instead of `let` for joinpoints to make sure `$k` is elaborated before `$body`. By elaborating `$k` first, we "learn" more about `$body`'s type. For example, consider the following example `do` expression ``` def f (x : Nat) : IO Unit := do if x > 0 then IO.println "x is not zero" -- Error is here IO.mkRef true ``` it is expanded into ``` def f (x : Nat) : IO Unit := do let jp (u : Unit) : IO _ := IO.mkRef true; if x > 0 then IO.println "not zero" jp () else jp () ``` If we use the regular `let` instead of `let_delayed`, the joinpoint `jp` will be elaborated and its type will be inferred to be `Unit → IO (IO.Ref Bool)`. Then, we get a typing error at `jp ()`. By using `let_delayed`, we first elaborate `if x > 0 ...` and learn that `jp` has type `Unit → IO Unit`. Then, we get the expected type mismatch error at `IO.mkRef true`. -/ `(let_delayed $(← mkIdentFromRef j):ident $[($ps : $pTypes)]* : $((← read).m) _ := $body; $k) def mkJmp (ref : Syntax) (j : Name) (args : Array Syntax) : Syntax := Syntax.mkApp (mkIdentFrom ref j) args partial def toTerm : Code → M Syntax | Code.«return» ref val => withRef ref <| returnToTerm val | Code.«continue» ref => withRef ref continueToTerm | Code.«break» ref => withRef ref breakToTerm | Code.action e => actionTerminalToTerm e | Code.joinpoint j ps b k => do mkJoinPoint j ps (← toTerm b) (← toTerm k) | Code.jmp ref j args => pure $ mkJmp ref j args | Code.decl _ stx k => do declToTerm stx (← toTerm k) | Code.reassign _ stx k => do reassignToTerm stx (← toTerm k) | Code.seq stx k => do seqToTerm stx (← toTerm k) | Code.ite ref _ o c t e => withRef ref <| do mkIte o c (← toTerm t) (← toTerm e) | Code.«match» ref discrs optType alts => do let mut termAlts := #[] for alt in alts do let rhs ← toTerm alt.rhs let termAlt := mkNode `Lean.Parser.Term.matchAlt #[mkAtomFrom alt.ref "|", alt.patterns, mkAtomFrom alt.ref "=>", rhs] termAlts := termAlts.push termAlt let termMatchAlts := mkNode `Lean.Parser.Term.matchAlts #[mkNullNode termAlts] pure $ mkNode `Lean.Parser.Term.«match» #[mkAtomFrom ref "match", discrs, optType, mkAtomFrom ref "with", termMatchAlts] def run (code : Code) (m : Syntax) (uvars : Array Name := #[]) (kind := Kind.regular) : MacroM Syntax := do let term ← toTerm code { m := m, kind := kind, uvars := uvars } pure term /- Given - `a` is true if the code block has a `Code.action _` exit point - `r` is true if the code block has a `Code.return _ _` exit point - `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point generate Kind. See comment at the beginning of the `ToTerm` namespace. -/ def mkNestedKind (a r bc : Bool) : Kind := match a, r, bc with | true, false, false => Kind.regular | false, true, false => Kind.regular | false, false, true => Kind.nestedBC | true, true, false => Kind.nestedPR | true, false, true => Kind.nestedSBC | false, true, true => Kind.nestedSBC | true, true, true => Kind.nestedPRBC | false, false, false => unreachable! def mkNestedTerm (code : Code) (m : Syntax) (uvars : Array Name) (a r bc : Bool) : MacroM Syntax := do ToTerm.run code m uvars (mkNestedKind a r bc) /- Given a term `term` produced by `ToTerm.run`, pattern match on its result. See comment at the beginning of the `ToTerm` namespace. - `a` is true if the code block has a `Code.action _` exit point - `r` is true if the code block has a `Code.return _ _` exit point - `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point The result is a sequence of `doElem` -/ def matchNestedTermResult (term : Syntax) (uvars : Array Name) (a r bc : Bool) : MacroM (List Syntax) := do let toDoElems (auxDo : Syntax) : List Syntax := getDoSeqElems (getDoSeq auxDo) let u ← mkTuple (← uvars.mapM mkIdentFromRef) match a, r, bc with | true, false, false => if uvars.isEmpty then toDoElems (← `(do $term:term)) else toDoElems (← `(do let r ← $term:term; $u:term := r.2; pure r.1)) | false, true, false => if uvars.isEmpty then toDoElems (← `(do let r ← $term:term; return r)) else toDoElems (← `(do let r ← $term:term; $u:term := r.2; return r.1)) | false, false, true => toDoElems <$> `(do let r ← $term:term; match r with | DoResultBC.«break» u => $u:term := u; break | DoResultBC.«continue» u => $u:term := u; continue) | true, true, false => toDoElems <$> `(do let r ← $term:term; match r with | DoResultPR.«pure» a u => $u:term := u; pure a | DoResultPR.«return» b u => $u:term := u; return b) | true, false, true => toDoElems <$> `(do let r ← $term:term; match r with | DoResultSBC.«pureReturn» a u => $u:term := u; pure a | DoResultSBC.«break» u => $u:term := u; break | DoResultSBC.«continue» u => $u:term := u; continue) | false, true, true => toDoElems <$> `(do let r ← $term:term; match r with | DoResultSBC.«pureReturn» a u => $u:term := u; return a | DoResultSBC.«break» u => $u:term := u; break | DoResultSBC.«continue» u => $u:term := u; continue) | true, true, true => toDoElems <$> `(do let r ← $term:term; match r with | DoResultPRBC.«pure» a u => $u:term := u; pure a | DoResultPRBC.«return» a u => $u:term := u; return a | DoResultPRBC.«break» u => $u:term := u; break | DoResultPRBC.«continue» u => $u:term := u; continue) | false, false, false => unreachable! end ToTerm def isMutableLet (doElem : Syntax) : Bool := let kind := doElem.getKind (kind == `Lean.Parser.Term.doLetArrow || kind == `Lean.Parser.Term.doLet) && !doElem[1].isNone namespace ToCodeBlock structure Context where ref : Syntax m : Syntax -- Syntax representing the monad associated with the do notation. mutableVars : NameSet := {} insideFor : Bool := false abbrev M := ReaderT Context TermElabM @[inline] def withNewMutableVars {α} (newVars : Array Name) (mutable : Bool) (x : M α) : M α := withReader (fun ctx => if mutable then { ctx with mutableVars := insertVars ctx.mutableVars newVars } else ctx) x def checkReassignable (xs : Array Name) : M Unit := do let throwInvalidReassignment (x : Name) : M Unit := throwError "'{x.simpMacroScopes}' cannot be reassigned" let ctx ← read for x in xs do unless ctx.mutableVars.contains x do throwInvalidReassignment x @[inline] def withFor {α} (x : M α) : M α := withReader (fun ctx => { ctx with insideFor := true }) x structure ToForInTermResult where uvars : Array Name term : Syntax def mkForInBody (x : Syntax) (forInBody : CodeBlock) : M ToForInTermResult := do let ctx ← read let uvars := forInBody.uvars let uvars := nameSetToArray uvars let term ← liftMacroM $ ToTerm.run forInBody.code ctx.m uvars (if hasReturn forInBody.code then ToTerm.Kind.forInWithReturn else ToTerm.Kind.forIn) pure ⟨uvars, term⟩ def ensureInsideFor : M Unit := unless (← read).insideFor do throwError "invalid 'do' element, it must be inside 'for'" def ensureEOS (doElems : List Syntax) : M Unit := unless doElems.isEmpty do throwError "must be last element in a 'do' sequence" private partial def expandLiftMethodAux (inQuot : Bool) : Syntax → StateT (List Syntax) MacroM Syntax | stx@(Syntax.node k args) => if liftMethodDelimiter k then pure stx else if k == `Lean.Parser.Term.liftMethod && !inQuot then withFreshMacroScope do let term := args[1] let term ← expandLiftMethodAux inQuot term let auxDoElem ← `(doElem| let a ← $term:term) modify fun s => s ++ [auxDoElem] `(a) else do let inAntiquot := stx.isAntiquot && !stx.isEscapedAntiquot let args ← args.mapM (expandLiftMethodAux (inQuot && !inAntiquot || stx.isQuot)) pure $ Syntax.node k args | stx => pure stx def expandLiftMethod (doElem : Syntax) : MacroM (List Syntax × Syntax) := do if !hasLiftMethod doElem then pure ([], doElem) else let (doElem, doElemsNew) ← (expandLiftMethodAux false doElem).run [] pure (doElemsNew, doElem) def checkLetArrowRHS (doElem : Syntax) : M Unit := do let kind := doElem.getKind if kind == `Lean.Parser.Term.doLetArrow || kind == `Lean.Parser.Term.doLet || kind == `Lean.Parser.Term.doLetRec || kind == `Lean.Parser.Term.doHave || kind == `Lean.Parser.Term.doReassign || kind == `Lean.Parser.Term.doReassignArrow then throwErrorAt doElem "invalid kind of value '{kind}' in an assignment" /- Generate `CodeBlock` for `doReturn` which is of the form ``` "return " >> optional termParser ``` `doElems` is only used for sanity checking. -/ def doReturnToCode (doReturn : Syntax) (doElems: List Syntax) : M CodeBlock := withRef doReturn do ensureEOS doElems let argOpt := doReturn[1] let arg ← if argOpt.isNone then liftMacroM mkUnit else pure argOpt[0] return mkReturn (← getRef) arg structure Catch where x : Syntax optType : Syntax codeBlock : CodeBlock def getTryCatchUpdatedVars (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) : NameSet := let ws := tryCode.uvars let ws := catches.foldl (fun ws alt => union alt.codeBlock.uvars ws) ws let ws := match finallyCode? with | none => ws | some c => union c.uvars ws ws def tryCatchPred (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) (p : Code → Bool) : Bool := p tryCode.code || catches.any (fun «catch» => p «catch».codeBlock.code) || match finallyCode? with | none => false | some finallyCode => p finallyCode.code mutual /- "Concatenate" `c` with `doSeqToCode doElems` -/ partial def concatWith (c : CodeBlock) (doElems : List Syntax) : M CodeBlock := match doElems with | [] => pure c | nextDoElem :: _ => do let k ← doSeqToCode doElems let ref := nextDoElem concat c ref none k /- Generate `CodeBlock` for `doLetArrow; doElems` `doLetArrow` is of the form ``` "let " >> optional "mut " >> (doIdDecl <|> doPatDecl) ``` where ``` def doIdDecl := leading_parser ident >> optType >> leftArrow >> doElemParser def doPatDecl := leading_parser termParser >> leftArrow >> doElemParser >> optional (" | " >> doElemParser) ``` -/ partial def doLetArrowToCode (doLetArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do let ref := doLetArrow let decl := doLetArrow[2] if decl.getKind == `Lean.Parser.Term.doIdDecl then let y := decl[0].getId let doElem := decl[3] let k ← withNewMutableVars #[y] (isMutableLet doLetArrow) (doSeqToCode doElems) match isDoExpr? doElem with | some action => pure $ mkVarDeclCore #[y] doLetArrow k | none => checkLetArrowRHS doElem let c ← doSeqToCode [doElem] match doElems with | [] => pure c | kRef::_ => concat c kRef y k else if decl.getKind == `Lean.Parser.Term.doPatDecl then let pattern := decl[0] let doElem := decl[2] let optElse := decl[3] if optElse.isNone then withFreshMacroScope do let auxDo ← if isMutableLet doLetArrow then `(do let discr ← $doElem; let mut $pattern:term := discr) else `(do let discr ← $doElem; let $pattern:term := discr) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems else if isMutableLet doLetArrow then throwError "'mut' is currently not supported in let-decls with 'else' case" let contSeq := mkDoSeq doElems.toArray let elseSeq := mkSingletonDoSeq optElse[1] let auxDo ← `(do let discr ← $doElem; match discr with | $pattern:term => $contSeq | _ => $elseSeq) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) else throwError "unexpected kind of 'do' declaration" /- Generate `CodeBlock` for `doReassignArrow; doElems` `doReassignArrow` is of the form ``` (doIdDecl <|> doPatDecl) ``` -/ partial def doReassignArrowToCode (doReassignArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do let ref := doReassignArrow let decl := doReassignArrow[0] if decl.getKind == `Lean.Parser.Term.doIdDecl then let doElem := decl[3] let y := decl[0] let auxDo ← `(do let r ← $doElem; $y:ident := r) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems else if decl.getKind == `Lean.Parser.Term.doPatDecl then let pattern := decl[0] let doElem := decl[2] let optElse := decl[3] if optElse.isNone then withFreshMacroScope do let auxDo ← `(do let discr ← $doElem; $pattern:term := discr) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems else throwError "reassignment with `|` (i.e., \"else clause\") is not currently supported" else throwError "unexpected kind of 'do' reassignment" /- Generate `CodeBlock` for `doIf; doElems` `doIf` is of the form ``` "if " >> optIdent >> termParser >> " then " >> doSeq >> many (group (try (group (" else " >> " if ")) >> optIdent >> termParser >> " then " >> doSeq)) >> optional (" else " >> doSeq) ``` -/ partial def doIfToCode (doIf : Syntax) (doElems : List Syntax) : M CodeBlock := do let view ← liftMacroM $ mkDoIfView doIf let thenBranch ← doSeqToCode (getDoSeqElems view.thenBranch) let elseBranch ← doSeqToCode (getDoSeqElems view.elseBranch) let ite ← mkIte view.ref view.optIdent view.cond thenBranch elseBranch concatWith ite doElems /- Generate `CodeBlock` for `doUnless; doElems` `doUnless` is of the form ``` "unless " >> termParser >> "do " >> doSeq ``` -/ partial def doUnlessToCode (doUnless : Syntax) (doElems : List Syntax) : M CodeBlock := withRef doUnless do let ref := doUnless let cond := doUnless[1] let doSeq := doUnless[3] let body ← doSeqToCode (getDoSeqElems doSeq) let unlessCode ← liftMacroM <| mkUnless cond body concatWith unlessCode doElems /- Generate `CodeBlock` for `doFor; doElems` `doFor` is of the form ``` def doForDecl := leading_parser termParser >> " in " >> withForbidden "do" termParser def doFor := leading_parser "for " >> sepBy1 doForDecl ", " >> "do " >> doSeq ``` -/ partial def doForToCode (doFor : Syntax) (doElems : List Syntax) : M CodeBlock := do let doForDecls := doFor[1].getSepArgs if doForDecls.size > 1 then /- Expand ``` for x in xs, y in ys do body ``` into ``` let s := toStream ys for x in xs do match Stream.next? s with | none => break | some (y, s') => s := s' body ``` -/ -- Extract second element let doForDecl := doForDecls[1] let y := doForDecl[0] let ys := doForDecl[2] let doForDecls := doForDecls.eraseIdx 1 let body := doFor[3] withFreshMacroScope do let toStreamFn ← withRef ys `(toStream) let auxDo ← `(do let mut s := $toStreamFn:ident $ys for $doForDecls:doForDecl,* do match Stream.next? s with | none => break | some ($y, s') => s := s' do $body) doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems) else withRef doFor do let x := doForDecls[0][0] let xs := doForDecls[0][2] let forElems := getDoSeqElems doFor[3] let forInBodyCodeBlock ← withFor (doSeqToCode forElems) let ⟨uvars, forInBody⟩ ← mkForInBody x forInBodyCodeBlock let uvarsTuple ← liftMacroM do mkTuple (← uvars.mapM mkIdentFromRef) if hasReturn forInBodyCodeBlock.code then let forInBody ← liftMacroM <| destructTuple uvars (← `(r)) forInBody let forInTerm ← `(forIn% $(xs) (MProd.mk none $uvarsTuple) fun $x r => let r := r.2; $forInBody) let auxDo ← `(do let r ← $forInTerm:term; $uvarsTuple:term := r.2; match r.1 with | none => Pure.pure (ensureExpectedType% "type mismatch, 'for'" PUnit.unit) | some a => return ensureExpectedType% "type mismatch, 'for'" a) doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems) else let forInBody ← liftMacroM <| destructTuple uvars (← `(r)) forInBody let forInTerm ← `(forIn% $(xs) $uvarsTuple fun $x r => $forInBody) if doElems.isEmpty then let auxDo ← `(do let r ← $forInTerm:term; $uvarsTuple:term := r; Pure.pure (ensureExpectedType% "type mismatch, 'for'" PUnit.unit)) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) else let auxDo ← `(do let r ← $forInTerm:term; $uvarsTuple:term := r) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems /-- Generate `CodeBlock` for `doMatch; doElems` -/ partial def doMatchToCode (doMatch : Syntax) (doElems: List Syntax) : M CodeBlock := do let ref := doMatch let discrs := doMatch[1] let optType := doMatch[2] let matchAlts := doMatch[4][0].getArgs -- Array of `doMatchAlt` let alts ← matchAlts.mapM fun matchAlt => do let patterns := matchAlt[1] let vars ← getPatternsVarsEx patterns.getSepArgs let rhs := matchAlt[3] let rhs ← doSeqToCode (getDoSeqElems rhs) pure { ref := matchAlt, vars := vars, patterns := patterns, rhs := rhs : Alt CodeBlock } let matchCode ← mkMatch ref discrs optType alts concatWith matchCode doElems /-- Generate `CodeBlock` for `doTry; doElems` ``` def doTry := leading_parser "try " >> doSeq >> many (doCatch <|> doCatchMatch) >> optional doFinally def doCatch := leading_parser "catch " >> binderIdent >> optional (":" >> termParser) >> darrow >> doSeq def doCatchMatch := leading_parser "catch " >> doMatchAlts def doFinally := leading_parser "finally " >> doSeq ``` -/ partial def doTryToCode (doTry : Syntax) (doElems: List Syntax) : M CodeBlock := do let ref := doTry let tryCode ← doSeqToCode (getDoSeqElems doTry[1]) let optFinally := doTry[3] let catches ← doTry[2].getArgs.mapM fun catchStx => do if catchStx.getKind == `Lean.Parser.Term.doCatch then let x := catchStx[1] let optType := catchStx[2] let c ← doSeqToCode (getDoSeqElems catchStx[4]) pure { x := x, optType := optType, codeBlock := c : Catch } else if catchStx.getKind == `Lean.Parser.Term.doCatchMatch then let matchAlts := catchStx[1] let x ← `(ex) let auxDo ← `(do match ex with $matchAlts) let c ← doSeqToCode (getDoSeqElems (getDoSeq auxDo)) pure { x := x, codeBlock := c, optType := mkNullNode : Catch } else throwError "unexpected kind of 'catch'" let finallyCode? ← if optFinally.isNone then pure none else some <$> doSeqToCode (getDoSeqElems optFinally[0][1]) if catches.isEmpty && finallyCode?.isNone then throwError "invalid 'try', it must have a 'catch' or 'finally'" let ctx ← read let ws := getTryCatchUpdatedVars tryCode catches finallyCode? let uvars := nameSetToArray ws let a := tryCatchPred tryCode catches finallyCode? hasTerminalAction let r := tryCatchPred tryCode catches finallyCode? hasReturn let bc := tryCatchPred tryCode catches finallyCode? hasBreakContinue let toTerm (codeBlock : CodeBlock) : M Syntax := do let codeBlock ← liftM $ extendUpdatedVars codeBlock ws liftMacroM $ ToTerm.mkNestedTerm codeBlock.code ctx.m uvars a r bc let term ← toTerm tryCode let term ← catches.foldlM (fun term «catch» => do let catchTerm ← toTerm «catch».codeBlock if catch.optType.isNone then `(MonadExcept.tryCatch $term (fun $(«catch».x):ident => $catchTerm)) else let type := «catch».optType[1] `(tryCatchThe $type $term (fun $(«catch».x):ident => $catchTerm))) term let term ← match finallyCode? with | none => pure term | some finallyCode => withRef optFinally do unless finallyCode.uvars.isEmpty do throwError "'finally' currently does not support reassignments" if hasBreakContinueReturn finallyCode.code then throwError "'finally' currently does 'return', 'break', nor 'continue'" let finallyTerm ← liftMacroM <| ToTerm.run finallyCode.code ctx.m {} ToTerm.Kind.regular `(tryFinally $term $finallyTerm) let doElemsNew ← liftMacroM <| ToTerm.matchNestedTermResult term uvars a r bc doSeqToCode (doElemsNew ++ doElems) partial def doSeqToCode : List Syntax → M CodeBlock | [] => do liftMacroM mkPureUnitAction | doElem::doElems => withIncRecDepth <| withRef doElem do checkMaxHeartbeats "'do'-expander" match (← liftMacroM <| expandMacro? doElem) with | some doElem => doSeqToCode (doElem::doElems) | none => match (← liftMacroM <| expandDoIf? doElem) with | some doElem => doSeqToCode (doElem::doElems) | none => let (liftedDoElems, doElem) ← liftM (liftMacroM <| expandLiftMethod doElem : TermElabM _) if !liftedDoElems.isEmpty then doSeqToCode (liftedDoElems ++ [doElem] ++ doElems) else let ref := doElem let concatWithRest (c : CodeBlock) : M CodeBlock := concatWith c doElems let k := doElem.getKind if k == `Lean.Parser.Term.doLet then let vars ← getDoLetVars doElem mkVarDeclCore vars doElem <$> withNewMutableVars vars (isMutableLet doElem) (doSeqToCode doElems) else if k == `Lean.Parser.Term.doHave then let var := getDoHaveVar doElem mkVarDeclCore #[var] doElem <$> (doSeqToCode doElems) else if k == `Lean.Parser.Term.doLetRec then let vars ← getDoLetRecVars doElem mkVarDeclCore vars doElem <$> (doSeqToCode doElems) else if k == `Lean.Parser.Term.doReassign then let vars ← getDoReassignVars doElem checkReassignable vars let k ← doSeqToCode doElems mkReassignCore vars doElem k else if k == `Lean.Parser.Term.doLetArrow then doLetArrowToCode doElem doElems else if k == `Lean.Parser.Term.doReassignArrow then doReassignArrowToCode doElem doElems else if k == `Lean.Parser.Term.doIf then doIfToCode doElem doElems else if k == `Lean.Parser.Term.doUnless then doUnlessToCode doElem doElems else if k == `Lean.Parser.Term.doFor then withFreshMacroScope do doForToCode doElem doElems else if k == `Lean.Parser.Term.doMatch then doMatchToCode doElem doElems else if k == `Lean.Parser.Term.doTry then doTryToCode doElem doElems else if k == `Lean.Parser.Term.doBreak then ensureInsideFor ensureEOS doElems return mkBreak ref else if k == `Lean.Parser.Term.doContinue then ensureInsideFor ensureEOS doElems return mkContinue ref else if k == `Lean.Parser.Term.doReturn then doReturnToCode doElem doElems else if k == `Lean.Parser.Term.doDbgTrace then return mkSeq doElem (← doSeqToCode doElems) else if k == `Lean.Parser.Term.doAssert then return mkSeq doElem (← doSeqToCode doElems) else if k == `Lean.Parser.Term.doNested then let nestedDoSeq := doElem[1] doSeqToCode (getDoSeqElems nestedDoSeq ++ doElems) else if k == `Lean.Parser.Term.doExpr then let term := doElem[0] if doElems.isEmpty then return mkTerminalAction term else return mkSeq term (← doSeqToCode doElems) else throwError "unexpected do-element\n{doElem}" end def run (doStx : Syntax) (m : Syntax) : TermElabM CodeBlock := (doSeqToCode <| getDoSeqElems <| getDoSeq doStx).run { ref := doStx, m := m } end ToCodeBlock /- Create a synthetic metavariable `?m` and assign `m` to it. We use `?m` to refer to `m` when expanding the `do` notation. -/ private def mkMonadAlias (m : Expr) : TermElabM Syntax := do let result ← `(?m) let mType ← inferType m let mvar ← elabTerm result mType assignExprMVar mvar.mvarId! m pure result @[builtinTermElab «do»] def elabDo : TermElab := fun stx expectedType? => do tryPostponeIfNoneOrMVar expectedType? let bindInfo ← extractBind expectedType? let m ← mkMonadAlias bindInfo.m let codeBlock ← ToCodeBlock.run stx m let stxNew ← liftMacroM $ ToTerm.run codeBlock.code m trace[Elab.do] stxNew withMacroExpansion stx stxNew $ elabTermEnsuringType stxNew bindInfo.expectedType end Do builtin_initialize registerTraceClass `Elab.do private def toDoElem (newKind : SyntaxNodeKind) : Macro := fun stx => do let stx := stx.setKind newKind withRef stx `(do $stx:doElem) @[builtinMacro Lean.Parser.Term.termFor] def expandTermFor : Macro := toDoElem `Lean.Parser.Term.doFor @[builtinMacro Lean.Parser.Term.termTry] def expandTermTry : Macro := toDoElem `Lean.Parser.Term.doTry @[builtinMacro Lean.Parser.Term.termUnless] def expandTermUnless : Macro := toDoElem `Lean.Parser.Term.doUnless @[builtinMacro Lean.Parser.Term.termReturn] def expandTermReturn : Macro := toDoElem `Lean.Parser.Term.doReturn end Term end Elab end Lean
e6c64d680100ceb04c5facb45590c6539d8563b4
1b8f093752ba748c5ca0083afef2959aaa7dace5
/src/category_theory/limits/binary_products.lean
df7b279276c9c14c3ef3e58c58d9f6cfe9d997a8
[]
no_license
khoek/lean-category-theory
7ec4cda9cc64a5a4ffeb84712ac7d020dbbba386
63dcb598e9270a3e8b56d1769eb4f825a177cd95
refs/heads/master
1,585,251,725,759
1,539,344,445,000
1,539,344,445,000
145,281,070
0
0
null
1,534,662,376,000
1,534,662,376,000
null
UTF-8
Lean
false
false
11,715
lean
-- Copyright (c) 2018 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison, Reid Barton, Mario Carneiro import category_theory.limits.shape open category_theory namespace category_theory.limits universes u v w variables {C : Type u} [𝒞 : category.{u v} C] include 𝒞 section binary_product structure is_binary_product {Y Z : C} (t : span Y Z) := (lift : ∀ (s : span Y Z), s.X ⟶ t.X) (fac₁' : ∀ (s : span Y Z), (lift s) ≫ t.π₁ = s.π₁ . obviously) (fac₂' : ∀ (s : span Y Z), (lift s) ≫ t.π₂ = s.π₂ . obviously) (uniq' : ∀ (s : span Y Z) (m : s.X ⟶ t.X) (w₁ : m ≫ t.π₁ = s.π₁) (w₂ : m ≫ t.π₂ = s.π₂), m = lift s . obviously) restate_axiom is_binary_product.fac₁' attribute [simp,search] is_binary_product.fac₁ restate_axiom is_binary_product.fac₂' attribute [simp,search] is_binary_product.fac₂ restate_axiom is_binary_product.uniq' attribute [search,back'] is_binary_product.uniq @[extensionality] lemma is_binary_product.ext {Y Z : C} {t : span Y Z} (P Q : is_binary_product t) : P = Q := begin tactic.unfreeze_local_instances, cases P, cases Q, congr, obviously end instance subsingleton_is_binary_product {Y Z : C} {t : span Y Z} : subsingleton (is_binary_product t) := by obviously lemma is_binary_product.uniq'' {Y Z : C} {t : span Y Z} (h : is_binary_product t) {X' : C} (m : X' ⟶ t.X) : m = h.lift { X := X', π₁ := m ≫ t.π₁, π₂ := m ≫ t.π₂ } := h.uniq { X := X', π₁ := m ≫ t.π₁, π₂ := m ≫ t.π₂ } m (by obviously) (by obviously) -- TODO provide alternative constructor using uniq'' instead of uniq? lemma is_binary_product.univ {Y Z : C} {t : span Y Z} (h : is_binary_product t) (s : span Y Z) (φ : s.X ⟶ t.X) : (φ ≫ t.π₁ = s.π₁ ∧ φ ≫ t.π₂ = s.π₂) ↔ (φ = h.lift s) := begin obviously end def is_binary_product.of_lift_univ {Y Z : C} {t : span Y Z} (lift : Π (s : span Y Z), s.X ⟶ t.X) (univ : Π (s : span Y Z) (φ : s.X ⟶ t.X), (φ ≫ t.π₁ = s.π₁ ∧ φ ≫ t.π₂ = s.π₂) ↔ (φ = lift s)) : is_binary_product t := { lift := lift, fac₁' := λ s, ((univ s (lift s)).mpr (eq.refl (lift s))).left, -- PROJECT automation fac₂' := λ s, ((univ s (lift s)).mpr (eq.refl (lift s))).right, uniq' := begin obviously, apply univ_s_m.mp, obviously, end } -- TODO should be easy to automate end binary_product section binary_coproduct structure is_binary_coproduct {Y Z : C} (t : cospan Y Z) := (desc : ∀ (s : cospan Y Z), t.X ⟶ s.X) (fac₁' : ∀ (s : cospan Y Z), t.ι₁ ≫ (desc s) = s.ι₁ . obviously) (fac₂' : ∀ (s : cospan Y Z), t.ι₂ ≫ (desc s) = s.ι₂ . obviously) (uniq' : ∀ (s : cospan Y Z) (m : t.X ⟶ s.X) (w₁ : t.ι₁ ≫ m = s.ι₁) (w₂ : t.ι₂ ≫ m = s.ι₂), m = desc s . obviously) restate_axiom is_binary_coproduct.fac₁' attribute [simp,search] is_binary_coproduct.fac₁ restate_axiom is_binary_coproduct.fac₂' attribute [simp,search] is_binary_coproduct.fac₂ restate_axiom is_binary_coproduct.uniq' attribute [search, back'] is_binary_coproduct.uniq @[extensionality] lemma is_binary_coproduct.ext {Y Z : C} {t : cospan Y Z} (P Q : is_binary_coproduct t) : P = Q := begin tactic.unfreeze_local_instances, cases P, cases Q, congr, obviously end instance subsingleton_is_binary_coproduct {Y Z : C} {t : cospan Y Z} : subsingleton (is_binary_coproduct t) := by obviously lemma is_binary_coproduct.uniq'' {Y Z : C} {t : cospan Y Z} (h : is_binary_coproduct t) {X' : C} (m : t.X ⟶ X') : m = h.desc { X := X', ι₁ := t.ι₁ ≫ m, ι₂ := t.ι₂ ≫ m } := h.uniq { X := X', ι₁ := t.ι₁ ≫ m, ι₂ := t.ι₂ ≫ m } m (by obviously) (by obviously) -- TODO provide alternative constructor using uniq'' instead of uniq. lemma is_binary_coproduct.univ {Y Z : C} {t : cospan Y Z} (h : is_binary_coproduct t) (s : cospan Y Z) (φ : t.X ⟶ s.X) : (t.ι₁ ≫ φ = s.ι₁ ∧ t.ι₂ ≫ φ = s.ι₂) ↔ (φ = h.desc s) := begin obviously end def is_binary_coproduct.of_desc_univ {Y Z : C} {t : cospan Y Z} (desc : Π (s : cospan Y Z), t.X ⟶ s.X) (univ : Π (s : cospan Y Z) (φ : t.X ⟶ s.X), (t.ι₁ ≫ φ = s.ι₁ ∧ t.ι₂ ≫ φ = s.ι₂) ↔ (φ = desc s)) : is_binary_coproduct t := { desc := desc, fac₁' := λ s, ((univ s (desc s)).mpr (eq.refl (desc s))).left, -- PROJECT automation fac₂' := λ s, ((univ s (desc s)).mpr (eq.refl (desc s))).right, uniq' := begin obviously, apply univ_s_m.mp, obviously, end } -- TODO should be easy to automate end binary_coproduct variable (C) class has_binary_products := (prod : Π (Y Z : C), span Y Z) (is_binary_product : Π (Y Z : C), is_binary_product (prod Y Z) . obviously) class has_binary_coproducts := (coprod : Π (Y Z : C), cospan Y Z) (is_binary_coproduct : Π (Y Z : C), is_binary_coproduct (coprod Y Z) . obviously) variable {C} section variables [has_binary_products.{u v} C] def prod.span (Y Z : C) := has_binary_products.prod.{u v} Y Z def prod (Y Z : C) : C := (prod.span Y Z).X def prod.π₁ (Y Z : C) : prod Y Z ⟶ Y := (prod.span Y Z).π₁ def prod.π₂ (Y Z : C) : prod Y Z ⟶ Z := (prod.span Y Z).π₂ def prod.universal_property (Y Z : C) : is_binary_product (prod.span Y Z) := has_binary_products.is_binary_product.{u v} C Y Z def prod.lift {P Q R : C} (f : P ⟶ Q) (g : P ⟶ R) : P ⟶ (prod Q R) := (prod.universal_property Q R).lift ⟨ ⟨ P ⟩, f, g ⟩ @[simp,search] lemma prod.lift_π₁ {P Q R : C} (f : P ⟶ Q) (g : P ⟶ R) : prod.lift f g ≫ prod.π₁ Q R = f := is_binary_product.fac₁ _ { X := P, π₁ := f, π₂ := g } @[simp,search] lemma prod.lift_π₂ {P Q R : C} (f : P ⟶ Q) (g : P ⟶ R) : prod.lift f g ≫ prod.π₂ Q R = g := is_binary_product.fac₂ _ { X := P, π₁ := f, π₂ := g } def prod.map {P Q R S : C} (f : P ⟶ Q) (g : R ⟶ S) : (prod P R) ⟶ (prod Q S) := prod.lift (prod.π₁ P R ≫ f) (prod.π₂ P R ≫ g) @[simp,search] lemma prod.map_π₁ {P Q R S : C} (f : P ⟶ Q) (g : R ⟶ S) : prod.map f g ≫ prod.π₁ Q S = prod.π₁ P R ≫ f := by erw is_binary_product.fac₁ @[simp,search] lemma prod.map_π₂ {P Q R S : C} (f : P ⟶ Q) (g : R ⟶ S) : prod.map f g ≫ prod.π₂ Q S = prod.π₂ P R ≫ g := by erw is_binary_product.fac₂ def prod.swap (P Q : C) : prod P Q ⟶ prod Q P := prod.lift (prod.π₂ P Q) (prod.π₁ P Q) @[simp,search] lemma prod.swap_π₁ (P Q : C) : prod.swap P Q ≫ prod.π₁ Q P = prod.π₂ P Q := by erw is_binary_product.fac₁ @[simp,search] lemma prod.swap_π₂ (P Q : C) : prod.swap P Q ≫ prod.π₂ Q P = prod.π₁ P Q := by erw is_binary_product.fac₂ section variables {D : Type u} [𝒟 : category.{u v} D] [has_binary_products.{u v} D] include 𝒟 def prod.post (P Q : C) (G : C ⥤ D) : G (prod P Q) ⟶ (prod (G P) (G Q)) := @is_binary_product.lift _ _ _ _ (prod.span (G P) (G Q)) (prod.universal_property _ _) { X := _, π₁ := G.map (prod.π₁ P Q), π₂ := G.map (prod.π₂ P Q) } @[simp] def prod.post_π₁ (P Q : C) (G : C ⥤ D) : prod.post P Q G ≫ prod.π₁ _ _ = G.map (prod.π₁ P Q) := by erw is_binary_product.fac₁ @[simp] def prod.post_π₂ (P Q : C) (G : C ⥤ D) : prod.post P Q G ≫ prod.π₂ _ _ = G.map (prod.π₂ P Q) := by erw is_binary_product.fac₂ end @[extensionality] def prod.hom_ext (Y Z : C) (X : C) (f g : X ⟶ prod Y Z) (w₁ : f ≫ prod.π₁ Y Z = g ≫ prod.π₁ Y Z) (w₂ : f ≫ prod.π₂ Y Z = g ≫ prod.π₂ Y Z) : f = g := begin rw (prod.universal_property Y Z).uniq'' f, rw (prod.universal_property Y Z).uniq'' g, congr ; assumption, end @[simp,search] lemma prod.swap_swap (P Q : C) : prod.swap P Q ≫ prod.swap Q P = 𝟙 _ := by obviously @[simp,search] lemma prod.swap_lift {P Q R : C} (f : P ⟶ Q) (g : P ⟶ R) : prod.lift g f ≫ prod.swap R Q = prod.lift f g := by obviously @[search] lemma prod.swap_map {P Q R S : C} (f : P ⟶ Q) (g : R ⟶ S) : prod.swap P R ≫ prod.map g f = prod.map f g ≫ prod.swap Q S := by obviously @[simp,search] lemma prod.lift_map {P Q R S T : C} (f : P ⟶ Q) (g : P ⟶ R) (h : Q ⟶ T) (k : R ⟶ S) : prod.lift f g ≫ prod.map h k = prod.lift (f ≫ h) (g ≫ k) := by obviously @[simp,search] lemma prod.map_map {P Q R S T U : C} (f : P ⟶ Q) (g : R ⟶ S) (h : Q ⟶ T) (k : S ⟶ U) : prod.map f g ≫ prod.map h k = prod.map (f ≫ h) (g ≫ k) := by obviously -- TODO add lemmas lift_post, map_post, swap_post, post_post when needed -- TODO also to coprod end section variables [has_binary_coproducts.{u v} C] def coprod.cospan (Y Z : C) := has_binary_coproducts.coprod.{u v} Y Z def coprod (Y Z : C) : C := (coprod.cospan Y Z).X def coprod.ι₁ (Y Z : C) : Y ⟶ coprod Y Z := (coprod.cospan Y Z).ι₁ def coprod.ι₂ (Y Z : C) : Z ⟶ coprod Y Z := (coprod.cospan Y Z).ι₂ def coprod.universal_property (Y Z : C) : is_binary_coproduct (coprod.cospan Y Z) := has_binary_coproducts.is_binary_coproduct.{u v} C Y Z def coprod.desc {P Q R : C} (f : Q ⟶ P) (g : R ⟶ P) : (coprod Q R) ⟶ P := (coprod.universal_property Q R).desc ⟨ ⟨ P ⟩, f, g ⟩ def coprod.map {P Q R S : C} (f : P ⟶ Q) (g : R ⟶ S) : (coprod P R) ⟶ (coprod Q S) := coprod.desc (f ≫ coprod.ι₁ Q S) (g ≫ coprod.ι₂ Q S) def coprod.swap (P Q : C) : coprod P Q ⟶ coprod Q P := coprod.desc (coprod.ι₂ Q P) (coprod.ι₁ Q P) @[simp,search] lemma coprod.desc_ι₁ {P Q R : C} (f : Q ⟶ P) (g : R ⟶ P) : coprod.ι₁ Q R ≫ coprod.desc f g = f := is_binary_coproduct.fac₁ _ { X := P, ι₁ := f, ι₂ := g } @[simp,search] lemma coprod.desc_ι₂ {P Q R : C} (f : Q ⟶ P) (g : R ⟶ P) : coprod.ι₂ Q R ≫ coprod.desc f g = g := is_binary_coproduct.fac₂ _ { X := P, ι₁ := f, ι₂ := g } @[simp,search] lemma coprod.swap_ι₁ (P Q : C) : coprod.ι₁ P Q ≫ coprod.swap P Q = coprod.ι₂ Q P := by erw is_binary_coproduct.fac₁ @[simp,search] lemma coprod.swap_ι₂ (P Q : C) : coprod.ι₂ P Q ≫ coprod.swap P Q = coprod.ι₁ Q P := by erw is_binary_coproduct.fac₂ @[simp,search] lemma coprod.map_ι₁ {P Q R S : C} (f : P ⟶ Q) (g : R ⟶ S) : coprod.ι₁ P R ≫ coprod.map f g = f ≫ coprod.ι₁ Q S := by erw is_binary_coproduct.fac₁ @[simp,search] lemma coprod.map_ι₂ {P Q R S : C} (f : P ⟶ Q) (g : R ⟶ S) : coprod.ι₂ P R ≫ coprod.map f g = g ≫ coprod.ι₂ Q S := by erw is_binary_coproduct.fac₂ @[extensionality] def coprod.hom_ext (Y Z : C) (X : C) (f g : coprod Y Z ⟶ X) (w₁ : coprod.ι₁ Y Z ≫ f = coprod.ι₁ Y Z ≫ g) (w₂ : coprod.ι₂ Y Z ≫ f = coprod.ι₂ Y Z ≫ g) : f = g := begin rw (coprod.universal_property Y Z).uniq'' f, rw (coprod.universal_property Y Z).uniq'' g, congr ; assumption, end @[simp,search] lemma coprod.swap_swap (P Q : C) : coprod.swap P Q ≫ coprod.swap Q P = 𝟙 _ := by obviously @[simp,search] lemma coprod.swap_desc {P Q R : C} (f : Q ⟶ P) (g : R ⟶ P) : coprod.swap Q R ≫ coprod.desc g f = coprod.desc f g := by obviously @[search] lemma coprod.swap_map {P Q R S : C} (f : P ⟶ Q) (g : R ⟶ S) : coprod.swap P R ≫ coprod.map g f = coprod.map f g ≫ coprod.swap Q S := by obviously @[simp,search] lemma coprod.map_desc {P Q R S T : C} (f : P ⟶ Q) (g : R ⟶ S) (h : Q ⟶ T) (k : S ⟶ T) : coprod.map f g ≫ coprod.desc h k = coprod.desc (f ≫ h) (g ≫ k) := by obviously @[simp,search] lemma coprod.map_map {P Q R S T U : C} (f : P ⟶ Q) (g : R ⟶ S) (h : Q ⟶ T) (k : S ⟶ U) : coprod.map f g ≫ coprod.map h k = coprod.map (f ≫ h) (g ≫ k) := by obviously end end category_theory.limits
7ed1fca2f45db5cd03070930ec1f748430139f24
d436468d80b739ba7e06843c4d0d2070e43448e5
/src/analysis/complex/exponential.lean
8ce865ca585ce3163f1dcf6ef873837e1f0b6818
[ "Apache-2.0" ]
permissive
roro47/mathlib
761fdc002aef92f77818f3fef06bf6ec6fc1a28e
80aa7d52537571a2ca62a3fdf71c9533a09422cf
refs/heads/master
1,599,656,410,625
1,573,649,488,000
1,573,649,488,000
221,452,951
0
0
Apache-2.0
1,573,647,693,000
1,573,647,692,000
null
UTF-8
Lean
false
false
74,206
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne -/ import topology.instances.complex tactic.linarith data.complex.exponential group_theory.quotient_group topology.metric_space.basic /-! # Exponential ## Main definitions This file contains the following definitions: • π, arcsin, arccos, arctan • argument of a complex number • logarithm on real and complex numbers • complex and real power function ## Main statements The following functions are shown to be continuous: • complex and real exponential function • sin, cos, tan, sinh, cosh • logarithm on real numbers • real power function • square root function ## Tags exp, log, sin, cos, tan, arcsin, arccos, arctan, angle, argument, power, square root, -/ open finset filter metric open_locale topological_space namespace complex lemma tendsto_exp_zero_one : tendsto exp (𝓝 0) (𝓝 1) := tendsto_nhds_nhds.2 $ λ ε ε0, ⟨min (ε / 2) 1, lt_min (div_pos ε0 (by norm_num)) (by norm_num), λ x h, have h : abs x < min (ε / 2) 1, by simpa [dist_eq] using h, calc abs (exp x - 1) ≤ 2 * abs x : abs_exp_sub_one_le (le_trans (le_of_lt h) (min_le_right _ _)) ... = abs x + abs x : two_mul (abs x) ... < ε / 2 + ε / 2 : add_lt_add (lt_of_lt_of_le h (min_le_left _ _)) (lt_of_lt_of_le h (min_le_left _ _)) ... = ε : by rw add_halves⟩ lemma continuous_exp : continuous exp := continuous_iff_continuous_at.2 (λ x, have H1 : tendsto (λ h, exp (x + h)) (𝓝 0) (𝓝 (exp x)), by simpa [exp_add] using tendsto_mul tendsto_const_nhds tendsto_exp_zero_one, have H2 : tendsto (λ y, y - x) (𝓝 x) (𝓝 (x - x)) := tendsto_sub tendsto_id (@tendsto_const_nhds _ _ _ x _), suffices tendsto ((λ h, exp (x + h)) ∘ (λ y, id y - (λ z, x) y)) (𝓝 x) (𝓝 (exp x)), by simp only [function.comp, add_sub_cancel'_right, id.def] at this; exact this, tendsto.comp H1 (by rw [sub_self] at H2; exact H2)) lemma continuous_sin : continuous sin := continuous_mul (continuous_mul (continuous_sub (continuous_exp.comp (continuous_mul continuous_neg' continuous_const)) (continuous_exp.comp (continuous_mul continuous_id continuous_const))) continuous_const) continuous_const lemma continuous_cos : continuous cos := continuous_mul (continuous_add (continuous_exp.comp (continuous_mul continuous_id continuous_const)) (continuous_exp.comp (continuous_mul continuous_neg' continuous_const))) continuous_const lemma continuous_tan : continuous (λ x : {x // cos x ≠ 0}, tan x) := continuous_mul (continuous_sin.comp continuous_subtype_val) (continuous_inv subtype.property (continuous_cos.comp continuous_subtype_val)) lemma continuous_sinh : continuous sinh := continuous_mul (continuous_sub continuous_exp (continuous_exp.comp continuous_neg')) continuous_const lemma continuous_cosh : continuous cosh := continuous_mul (continuous_add continuous_exp (continuous_exp.comp continuous_neg')) continuous_const end complex namespace real variables {x y z : ℝ} lemma continuous_exp : continuous exp := complex.continuous_re.comp (complex.continuous_exp.comp complex.continuous_of_real) lemma continuous_sin : continuous sin := complex.continuous_re.comp (complex.continuous_sin.comp complex.continuous_of_real) lemma continuous_cos : continuous cos := complex.continuous_re.comp (complex.continuous_cos.comp complex.continuous_of_real) lemma continuous_tan : continuous (λ x : {x // cos x ≠ 0}, tan x) := by simp only [tan_eq_sin_div_cos]; exact continuous_mul (continuous_sin.comp continuous_subtype_val) (continuous_inv subtype.property (continuous_cos.comp continuous_subtype_val)) lemma continuous_sinh : continuous sinh := complex.continuous_re.comp (complex.continuous_sinh.comp complex.continuous_of_real) lemma continuous_cosh : continuous cosh := complex.continuous_re.comp (complex.continuous_cosh.comp complex.continuous_of_real) private lemma exists_exp_eq_of_one_le {x : ℝ} (hx : 1 ≤ x) : ∃ y, exp y = x := let ⟨y, hy⟩ := @intermediate_value real.exp 0 (x - 1) x (λ _ _ _, continuous_iff_continuous_at.1 continuous_exp _) (by simpa) (by simpa using add_one_le_exp_of_nonneg (sub_nonneg.2 hx)) (sub_nonneg.2 hx) in ⟨y, hy.2.2⟩ lemma exists_exp_eq_of_pos {x : ℝ} (hx : 0 < x) : ∃ y, exp y = x := match le_total x 1 with | (or.inl hx1) := let ⟨y, hy⟩ := exists_exp_eq_of_one_le (one_le_inv hx hx1) in ⟨-y, by rw [exp_neg, hy, inv_inv']⟩ | (or.inr hx1) := exists_exp_eq_of_one_le hx1 end noncomputable def log (x : ℝ) : ℝ := if hx : 0 < x then classical.some (exists_exp_eq_of_pos hx) else 0 lemma exp_log {x : ℝ} (hx : 0 < x) : exp (log x) = x := by rw [log, dif_pos hx]; exact classical.some_spec (exists_exp_eq_of_pos hx) @[simp] lemma log_exp (x : ℝ) : log (exp x) = x := exp_injective $ exp_log (exp_pos x) @[simp] lemma log_zero : log 0 = 0 := by simp [log, lt_irrefl] @[simp] lemma log_one : log 1 = 0 := exp_injective $ by rw [exp_log zero_lt_one, exp_zero] lemma log_mul {x y : ℝ} (hx : 0 < x) (hy : 0 < y) : log (x * y) = log x + log y := exp_injective $ by rw [exp_log (mul_pos hx hy), exp_add, exp_log hx, exp_log hy] lemma log_le_log {x y : ℝ} (h : 0 < x) (h₁ : 0 < y) : real.log x ≤ real.log y ↔ x ≤ y := ⟨λ h₂, by rwa [←real.exp_le_exp, real.exp_log h, real.exp_log h₁] at h₂, λ h₂, (real.exp_le_exp).1 $ by rwa [real.exp_log h₁, real.exp_log h]⟩ lemma log_lt_log (hx : 0 < x) : x < y → log x < log y := by { intro h, rwa [← exp_lt_exp, exp_log hx, exp_log (lt_trans hx h)] } lemma log_lt_log_iff (hx : 0 < x) (hy : 0 < y) : log x < log y ↔ x < y := by { rw [← exp_lt_exp, exp_log hx, exp_log hy] } lemma log_pos_iff (x : ℝ) : 0 < log x ↔ 1 < x := begin by_cases h : 0 < x, { rw ← log_one, exact log_lt_log_iff (by norm_num) h }, { rw [log, dif_neg], split, repeat {intro, linarith} } end lemma log_pos : 1 < x → 0 < log x := (log_pos_iff x).2 lemma log_neg_iff (h : 0 < x) : log x < 0 ↔ x < 1 := by { rw ← log_one, exact log_lt_log_iff h (by norm_num) } lemma log_neg (h0 : 0 < x) (h1 : x < 1) : log x < 0 := (log_neg_iff h0).2 h1 lemma log_nonneg : 1 ≤ x → 0 ≤ log x := by { intro, rwa [← log_one, log_le_log], norm_num, linarith } lemma log_nonpos : x ≤ 1 → log x ≤ 0 := begin intro, by_cases hx : 0 < x, { rwa [← log_one, log_le_log], exact hx, norm_num }, { simp [log, dif_neg hx] } end section prove_log_is_continuous lemma tendsto_log_one_zero : tendsto log (𝓝 1) (𝓝 0) := begin rw tendsto_nhds_nhds, assume ε ε0, let δ := min (exp ε - 1) (1 - exp (-ε)), have : 0 < δ, refine lt_min (sub_pos_of_lt (by rwa one_lt_exp_iff)) (sub_pos_of_lt _), by { rw exp_lt_one_iff, linarith }, use [δ, this], assume x h, cases le_total 1 x with hx hx, { have h : x < exp ε, rw [dist_eq, abs_of_nonneg (sub_nonneg_of_le hx)] at h, linarith [(min_le_left _ _ : δ ≤ exp ε - 1)], calc abs (log x - 0) = abs (log x) : by simp ... = log x : abs_of_nonneg $ log_nonneg hx ... < ε : by { rwa [← exp_lt_exp, exp_log], linarith }}, { have h : exp (-ε) < x, rw [dist_eq, abs_of_nonpos (sub_nonpos_of_le hx)] at h, linarith [(min_le_right _ _ : δ ≤ 1 - exp (-ε))], have : 0 < x := lt_trans (exp_pos _) h, calc abs (log x - 0) = abs (log x) : by simp ... = -log x : abs_of_nonpos $ log_nonpos hx ... < ε : by { rw [neg_lt, ← exp_lt_exp, exp_log], assumption' } } end lemma continuous_log' : continuous (λx : {x:ℝ // 0 < x}, log x.val) := continuous_iff_continuous_at.2 $ λ x, begin rw continuous_at, let f₁ := λ h:{h:ℝ // 0 < h}, log (x.1 * h.1), let f₂ := λ y:{y:ℝ // 0 < y}, subtype.mk (x.1 ⁻¹ * y.1) (mul_pos (inv_pos x.2) y.2), have H1 : tendsto f₁ (𝓝 ⟨1, zero_lt_one⟩) (𝓝 (log (x.1*1))), have : f₁ = λ h:{h:ℝ // 0 < h}, log x.1 + log h.1, ext h, rw ← log_mul x.2 h.2, simp only [this, log_mul x.2 zero_lt_one, log_one], exact tendsto_add tendsto_const_nhds (tendsto.comp tendsto_log_one_zero continuous_at_subtype_val), have H2 : tendsto f₂ (𝓝 x) (𝓝 ⟨x.1⁻¹ * x.1, mul_pos (inv_pos x.2) x.2⟩), rw tendsto_subtype_rng, exact tendsto_mul tendsto_const_nhds continuous_at_subtype_val, suffices h : tendsto (f₁ ∘ f₂) (𝓝 x) (𝓝 (log x.1)), begin convert h, ext y, have : x.val * (x.val⁻¹ * y.val) = y.val, rw [← mul_assoc, mul_inv_cancel (ne_of_gt x.2), one_mul], show log (y.val) = log (x.val * (x.val⁻¹ * y.val)), rw this end, exact tendsto.comp (by rwa mul_one at H1) (by { simp only [inv_mul_cancel (ne_of_gt x.2)] at H2, assumption }) end lemma continuous_at_log (hx : 0 < x) : continuous_at log x := continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_log' _ hx) (mem_nhds_sets (is_open_lt' _) hx) /-- Three forms of the continuity of `real.log` is provided. For the other two forms, see `real.continuous_log'` and `real.continuous_at_log` -/ lemma continuous_log {α : Type*} [topological_space α] {f : α → ℝ} (h : ∀a, 0 < f a) (hf : continuous f) : continuous (λa, log (f a)) := show continuous ((log ∘ @subtype.val ℝ (λr, 0 < r)) ∘ λa, ⟨f a, h a⟩), from continuous_log'.comp (continuous_subtype_mk _ hf) end prove_log_is_continuous lemma exists_cos_eq_zero : ∃ x, 1 ≤ x ∧ x ≤ 2 ∧ cos x = 0 := real.intermediate_value' (λ x _ _, continuous_iff_continuous_at.1 continuous_cos _) (le_of_lt cos_one_pos) (le_of_lt cos_two_neg) (by norm_num) noncomputable def pi : ℝ := 2 * classical.some exists_cos_eq_zero localized "notation `π` := real.pi" in real @[simp] lemma cos_pi_div_two : cos (π / 2) = 0 := by rw [pi, mul_div_cancel_left _ (@two_ne_zero' ℝ _ _ _)]; exact (classical.some_spec exists_cos_eq_zero).2.2 lemma one_le_pi_div_two : (1 : ℝ) ≤ π / 2 := by rw [pi, mul_div_cancel_left _ (@two_ne_zero' ℝ _ _ _)]; exact (classical.some_spec exists_cos_eq_zero).1 lemma pi_div_two_le_two : π / 2 ≤ 2 := by rw [pi, mul_div_cancel_left _ (@two_ne_zero' ℝ _ _ _)]; exact (classical.some_spec exists_cos_eq_zero).2.1 lemma two_le_pi : (2 : ℝ) ≤ π := (div_le_div_right (show (0 : ℝ) < 2, by norm_num)).1 (by rw div_self (@two_ne_zero' ℝ _ _ _); exact one_le_pi_div_two) lemma pi_le_four : π ≤ 4 := (div_le_div_right (show (0 : ℝ) < 2, by norm_num)).1 (calc π / 2 ≤ 2 : pi_div_two_le_two ... = 4 / 2 : by norm_num) lemma pi_pos : 0 < π := lt_of_lt_of_le (by norm_num) two_le_pi lemma pi_div_two_pos : 0 < π / 2 := half_pos pi_pos lemma two_pi_pos : 0 < 2 * π := by linarith [pi_pos] @[simp] lemma sin_pi : sin π = 0 := by rw [← mul_div_cancel_left pi (@two_ne_zero ℝ _), two_mul, add_div, sin_add, cos_pi_div_two]; simp @[simp] lemma cos_pi : cos π = -1 := by rw [← mul_div_cancel_left pi (@two_ne_zero ℝ _), mul_div_assoc, cos_two_mul, cos_pi_div_two]; simp [bit0, pow_add] @[simp] lemma sin_two_pi : sin (2 * π) = 0 := by simp [two_mul, sin_add] @[simp] lemma cos_two_pi : cos (2 * π) = 1 := by simp [two_mul, cos_add] lemma sin_add_pi (x : ℝ) : sin (x + π) = -sin x := by simp [sin_add] lemma sin_add_two_pi (x : ℝ) : sin (x + 2 * π) = sin x := by simp [sin_add_pi, sin_add, sin_two_pi, cos_two_pi] lemma cos_add_two_pi (x : ℝ) : cos (x + 2 * π) = cos x := by simp [cos_add, cos_two_pi, sin_two_pi] lemma sin_pi_sub (x : ℝ) : sin (π - x) = sin x := by simp [sin_add] lemma cos_add_pi (x : ℝ) : cos (x + π) = -cos x := by simp [cos_add] lemma cos_pi_sub (x : ℝ) : cos (π - x) = -cos x := by simp [cos_add] lemma sin_pos_of_pos_of_lt_pi {x : ℝ} (h0x : 0 < x) (hxp : x < π) : 0 < sin x := if hx2 : x ≤ 2 then sin_pos_of_pos_of_le_two h0x hx2 else have (2 : ℝ) + 2 = 4, from rfl, have π - x ≤ 2, from sub_le_iff_le_add.2 (le_trans pi_le_four (this ▸ add_le_add_left (le_of_not_ge hx2) _)), sin_pi_sub x ▸ sin_pos_of_pos_of_le_two (sub_pos.2 hxp) this lemma sin_nonneg_of_nonneg_of_le_pi {x : ℝ} (h0x : 0 ≤ x) (hxp : x ≤ π) : 0 ≤ sin x := match lt_or_eq_of_le h0x with | or.inl h0x := (lt_or_eq_of_le hxp).elim (le_of_lt ∘ sin_pos_of_pos_of_lt_pi h0x) (λ hpx, by simp [hpx]) | or.inr h0x := by simp [h0x.symm] end lemma sin_neg_of_neg_of_neg_pi_lt {x : ℝ} (hx0 : x < 0) (hpx : -π < x) : sin x < 0 := neg_pos.1 $ sin_neg x ▸ sin_pos_of_pos_of_lt_pi (neg_pos.2 hx0) (neg_lt.1 hpx) lemma sin_nonpos_of_nonnpos_of_neg_pi_le {x : ℝ} (hx0 : x ≤ 0) (hpx : -π ≤ x) : sin x ≤ 0 := neg_nonneg.1 $ sin_neg x ▸ sin_nonneg_of_nonneg_of_le_pi (neg_nonneg.2 hx0) (neg_le.1 hpx) @[simp] lemma sin_pi_div_two : sin (π / 2) = 1 := have sin (π / 2) = 1 ∨ sin (π / 2) = -1 := by simpa [pow_two, mul_self_eq_one_iff] using sin_sq_add_cos_sq (π / 2), this.resolve_right (λ h, (show ¬(0 : ℝ) < -1, by norm_num) $ h ▸ sin_pos_of_pos_of_lt_pi pi_div_two_pos (half_lt_self pi_pos)) lemma sin_add_pi_div_two (x : ℝ) : sin (x + π / 2) = cos x := by simp [sin_add] lemma sin_sub_pi_div_two (x : ℝ) : sin (x - π / 2) = -cos x := by simp [sin_add] lemma sin_pi_div_two_sub (x : ℝ) : sin (π / 2 - x) = cos x := by simp [sin_add] lemma cos_add_pi_div_two (x : ℝ) : cos (x + π / 2) = -sin x := by simp [cos_add] lemma cos_sub_pi_div_two (x : ℝ) : cos (x - π / 2) = sin x := by simp [cos_add] lemma cos_pi_div_two_sub (x : ℝ) : cos (π / 2 - x) = sin x := by rw [← cos_neg, neg_sub, cos_sub_pi_div_two] lemma cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two {x : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) : 0 < cos x := sin_add_pi_div_two x ▸ sin_pos_of_pos_of_lt_pi (by linarith) (by linarith) lemma cos_nonneg_of_neg_pi_div_two_le_of_le_pi_div_two {x : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) : 0 ≤ cos x := match lt_or_eq_of_le hx₁, lt_or_eq_of_le hx₂ with | or.inl hx₁, or.inl hx₂ := le_of_lt (cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two hx₁ hx₂) | or.inl hx₁, or.inr hx₂ := by simp [hx₂] | or.inr hx₁, _ := by simp [hx₁.symm] end lemma cos_neg_of_pi_div_two_lt_of_lt {x : ℝ} (hx₁ : π / 2 < x) (hx₂ : x < π + π / 2) : cos x < 0 := neg_pos.1 $ cos_pi_sub x ▸ cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (by linarith) (by linarith) lemma cos_nonpos_of_pi_div_two_le_of_le {x : ℝ} (hx₁ : π / 2 ≤ x) (hx₂ : x ≤ π + π / 2) : cos x ≤ 0 := neg_nonneg.1 $ cos_pi_sub x ▸ cos_nonneg_of_neg_pi_div_two_le_of_le_pi_div_two (by linarith) (by linarith) lemma sin_nat_mul_pi (n : ℕ) : sin (n * π) = 0 := by induction n; simp [add_mul, sin_add, *] lemma sin_int_mul_pi (n : ℤ) : sin (n * π) = 0 := by cases n; simp [add_mul, sin_add, *, sin_nat_mul_pi] lemma cos_nat_mul_two_pi (n : ℕ) : cos (n * (2 * π)) = 1 := by induction n; simp [*, mul_add, cos_add, add_mul, cos_two_pi, sin_two_pi] lemma cos_int_mul_two_pi (n : ℤ) : cos (n * (2 * π)) = 1 := by cases n; simp only [cos_nat_mul_two_pi, int.of_nat_eq_coe, int.neg_succ_of_nat_coe, int.cast_coe_nat, int.cast_neg, (neg_mul_eq_neg_mul _ _).symm, cos_neg] lemma cos_int_mul_two_pi_add_pi (n : ℤ) : cos (n * (2 * π) + π) = -1 := by simp [cos_add, sin_add, cos_int_mul_two_pi] lemma sin_eq_zero_iff_of_lt_of_lt {x : ℝ} (hx₁ : -π < x) (hx₂ : x < π) : sin x = 0 ↔ x = 0 := ⟨λ h, le_antisymm (le_of_not_gt (λ h0, lt_irrefl (0 : ℝ) $ calc 0 < sin x : sin_pos_of_pos_of_lt_pi h0 hx₂ ... = 0 : h)) (le_of_not_gt (λ h0, lt_irrefl (0 : ℝ) $ calc 0 = sin x : h.symm ... < 0 : sin_neg_of_neg_of_neg_pi_lt h0 hx₁)), λ h, by simp [h]⟩ lemma sin_eq_zero_iff {x : ℝ} : sin x = 0 ↔ ∃ n : ℤ, (n : ℝ) * π = x := ⟨λ h, ⟨⌊x / π⌋, le_antisymm (sub_nonneg.1 (sub_floor_div_mul_nonneg _ pi_pos)) (sub_nonpos.1 $ le_of_not_gt $ λ h₃, ne_of_lt (sin_pos_of_pos_of_lt_pi h₃ (sub_floor_div_mul_lt _ pi_pos)) (by simp [sin_add, h, sin_int_mul_pi]))⟩, λ ⟨n, hn⟩, hn ▸ sin_int_mul_pi _⟩ lemma sin_eq_zero_iff_cos_eq {x : ℝ} : sin x = 0 ↔ cos x = 1 ∨ cos x = -1 := by rw [← mul_self_eq_one_iff (cos x), ← sin_sq_add_cos_sq x, pow_two, pow_two, ← sub_eq_iff_eq_add, sub_self]; exact ⟨λ h, by rw [h, mul_zero], eq_zero_of_mul_self_eq_zero ∘ eq.symm⟩ theorem sin_sub_sin (θ ψ : ℝ) : sin θ - sin ψ = 2 * sin((θ - ψ)/2) * cos((θ + ψ)/2) := begin have s1 := sin_add ((θ + ψ) / 2) ((θ - ψ) / 2), have s2 := sin_sub ((θ + ψ) / 2) ((θ - ψ) / 2), rw [div_add_div_same, add_sub, add_right_comm, add_sub_cancel, add_self_div_two] at s1, rw [div_sub_div_same, ←sub_add, add_sub_cancel', add_self_div_two] at s2, rw [s1, s2, ←sub_add, add_sub_cancel', ← two_mul, ← mul_assoc, mul_right_comm] end lemma cos_eq_one_iff (x : ℝ) : cos x = 1 ↔ ∃ n : ℤ, (n : ℝ) * (2 * π) = x := ⟨λ h, let ⟨n, hn⟩ := sin_eq_zero_iff.1 (sin_eq_zero_iff_cos_eq.2 (or.inl h)) in ⟨n / 2, (int.mod_two_eq_zero_or_one n).elim (λ hn0, by rwa [← mul_assoc, ← @int.cast_two ℝ, ← int.cast_mul, int.div_mul_cancel ((int.dvd_iff_mod_eq_zero _ _).2 hn0)]) (λ hn1, by rw [← int.mod_add_div n 2, hn1, int.cast_add, int.cast_one, add_mul, one_mul, add_comm, mul_comm (2 : ℤ), int.cast_mul, mul_assoc, int.cast_two] at hn; rw [← hn, cos_int_mul_two_pi_add_pi] at h; exact absurd h (by norm_num))⟩, λ ⟨n, hn⟩, hn ▸ cos_int_mul_two_pi _⟩ theorem cos_eq_zero_iff {θ : ℝ} : cos θ = 0 ↔ ∃ k : ℤ, θ = (2 * k + 1) * pi / 2 := begin rw [←real.sin_pi_div_two_sub, sin_eq_zero_iff], split, { rintro ⟨n, hn⟩, existsi -n, rw [int.cast_neg, add_mul, add_div, mul_assoc, mul_div_cancel_left _ two_ne_zero, one_mul, ←neg_mul_eq_neg_mul, hn, neg_sub, sub_add_cancel] }, { rintro ⟨n, hn⟩, existsi -n, rw [hn, add_mul, one_mul, add_div, mul_assoc, mul_div_cancel_left _ two_ne_zero, sub_add_eq_sub_sub_swap, sub_self, zero_sub, neg_mul_eq_neg_mul, int.cast_neg] } end lemma cos_eq_one_iff_of_lt_of_lt {x : ℝ} (hx₁ : -(2 * π) < x) (hx₂ : x < 2 * π) : cos x = 1 ↔ x = 0 := ⟨λ h, let ⟨n, hn⟩ := (cos_eq_one_iff x).1 h in begin clear _let_match, subst hn, rw [mul_lt_iff_lt_one_left two_pi_pos, ← int.cast_one, int.cast_lt, ← int.le_sub_one_iff, sub_self] at hx₂, rw [neg_lt, neg_mul_eq_neg_mul, mul_lt_iff_lt_one_left two_pi_pos, neg_lt, ← int.cast_one, ← int.cast_neg, int.cast_lt, ← int.add_one_le_iff, neg_add_self] at hx₁, exact mul_eq_zero.2 (or.inl (int.cast_eq_zero.2 (le_antisymm hx₂ hx₁))), end, λ h, by simp [h]⟩ theorem cos_sub_cos (θ ψ : ℝ) : cos θ - cos ψ = -2 * sin((θ + ψ)/2) * sin((θ - ψ)/2) := by rw [← sin_pi_div_two_sub, ← sin_pi_div_two_sub, sin_sub_sin, sub_sub_sub_cancel_left, add_sub, sub_add_eq_add_sub, add_halves, sub_sub, sub_div π, cos_pi_div_two_sub, ← neg_sub, neg_div, sin_neg, ← neg_mul_eq_mul_neg, neg_mul_eq_neg_mul, mul_right_comm] lemma cos_lt_cos_of_nonneg_of_le_pi_div_two {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π / 2) (hy₁ : 0 ≤ y) (hy₂ : y ≤ π / 2) (hxy : x < y) : cos y < cos x := calc cos y = cos x * cos (y - x) - sin x * sin (y - x) : by rw [← cos_add, add_sub_cancel'_right] ... < (cos x * 1) - sin x * sin (y - x) : sub_lt_sub_right ((mul_lt_mul_left (cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (lt_of_lt_of_le (neg_neg_of_pos pi_div_two_pos) hx₁) (lt_of_lt_of_le hxy hy₂))).2 (lt_of_le_of_ne (cos_le_one _) (mt (cos_eq_one_iff_of_lt_of_lt (show -(2 * π) < y - x, by linarith) (show y - x < 2 * π, by linarith)).1 (sub_ne_zero.2 (ne_of_lt hxy).symm)))) _ ... ≤ _ : by rw mul_one; exact sub_le_self _ (mul_nonneg (sin_nonneg_of_nonneg_of_le_pi hx₁ (by linarith)) (sin_nonneg_of_nonneg_of_le_pi (by linarith) (by linarith))) lemma cos_lt_cos_of_nonneg_of_le_pi {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π) (hy₁ : 0 ≤ y) (hy₂ : y ≤ π) (hxy : x < y) : cos y < cos x := match (le_total x (π / 2) : x ≤ π / 2 ∨ π / 2 ≤ x), le_total y (π / 2) with | or.inl hx, or.inl hy := cos_lt_cos_of_nonneg_of_le_pi_div_two hx₁ hx hy₁ hy hxy | or.inl hx, or.inr hy := (lt_or_eq_of_le hx).elim (λ hx, calc cos y ≤ 0 : cos_nonpos_of_pi_div_two_le_of_le hy (by linarith [pi_pos]) ... < cos x : cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (by linarith) hx) (λ hx, calc cos y < 0 : cos_neg_of_pi_div_two_lt_of_lt (by linarith) (by linarith [pi_pos]) ... = cos x : by rw [hx, cos_pi_div_two]) | or.inr hx, or.inl hy := by linarith | or.inr hx, or.inr hy := neg_lt_neg_iff.1 (by rw [← cos_pi_sub, ← cos_pi_sub]; apply cos_lt_cos_of_nonneg_of_le_pi_div_two; linarith) end lemma cos_le_cos_of_nonneg_of_le_pi {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π) (hy₁ : 0 ≤ y) (hy₂ : y ≤ π) (hxy : x ≤ y) : cos y ≤ cos x := (lt_or_eq_of_le hxy).elim (le_of_lt ∘ cos_lt_cos_of_nonneg_of_le_pi hx₁ hx₂ hy₁ hy₂) (λ h, h ▸ le_refl _) lemma sin_lt_sin_of_le_of_le_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) (hy₁ : -(π / 2) ≤ y) (hy₂ : y ≤ π / 2) (hxy : x < y) : sin x < sin y := by rw [← cos_sub_pi_div_two, ← cos_sub_pi_div_two, ← cos_neg (x - _), ← cos_neg (y - _)]; apply cos_lt_cos_of_nonneg_of_le_pi; linarith lemma sin_le_sin_of_le_of_le_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) (hy₁ : -(π / 2) ≤ y) (hy₂ : y ≤ π / 2) (hxy : x ≤ y) : sin x ≤ sin y := (lt_or_eq_of_le hxy).elim (le_of_lt ∘ sin_lt_sin_of_le_of_le_pi_div_two hx₁ hx₂ hy₁ hy₂) (λ h, h ▸ le_refl _) lemma sin_inj_of_le_of_le_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) (hy₁ : -(π / 2) ≤ y) (hy₂ : y ≤ π / 2) (hxy : sin x = sin y) : x = y := match lt_trichotomy x y with | or.inl h := absurd (sin_lt_sin_of_le_of_le_pi_div_two hx₁ hx₂ hy₁ hy₂ h) (by rw hxy; exact lt_irrefl _) | or.inr (or.inl h) := h | or.inr (or.inr h) := absurd (sin_lt_sin_of_le_of_le_pi_div_two hy₁ hy₂ hx₁ hx₂ h) (by rw hxy; exact lt_irrefl _) end lemma cos_inj_of_nonneg_of_le_pi {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π) (hy₁ : 0 ≤ y) (hy₂ : y ≤ π) (hxy : cos x = cos y) : x = y := begin rw [← sin_pi_div_two_sub, ← sin_pi_div_two_sub] at hxy, refine (sub_left_inj).1 (sin_inj_of_le_of_le_pi_div_two _ _ _ _ hxy); linarith end lemma exists_sin_eq {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : ∃ y, -(π / 2) ≤ y ∧ y ≤ π / 2 ∧ sin y = x := @real.intermediate_value sin (-(π / 2)) (π / 2) x (λ _ _ _, continuous_iff_continuous_at.1 continuous_sin _) (by rwa [sin_neg, sin_pi_div_two]) (by rwa sin_pi_div_two) (le_trans (neg_nonpos.2 (le_of_lt pi_div_two_pos)) (le_of_lt pi_div_two_pos)) lemma sin_lt {x : ℝ} (h : 0 < x) : sin x < x := begin cases le_or_gt x 1 with h' h', { have hx : abs x = x := abs_of_nonneg (le_of_lt h), have : abs x ≤ 1, rwa [hx], have := sin_bound this, rw [abs_le] at this, have := this.2, rw [sub_le_iff_le_add', hx] at this, apply lt_of_le_of_lt this, rw [sub_add], apply lt_of_lt_of_le _ (le_of_eq (sub_zero x)), apply sub_lt_sub_left, rw sub_pos, apply mul_lt_mul', { rw [pow_succ x 3], refine le_trans _ (le_of_eq (one_mul _)), rw mul_le_mul_right, exact h', apply pow_pos h }, norm_num, norm_num, apply pow_pos h }, exact lt_of_le_of_lt (sin_le_one x) h' end /- note 1: this inequality is not tight, the tighter inequality is sin x > x - x ^ 3 / 6. note 2: this is also true for x > 1, but it's nontrivial for x just above 1. -/ lemma sin_gt_sub_cube {x : ℝ} (h : 0 < x) (h' : x ≤ 1) : sin x > x - x ^ 3 / 4 := begin have hx : abs x = x := abs_of_nonneg (le_of_lt h), have : abs x ≤ 1, rwa [hx], have := sin_bound this, rw [abs_le] at this, have := this.1, rw [le_sub_iff_add_le, hx] at this, refine lt_of_lt_of_le _ this, rw [add_comm, sub_add, sub_neg_eq_add], apply sub_lt_sub_left, apply add_lt_of_lt_sub_left, rw (show x ^ 3 / 4 - x ^ 3 / 6 = x ^ 3 / 12, by simp [div_eq_mul_inv, (mul_sub _ _ _).symm, -sub_eq_add_neg]; congr; norm_num), apply mul_lt_mul', { rw [pow_succ x 3], refine le_trans _ (le_of_eq (one_mul _)), rw mul_le_mul_right, exact h', apply pow_pos h }, norm_num, norm_num, apply pow_pos h end /-- The type of angles -/ def angle : Type := quotient_add_group.quotient (gmultiples (2 * π)) namespace angle instance angle.add_comm_group : add_comm_group angle := quotient_add_group.add_comm_group _ instance angle.has_coe : has_coe ℝ angle := ⟨quotient.mk'⟩ instance angle.is_add_group_hom : is_add_group_hom (coe : ℝ → angle) := @quotient_add_group.is_add_group_hom _ _ _ (normal_add_subgroup_of_add_comm_group _) @[simp] lemma coe_zero : ↑(0 : ℝ) = (0 : angle) := rfl @[simp] lemma coe_add (x y : ℝ) : ↑(x + y : ℝ) = (↑x + ↑y : angle) := rfl @[simp] lemma coe_neg (x : ℝ) : ↑(-x : ℝ) = -(↑x : angle) := rfl @[simp] lemma coe_sub (x y : ℝ) : ↑(x - y : ℝ) = (↑x - ↑y : angle) := rfl @[simp] lemma coe_gsmul (x : ℝ) (n : ℤ) : ↑(gsmul n x : ℝ) = gsmul n (↑x : angle) := is_add_group_hom.map_gsmul _ _ _ @[simp] lemma coe_two_pi : ↑(2 * π : ℝ) = (0 : angle) := quotient.sound' ⟨-1, by dsimp only; rw [neg_one_gsmul, add_zero]⟩ lemma angle_eq_iff_two_pi_dvd_sub {ψ θ : ℝ} : (θ : angle) = ψ ↔ ∃ k : ℤ, θ - ψ = 2 * π * k := by simp only [quotient_add_group.eq, gmultiples, set.mem_range, gsmul_eq_mul', (sub_eq_neg_add _ _).symm, eq_comm] theorem cos_eq_iff_eq_or_eq_neg {θ ψ : ℝ} : cos θ = cos ψ ↔ (θ : angle) = ψ ∨ (θ : angle) = -ψ := begin split, { intro Hcos, rw [←sub_eq_zero, cos_sub_cos, mul_eq_zero, mul_eq_zero, neg_eq_zero, eq_false_intro two_ne_zero, false_or, sin_eq_zero_iff, sin_eq_zero_iff] at Hcos, rcases Hcos with ⟨n, hn⟩ | ⟨n, hn⟩, { right, rw [eq_div_iff_mul_eq _ _ two_ne_zero, ← sub_eq_iff_eq_add] at hn, rw [← hn, coe_sub, eq_neg_iff_add_eq_zero, sub_add_cancel, mul_assoc, ← gsmul_eq_mul, coe_gsmul, mul_comm, coe_two_pi, gsmul_zero] }, { left, rw [eq_div_iff_mul_eq _ _ two_ne_zero, eq_sub_iff_add_eq] at hn, rw [← hn, coe_add, mul_assoc, ← gsmul_eq_mul, coe_gsmul, mul_comm, coe_two_pi, gsmul_zero, zero_add] } }, { rw [angle_eq_iff_two_pi_dvd_sub, ← coe_neg, angle_eq_iff_two_pi_dvd_sub], rintro (⟨k, H⟩ | ⟨k, H⟩), rw [← sub_eq_zero_iff_eq, cos_sub_cos, H, mul_assoc 2 π k, mul_div_cancel_left _ two_ne_zero, mul_comm π _, sin_int_mul_pi, mul_zero], rw [←sub_eq_zero_iff_eq, cos_sub_cos, ← sub_neg_eq_add, H, mul_assoc 2 π k, mul_div_cancel_left _ two_ne_zero, mul_comm π _, sin_int_mul_pi, mul_zero, zero_mul] } end theorem sin_eq_iff_eq_or_add_eq_pi {θ ψ : ℝ} : sin θ = sin ψ ↔ (θ : angle) = ψ ∨ (θ : angle) + ψ = π := begin split, { intro Hsin, rw [← cos_pi_div_two_sub, ← cos_pi_div_two_sub] at Hsin, cases cos_eq_iff_eq_or_eq_neg.mp Hsin with h h, { left, rw coe_sub at h, exact sub_left_inj.1 h }, right, rw [coe_sub, coe_sub, eq_neg_iff_add_eq_zero, add_sub, sub_add_eq_add_sub, ← coe_add, add_halves, sub_sub, sub_eq_zero] at h, exact h.symm }, { rw [angle_eq_iff_two_pi_dvd_sub, ←eq_sub_iff_add_eq, ←coe_sub, angle_eq_iff_two_pi_dvd_sub], rintro (⟨k, H⟩ | ⟨k, H⟩), rw [← sub_eq_zero_iff_eq, sin_sub_sin, H, mul_assoc 2 π k, mul_div_cancel_left _ two_ne_zero, mul_comm π _, sin_int_mul_pi, mul_zero, zero_mul], have H' : θ + ψ = (2 * k) * π + π := by rwa [←sub_add, sub_add_eq_add_sub, sub_eq_iff_eq_add, mul_assoc, mul_comm π _, ←mul_assoc] at H, rw [← sub_eq_zero_iff_eq, sin_sub_sin, H', add_div, mul_assoc 2 _ π, mul_div_cancel_left _ two_ne_zero, cos_add_pi_div_two, sin_int_mul_pi, neg_zero, mul_zero] } end theorem cos_sin_inj {θ ψ : ℝ} (Hcos : cos θ = cos ψ) (Hsin : sin θ = sin ψ) : (θ : angle) = ψ := begin cases cos_eq_iff_eq_or_eq_neg.mp Hcos with hc hc, { exact hc }, cases sin_eq_iff_eq_or_add_eq_pi.mp Hsin with hs hs, { exact hs }, rw [eq_neg_iff_add_eq_zero, hs] at hc, cases quotient.exact' hc with n hn, dsimp only at hn, rw [← neg_one_mul, add_zero, ← sub_eq_zero_iff_eq, gsmul_eq_mul, ← mul_assoc, ← sub_mul, mul_eq_zero, eq_false_intro (ne_of_gt pi_pos), or_false, sub_neg_eq_add, ← int.cast_zero, ← int.cast_one, ← int.cast_bit0, ← int.cast_mul, ← int.cast_add, int.cast_inj] at hn, have : (n * 2 + 1) % (2:ℤ) = 0 % (2:ℤ) := congr_arg (%(2:ℤ)) hn, rw [add_comm, int.add_mul_mod_self] at this, exact absurd this one_ne_zero end end angle /-- Inverse of the `sin` function, returns values in the range `-π / 2 ≤ arcsin x` and `arcsin x ≤ π / 2`. If the argument is not between `-1` and `1` it defaults to `0` -/ noncomputable def arcsin (x : ℝ) : ℝ := if hx : -1 ≤ x ∧ x ≤ 1 then classical.some (exists_sin_eq hx.1 hx.2) else 0 lemma arcsin_le_pi_div_two (x : ℝ) : arcsin x ≤ π / 2 := if hx : -1 ≤ x ∧ x ≤ 1 then by rw [arcsin, dif_pos hx]; exact (classical.some_spec (exists_sin_eq hx.1 hx.2)).2.1 else by rw [arcsin, dif_neg hx]; exact le_of_lt pi_div_two_pos lemma neg_pi_div_two_le_arcsin (x : ℝ) : -(π / 2) ≤ arcsin x := if hx : -1 ≤ x ∧ x ≤ 1 then by rw [arcsin, dif_pos hx]; exact (classical.some_spec (exists_sin_eq hx.1 hx.2)).1 else by rw [arcsin, dif_neg hx]; exact neg_nonpos.2 (le_of_lt pi_div_two_pos) lemma sin_arcsin {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : sin (arcsin x) = x := by rw [arcsin, dif_pos (and.intro hx₁ hx₂)]; exact (classical.some_spec (exists_sin_eq hx₁ hx₂)).2.2 lemma arcsin_sin {x : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) : arcsin (sin x) = x := sin_inj_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) hx₁ hx₂ (by rw sin_arcsin (neg_one_le_sin _) (sin_le_one _)) lemma arcsin_inj {x y : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) (hy₁ : -1 ≤ y) (hy₂ : y ≤ 1) (hxy : arcsin x = arcsin y) : x = y := by rw [← sin_arcsin hx₁ hx₂, ← sin_arcsin hy₁ hy₂, hxy] @[simp] lemma arcsin_zero : arcsin 0 = 0 := sin_inj_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) (neg_nonpos.2 (le_of_lt pi_div_two_pos)) (le_of_lt pi_div_two_pos) (by rw [sin_arcsin, sin_zero]; norm_num) @[simp] lemma arcsin_one : arcsin 1 = π / 2 := sin_inj_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) (by linarith [pi_pos]) (le_refl _) (by rw [sin_arcsin, sin_pi_div_two]; norm_num) @[simp] lemma arcsin_neg (x : ℝ) : arcsin (-x) = -arcsin x := if h : -1 ≤ x ∧ x ≤ 1 then have -1 ≤ -x ∧ -x ≤ 1, by rwa [neg_le_neg_iff, neg_le, and.comm], sin_inj_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) (neg_le_neg (arcsin_le_pi_div_two _)) (neg_le.1 (neg_pi_div_two_le_arcsin _)) (by rw [sin_arcsin this.1 this.2, sin_neg, sin_arcsin h.1 h.2]) else have ¬(-1 ≤ -x ∧ -x ≤ 1) := by rwa [neg_le_neg_iff, neg_le, and.comm], by rw [arcsin, arcsin, dif_neg h, dif_neg this, neg_zero] @[simp] lemma arcsin_neg_one : arcsin (-1) = -(π / 2) := by simp lemma arcsin_nonneg {x : ℝ} (hx : 0 ≤ x) : 0 ≤ arcsin x := if hx₁ : x ≤ 1 then not_lt.1 (λ h, not_lt.2 hx begin have := sin_lt_sin_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) (neg_nonpos.2 (le_of_lt pi_div_two_pos)) (le_of_lt pi_div_two_pos) h, rw [real.sin_arcsin, sin_zero] at this; linarith end) else by rw [arcsin, dif_neg]; simp [hx₁] lemma arcsin_eq_zero_iff {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : arcsin x = 0 ↔ x = 0 := ⟨λ h, have sin (arcsin x) = 0, by simp [h], by rwa [sin_arcsin hx₁ hx₂] at this, λ h, by simp [h]⟩ lemma arcsin_pos {x : ℝ} (hx₁ : 0 < x) (hx₂ : x ≤ 1) : 0 < arcsin x := lt_of_le_of_ne (arcsin_nonneg (le_of_lt hx₁)) (ne.symm (mt (arcsin_eq_zero_iff (by linarith) hx₂).1 (ne_of_lt hx₁).symm)) lemma arcsin_nonpos {x : ℝ} (hx : x ≤ 0) : arcsin x ≤ 0 := neg_nonneg.1 (arcsin_neg x ▸ arcsin_nonneg (neg_nonneg.2 hx)) /-- Inverse of the `cos` function, returns values in the range `0 ≤ arccos x` and `arccos x ≤ π`. If the argument is not between `-1` and `1` it defaults to `π / 2` -/ noncomputable def arccos (x : ℝ) : ℝ := π / 2 - arcsin x lemma arccos_eq_pi_div_two_sub_arcsin (x : ℝ) : arccos x = π / 2 - arcsin x := rfl lemma arcsin_eq_pi_div_two_sub_arccos (x : ℝ) : arcsin x = π / 2 - arccos x := by simp [arccos] lemma arccos_le_pi (x : ℝ) : arccos x ≤ π := by unfold arccos; linarith [neg_pi_div_two_le_arcsin x] lemma arccos_nonneg (x : ℝ) : 0 ≤ arccos x := by unfold arccos; linarith [arcsin_le_pi_div_two x] lemma cos_arccos {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : cos (arccos x) = x := by rw [arccos, cos_pi_div_two_sub, sin_arcsin hx₁ hx₂] lemma arccos_cos {x : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π) : arccos (cos x) = x := by rw [arccos, ← sin_pi_div_two_sub, arcsin_sin]; simp; linarith lemma arccos_inj {x y : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) (hy₁ : -1 ≤ y) (hy₂ : y ≤ 1) (hxy : arccos x = arccos y) : x = y := arcsin_inj hx₁ hx₂ hy₁ hy₂ $ by simp [arccos, *] at * @[simp] lemma arccos_zero : arccos 0 = π / 2 := by simp [arccos] @[simp] lemma arccos_one : arccos 1 = 0 := by simp [arccos] @[simp] lemma arccos_neg_one : arccos (-1) = π := by simp [arccos, add_halves] lemma arccos_neg (x : ℝ) : arccos (-x) = π - arccos x := by rw [← add_halves π, arccos, arcsin_neg, arccos, add_sub_assoc, sub_sub_self]; simp lemma cos_arcsin_nonneg (x : ℝ) : 0 ≤ cos (arcsin x) := cos_nonneg_of_neg_pi_div_two_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) lemma cos_arcsin {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : cos (arcsin x) = sqrt (1 - x ^ 2) := have sin (arcsin x) ^ 2 + cos (arcsin x) ^ 2 = 1 := sin_sq_add_cos_sq (arcsin x), begin rw [← eq_sub_iff_add_eq', ← sqrt_inj (pow_two_nonneg _) (sub_nonneg.2 (sin_sq_le_one (arcsin x))), pow_two, sqrt_mul_self (cos_arcsin_nonneg _)] at this, rw [this, sin_arcsin hx₁ hx₂], end lemma sin_arccos {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : sin (arccos x) = sqrt (1 - x ^ 2) := by rw [arccos_eq_pi_div_two_sub_arcsin, sin_pi_div_two_sub, cos_arcsin hx₁ hx₂] lemma abs_div_sqrt_one_add_lt (x : ℝ) : abs (x / sqrt (1 + x ^ 2)) < 1 := have h₁ : 0 < 1 + x ^ 2, from add_pos_of_pos_of_nonneg zero_lt_one (pow_two_nonneg _), have h₂ : 0 < sqrt (1 + x ^ 2), from sqrt_pos.2 h₁, by rw [abs_div, div_lt_iff (abs_pos_of_pos h₂), one_mul, mul_self_lt_mul_self_iff (abs_nonneg x) (abs_nonneg _), ← abs_mul, ← abs_mul, mul_self_sqrt (add_nonneg zero_le_one (pow_two_nonneg _)), abs_of_nonneg (mul_self_nonneg x), abs_of_nonneg (le_of_lt h₁), pow_two, add_comm]; exact lt_add_one _ lemma div_sqrt_one_add_lt_one (x : ℝ) : x / sqrt (1 + x ^ 2) < 1 := (abs_lt.1 (abs_div_sqrt_one_add_lt _)).2 lemma neg_one_lt_div_sqrt_one_add (x : ℝ) : -1 < x / sqrt (1 + x ^ 2) := (abs_lt.1 (abs_div_sqrt_one_add_lt _)).1 lemma tan_pos_of_pos_of_lt_pi_div_two {x : ℝ} (h0x : 0 < x) (hxp : x < π / 2) : 0 < tan x := by rw tan_eq_sin_div_cos; exact div_pos (sin_pos_of_pos_of_lt_pi h0x (by linarith)) (cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (by linarith) hxp) lemma tan_nonneg_of_nonneg_of_le_pi_div_two {x : ℝ} (h0x : 0 ≤ x) (hxp : x ≤ π / 2) : 0 ≤ tan x := match lt_or_eq_of_le h0x, lt_or_eq_of_le hxp with | or.inl hx0, or.inl hxp := le_of_lt (tan_pos_of_pos_of_lt_pi_div_two hx0 hxp) | or.inl hx0, or.inr hxp := by simp [hxp, tan_eq_sin_div_cos] | or.inr hx0, _ := by simp [hx0.symm] end lemma tan_neg_of_neg_of_pi_div_two_lt {x : ℝ} (hx0 : x < 0) (hpx : -(π / 2) < x) : tan x < 0 := neg_pos.1 (tan_neg x ▸ tan_pos_of_pos_of_lt_pi_div_two (by linarith) (by linarith [pi_pos])) lemma tan_nonpos_of_nonpos_of_neg_pi_div_two_le {x : ℝ} (hx0 : x ≤ 0) (hpx : -(π / 2) ≤ x) : tan x ≤ 0 := neg_nonneg.1 (tan_neg x ▸ tan_nonneg_of_nonneg_of_le_pi_div_two (by linarith) (by linarith [pi_pos])) lemma tan_lt_tan_of_nonneg_of_lt_pi_div_two {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x < π / 2) (hy₁ : 0 ≤ y) (hy₂ : y < π / 2) (hxy : x < y) : tan x < tan y := begin rw [tan_eq_sin_div_cos, tan_eq_sin_div_cos], exact div_lt_div (sin_lt_sin_of_le_of_le_pi_div_two (by linarith) (le_of_lt hx₂) (by linarith) (le_of_lt hy₂) hxy) (cos_le_cos_of_nonneg_of_le_pi hx₁ (by linarith) hy₁ (by linarith) (le_of_lt hxy)) (sin_nonneg_of_nonneg_of_le_pi hy₁ (by linarith)) (cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (by linarith) hy₂) end lemma tan_lt_tan_of_lt_of_lt_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) (hy₁ : -(π / 2) < y) (hy₂ : y < π / 2) (hxy : x < y) : tan x < tan y := match le_total x 0, le_total y 0 with | or.inl hx0, or.inl hy0 := neg_lt_neg_iff.1 $ by rw [← tan_neg, ← tan_neg]; exact tan_lt_tan_of_nonneg_of_lt_pi_div_two (neg_nonneg.2 hy0) (neg_lt.2 hy₁) (neg_nonneg.2 hx0) (neg_lt.2 hx₁) (neg_lt_neg hxy) | or.inl hx0, or.inr hy0 := (lt_or_eq_of_le hy0).elim (λ hy0, calc tan x ≤ 0 : tan_nonpos_of_nonpos_of_neg_pi_div_two_le hx0 (le_of_lt hx₁) ... < tan y : tan_pos_of_pos_of_lt_pi_div_two hy0 hy₂) (λ hy0, by rw [← hy0, tan_zero]; exact tan_neg_of_neg_of_pi_div_two_lt (hy0.symm ▸ hxy) hx₁) | or.inr hx0, or.inl hy0 := by linarith | or.inr hx0, or.inr hy0 := tan_lt_tan_of_nonneg_of_lt_pi_div_two hx0 hx₂ hy0 hy₂ hxy end lemma tan_inj_of_lt_of_lt_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) (hy₁ : -(π / 2) < y) (hy₂ : y < π / 2) (hxy : tan x = tan y) : x = y := match lt_trichotomy x y with | or.inl h := absurd (tan_lt_tan_of_lt_of_lt_pi_div_two hx₁ hx₂ hy₁ hy₂ h) (by rw hxy; exact lt_irrefl _) | or.inr (or.inl h) := h | or.inr (or.inr h) := absurd (tan_lt_tan_of_lt_of_lt_pi_div_two hy₁ hy₂ hx₁ hx₂ h) (by rw hxy; exact lt_irrefl _) end /-- Inverse of the `tan` function, returns values in the range `-π / 2 < arctan x` and `arctan x < π / 2` -/ noncomputable def arctan (x : ℝ) : ℝ := arcsin (x / sqrt (1 + x ^ 2)) lemma sin_arctan (x : ℝ) : sin (arctan x) = x / sqrt (1 + x ^ 2) := sin_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _)) lemma cos_arctan (x : ℝ) : cos (arctan x) = 1 / sqrt (1 + x ^ 2) := have h₁ : (0 : ℝ) < 1 + x ^ 2, from add_pos_of_pos_of_nonneg zero_lt_one (pow_two_nonneg _), have h₂ : (x / sqrt (1 + x ^ 2)) ^ 2 < 1, by rw [pow_two, ← abs_mul_self, _root_.abs_mul]; exact mul_lt_one_of_nonneg_of_lt_one_left (abs_nonneg _) (abs_div_sqrt_one_add_lt _) (le_of_lt (abs_div_sqrt_one_add_lt _)), by rw [arctan, cos_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _)), one_div_eq_inv, ← sqrt_inv, sqrt_inj (sub_nonneg.2 (le_of_lt h₂)) (inv_nonneg.2 (le_of_lt h₁)), div_pow _ (mt sqrt_eq_zero'.1 (not_le.2 h₁)), pow_two (sqrt _), mul_self_sqrt (le_of_lt h₁), ← domain.mul_left_inj (ne.symm (ne_of_lt h₁)), mul_sub, mul_div_cancel' _ (ne.symm (ne_of_lt h₁)), mul_inv_cancel (ne.symm (ne_of_lt h₁))]; simp lemma tan_arctan (x : ℝ) : tan (arctan x) = x := by rw [tan_eq_sin_div_cos, sin_arctan, cos_arctan, div_div_div_div_eq, mul_one, mul_div_assoc, div_self (mt sqrt_eq_zero'.1 (not_le_of_gt (add_pos_of_pos_of_nonneg zero_lt_one (pow_two_nonneg x)))), mul_one] lemma arctan_lt_pi_div_two (x : ℝ) : arctan x < π / 2 := lt_of_le_of_ne (arcsin_le_pi_div_two _) (λ h, ne_of_lt (div_sqrt_one_add_lt_one x) $ by rw [← sin_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _)), ← arctan, h, sin_pi_div_two]) lemma neg_pi_div_two_lt_arctan (x : ℝ) : -(π / 2) < arctan x := lt_of_le_of_ne (neg_pi_div_two_le_arcsin _) (λ h, ne_of_lt (neg_one_lt_div_sqrt_one_add x) $ by rw [← sin_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _)), ← arctan, ← h, sin_neg, sin_pi_div_two]) lemma tan_surjective : function.surjective tan := function.surjective_of_has_right_inverse ⟨_, tan_arctan⟩ lemma arctan_tan {x : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) : arctan (tan x) = x := tan_inj_of_lt_of_lt_pi_div_two (neg_pi_div_two_lt_arctan _) (arctan_lt_pi_div_two _) hx₁ hx₂ (by rw tan_arctan) @[simp] lemma arctan_zero : arctan 0 = 0 := by simp [arctan] @[simp] lemma arctan_neg (x : ℝ) : arctan (-x) = - arctan x := by simp [arctan, neg_div] end real namespace complex open_locale real /-- `arg` returns values in the range (-π, π], such that for `x ≠ 0`, `sin (arg x) = x.im / x.abs` and `cos (arg x) = x.re / x.abs`, `arg 0` defaults to `0` -/ noncomputable def arg (x : ℂ) : ℝ := if 0 ≤ x.re then real.arcsin (x.im / x.abs) else if 0 ≤ x.im then real.arcsin ((-x).im / x.abs) + π else real.arcsin ((-x).im / x.abs) - π lemma arg_le_pi (x : ℂ) : arg x ≤ π := if hx₁ : 0 ≤ x.re then by rw [arg, if_pos hx₁]; exact le_trans (real.arcsin_le_pi_div_two _) (le_of_lt (half_lt_self real.pi_pos)) else have hx : x ≠ 0, from λ h, by simpa [h, lt_irrefl] using hx₁, if hx₂ : 0 ≤ x.im then by rw [arg, if_neg hx₁, if_pos hx₂]; exact le_sub_iff_add_le.1 (by rw sub_self; exact real.arcsin_nonpos (by rw [neg_im, neg_div, neg_nonpos]; exact div_nonneg hx₂ (abs_pos.2 hx))) else by rw [arg, if_neg hx₁, if_neg hx₂]; exact sub_le_iff_le_add.2 (le_trans (real.arcsin_le_pi_div_two _) (by linarith [real.pi_pos])) lemma neg_pi_lt_arg (x : ℂ) : -π < arg x := if hx₁ : 0 ≤ x.re then by rw [arg, if_pos hx₁]; exact lt_of_lt_of_le (neg_lt_neg (half_lt_self real.pi_pos)) (real.neg_pi_div_two_le_arcsin _) else have hx : x ≠ 0, from λ h, by simpa [h, lt_irrefl] using hx₁, if hx₂ : 0 ≤ x.im then by rw [arg, if_neg hx₁, if_pos hx₂]; exact sub_lt_iff_lt_add.1 (lt_of_lt_of_le (by linarith [real.pi_pos]) (real.neg_pi_div_two_le_arcsin _)) else by rw [arg, if_neg hx₁, if_neg hx₂]; exact lt_sub_iff_add_lt.2 (by rw neg_add_self; exact real.arcsin_pos (by rw [neg_im]; exact div_pos (neg_pos.2 (lt_of_not_ge hx₂)) (abs_pos.2 hx)) (by rw [← abs_neg x]; exact (abs_le.1 (abs_im_div_abs_le_one _)).2)) lemma arg_eq_arg_neg_add_pi_of_im_nonneg_of_re_neg {x : ℂ} (hxr : x.re < 0) (hxi : 0 ≤ x.im) : arg x = arg (-x) + π := have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos], by rw [arg, arg, if_neg (not_le.2 hxr), if_pos this, if_pos hxi, abs_neg] lemma arg_eq_arg_neg_sub_pi_of_im_neg_of_re_neg {x : ℂ} (hxr : x.re < 0) (hxi : x.im < 0) : arg x = arg (-x) - π := have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos], by rw [arg, arg, if_neg (not_le.2 hxr), if_neg (not_le.2 hxi), if_pos this, abs_neg] @[simp] lemma arg_zero : arg 0 = 0 := by simp [arg, le_refl] @[simp] lemma arg_one : arg 1 = 0 := by simp [arg, zero_le_one] @[simp] lemma arg_neg_one : arg (-1) = π := by simp [arg, le_refl, not_le.2 (@zero_lt_one ℝ _)] @[simp] lemma arg_I : arg I = π / 2 := by simp [arg, le_refl] @[simp] lemma arg_neg_I : arg (-I) = -(π / 2) := by simp [arg, le_refl] lemma sin_arg (x : ℂ) : real.sin (arg x) = x.im / x.abs := by unfold arg; split_ifs; simp [arg, real.sin_arcsin (abs_le.1 (abs_im_div_abs_le_one x)).1 (abs_le.1 (abs_im_div_abs_le_one x)).2, real.sin_add, neg_div, real.arcsin_neg, real.sin_neg] private lemma cos_arg_of_re_nonneg {x : ℂ} (hx : x ≠ 0) (hxr : 0 ≤ x.re) : real.cos (arg x) = x.re / x.abs := have 0 ≤ 1 - (x.im / abs x) ^ 2, from sub_nonneg.2 $ by rw [pow_two, ← _root_.abs_mul_self, _root_.abs_mul, ← pow_two]; exact pow_le_one _ (_root_.abs_nonneg _) (abs_im_div_abs_le_one _), by rw [eq_div_iff_mul_eq _ _ (mt abs_eq_zero.1 hx), ← real.mul_self_sqrt (abs_nonneg x), arg, if_pos hxr, real.cos_arcsin (abs_le.1 (abs_im_div_abs_le_one x)).1 (abs_le.1 (abs_im_div_abs_le_one x)).2, ← real.sqrt_mul (abs_nonneg _), ← real.sqrt_mul this, sub_mul, div_pow _ (mt abs_eq_zero.1 hx), ← pow_two, div_mul_cancel _ (pow_ne_zero 2 (mt abs_eq_zero.1 hx)), one_mul, pow_two, mul_self_abs, norm_sq, pow_two, add_sub_cancel, real.sqrt_mul_self hxr] lemma cos_arg {x : ℂ} (hx : x ≠ 0) : real.cos (arg x) = x.re / x.abs := if hxr : 0 ≤ x.re then cos_arg_of_re_nonneg hx hxr else have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos] using hxr, if hxi : 0 ≤ x.im then have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos] using hxr, by rw [arg_eq_arg_neg_add_pi_of_im_nonneg_of_re_neg (not_le.1 hxr) hxi, real.cos_add_pi, cos_arg_of_re_nonneg (neg_ne_zero.2 hx) this]; simp [neg_div] else by rw [arg_eq_arg_neg_sub_pi_of_im_neg_of_re_neg (not_le.1 hxr) (not_le.1 hxi)]; simp [real.cos_add, neg_div, cos_arg_of_re_nonneg (neg_ne_zero.2 hx) this] lemma tan_arg {x : ℂ} : real.tan (arg x) = x.im / x.re := if hx : x = 0 then by simp [hx] else by rw [real.tan_eq_sin_div_cos, sin_arg, cos_arg hx, div_div_div_cancel_right _ _ (mt abs_eq_zero.1 hx)] lemma arg_cos_add_sin_mul_I {x : ℝ} (hx₁ : -π < x) (hx₂ : x ≤ π) : arg (cos x + sin x * I) = x := if hx₃ : -(π / 2) ≤ x ∧ x ≤ π / 2 then have hx₄ : 0 ≤ (cos x + sin x * I).re, by simp; exact real.cos_nonneg_of_neg_pi_div_two_le_of_le_pi_div_two hx₃.1 hx₃.2, by rw [arg, if_pos hx₄]; simp [abs_cos_add_sin_mul_I, sin_of_real_re, real.arcsin_sin hx₃.1 hx₃.2] else if hx₄ : x < -(π / 2) then have hx₅ : ¬0 ≤ (cos x + sin x * I).re := suffices ¬ 0 ≤ real.cos x, by simpa, not_le.2 $ by rw ← real.cos_neg; apply real.cos_neg_of_pi_div_two_lt_of_lt; linarith, have hx₆ : ¬0 ≤ (cos ↑x + sin ↑x * I).im := suffices real.sin x < 0, by simpa, by apply real.sin_neg_of_neg_of_neg_pi_lt; linarith, suffices -π + -real.arcsin (real.sin x) = x, by rw [arg, if_neg hx₅, if_neg hx₆]; simpa [abs_cos_add_sin_mul_I, sin_of_real_re], by rw [← real.arcsin_neg, ← real.sin_add_pi, real.arcsin_sin]; simp; linarith else have hx₅ : π / 2 < x, by cases not_and_distrib.1 hx₃; linarith, have hx₆ : ¬0 ≤ (cos x + sin x * I).re := suffices ¬0 ≤ real.cos x, by simpa, not_le.2 $ by apply real.cos_neg_of_pi_div_two_lt_of_lt; linarith, have hx₇ : 0 ≤ (cos x + sin x * I).im := suffices 0 ≤ real.sin x, by simpa, by apply real.sin_nonneg_of_nonneg_of_le_pi; linarith, suffices π - real.arcsin (real.sin x) = x, by rw [arg, if_neg hx₆, if_pos hx₇]; simpa [abs_cos_add_sin_mul_I, sin_of_real_re], by rw [← real.sin_pi_sub, real.arcsin_sin]; simp; linarith lemma arg_eq_arg_iff {x y : ℂ} (hx : x ≠ 0) (hy : y ≠ 0) : arg x = arg y ↔ (abs y / abs x : ℂ) * x = y := have hax : abs x ≠ 0, from (mt abs_eq_zero.1 hx), have hay : abs y ≠ 0, from (mt abs_eq_zero.1 hy), ⟨λ h, begin have hcos := congr_arg real.cos h, rw [cos_arg hx, cos_arg hy, div_eq_div_iff hax hay] at hcos, have hsin := congr_arg real.sin h, rw [sin_arg, sin_arg, div_eq_div_iff hax hay] at hsin, apply complex.ext, { rw [mul_re, ← of_real_div, of_real_re, of_real_im, zero_mul, sub_zero, mul_comm, ← mul_div_assoc, hcos, mul_div_cancel _ hax] }, { rw [mul_im, ← of_real_div, of_real_re, of_real_im, zero_mul, add_zero, mul_comm, ← mul_div_assoc, hsin, mul_div_cancel _ hax] } end, λ h, have hre : abs (y / x) * x.re = y.re, by rw ← of_real_div at h; simpa [-of_real_div] using congr_arg re h, have hre' : abs (x / y) * y.re = x.re, by rw [← hre, abs_div, abs_div, ← mul_assoc, div_mul_div, mul_comm (abs _), div_self (mul_ne_zero hay hax), one_mul], have him : abs (y / x) * x.im = y.im, by rw ← of_real_div at h; simpa [-of_real_div] using congr_arg im h, have him' : abs (x / y) * y.im = x.im, by rw [← him, abs_div, abs_div, ← mul_assoc, div_mul_div, mul_comm (abs _), div_self (mul_ne_zero hay hax), one_mul], have hxya : x.im / abs x = y.im / abs y, by rw [← him, abs_div, mul_comm, ← mul_div_comm, mul_div_cancel_left _ hay], have hnxya : (-x).im / abs x = (-y).im / abs y, by rw [neg_im, neg_im, neg_div, neg_div, hxya], if hxr : 0 ≤ x.re then have hyr : 0 ≤ y.re, from hre ▸ mul_nonneg (abs_nonneg _) hxr, by simp [arg, *] at * else have hyr : ¬ 0 ≤ y.re, from λ hyr, hxr $ hre' ▸ mul_nonneg (abs_nonneg _) hyr, if hxi : 0 ≤ x.im then have hyi : 0 ≤ y.im, from him ▸ mul_nonneg (abs_nonneg _) hxi, by simp [arg, *] at * else have hyi : ¬ 0 ≤ y.im, from λ hyi, hxi $ him' ▸ mul_nonneg (abs_nonneg _) hyi, by simp [arg, *] at *⟩ lemma arg_real_mul (x : ℂ) {r : ℝ} (hr : 0 < r) : arg (r * x) = arg x := if hx : x = 0 then by simp [hx] else (arg_eq_arg_iff (mul_ne_zero (of_real_ne_zero.2 (ne_of_lt hr).symm) hx) hx).2 $ by rw [abs_mul, abs_of_nonneg (le_of_lt hr), ← mul_assoc, of_real_mul, mul_comm (r : ℂ), ← div_div_eq_div_mul, div_mul_cancel _ (of_real_ne_zero.2 (ne_of_lt hr).symm), div_self (of_real_ne_zero.2 (mt abs_eq_zero.1 hx)), one_mul] lemma ext_abs_arg {x y : ℂ} (h₁ : x.abs = y.abs) (h₂ : x.arg = y.arg) : x = y := if hy : y = 0 then by simp * at * else have hx : x ≠ 0, from λ hx, by simp [*, eq_comm] at *, by rwa [arg_eq_arg_iff hx hy, h₁, div_self (of_real_ne_zero.2 (mt abs_eq_zero.1 hy)), one_mul] at h₂ lemma arg_of_real_of_nonneg {x : ℝ} (hx : 0 ≤ x) : arg x = 0 := by simp [arg, hx] lemma arg_of_real_of_neg {x : ℝ} (hx : x < 0) : arg x = π := by rw [arg_eq_arg_neg_add_pi_of_im_nonneg_of_re_neg, ← of_real_neg, arg_of_real_of_nonneg]; simp [*, le_iff_eq_or_lt, lt_neg] /-- Inverse of the `exp` function. Returns values such that `(log x).im > - π` and `(log x).im ≤ π`. `log 0 = 0`-/ noncomputable def log (x : ℂ) : ℂ := x.abs.log + arg x * I lemma log_re (x : ℂ) : x.log.re = x.abs.log := by simp [log] lemma log_im (x : ℂ) : x.log.im = x.arg := by simp [log] lemma exp_log {x : ℂ} (hx : x ≠ 0) : exp (log x) = x := by rw [log, exp_add_mul_I, ← of_real_sin, sin_arg, ← of_real_cos, cos_arg hx, ← of_real_exp, real.exp_log (abs_pos.2 hx), mul_add, of_real_div, of_real_div, mul_div_cancel' _ (of_real_ne_zero.2 (mt abs_eq_zero.1 hx)), ← mul_assoc, mul_div_cancel' _ (of_real_ne_zero.2 (mt abs_eq_zero.1 hx)), re_add_im] lemma exp_inj_of_neg_pi_lt_of_le_pi {x y : ℂ} (hx₁ : -π < x.im) (hx₂ : x.im ≤ π) (hy₁ : - π < y.im) (hy₂ : y.im ≤ π) (hxy : exp x = exp y) : x = y := by rw [exp_eq_exp_re_mul_sin_add_cos, exp_eq_exp_re_mul_sin_add_cos y] at hxy; exact complex.ext (real.exp_injective $ by simpa [abs_mul, abs_cos_add_sin_mul_I] using congr_arg complex.abs hxy) (by simpa [(of_real_exp _).symm, - of_real_exp, arg_real_mul _ (real.exp_pos _), arg_cos_add_sin_mul_I hx₁ hx₂, arg_cos_add_sin_mul_I hy₁ hy₂] using congr_arg arg hxy) lemma log_exp {x : ℂ} (hx₁ : -π < x.im) (hx₂: x.im ≤ π) : log (exp x) = x := exp_inj_of_neg_pi_lt_of_le_pi (by rw log_im; exact neg_pi_lt_arg _) (by rw log_im; exact arg_le_pi _) hx₁ hx₂ (by rw [exp_log (exp_ne_zero _)]) lemma of_real_log {x : ℝ} (hx : 0 ≤ x) : (x.log : ℂ) = log x := complex.ext (by rw [log_re, of_real_re, abs_of_nonneg hx]) (by rw [of_real_im, log_im, arg_of_real_of_nonneg hx]) @[simp] lemma log_zero : log 0 = 0 := by simp [log] @[simp] lemma log_one : log 1 = 0 := by simp [log] lemma log_neg_one : log (-1) = π * I := by simp [log] lemma log_I : log I = π / 2 * I := by simp [log] lemma log_neg_I : log (-I) = -(π / 2) * I := by simp [log] lemma exp_eq_one_iff {x : ℂ} : exp x = 1 ↔ ∃ n : ℤ, x = n * ((2 * π) * I) := have real.exp (x.re) * real.cos (x.im) = 1 → real.cos x.im ≠ -1, from λ h₁ h₂, begin rw [h₂, mul_neg_eq_neg_mul_symm, mul_one, neg_eq_iff_neg_eq] at h₁, have := real.exp_pos x.re, rw ← h₁ at this, exact absurd this (by norm_num) end, calc exp x = 1 ↔ (exp x).re = 1 ∧ (exp x).im = 0 : by simp [complex.ext_iff] ... ↔ real.cos x.im = 1 ∧ real.sin x.im = 0 ∧ x.re = 0 : begin rw exp_eq_exp_re_mul_sin_add_cos, simp [complex.ext_iff, cos_of_real_re, sin_of_real_re, exp_of_real_re, real.exp_ne_zero], split; finish [real.sin_eq_zero_iff_cos_eq] end ... ↔ (∃ n : ℤ, ↑n * (2 * π) = x.im) ∧ (∃ n : ℤ, ↑n * π = x.im) ∧ x.re = 0 : by rw [real.sin_eq_zero_iff, real.cos_eq_one_iff] ... ↔ ∃ n : ℤ, x = n * ((2 * π) * I) : ⟨λ ⟨⟨n, hn⟩, ⟨m, hm⟩, h⟩, ⟨n, by simp [complex.ext_iff, hn.symm, h]⟩, λ ⟨n, hn⟩, ⟨⟨n, by simp [hn]⟩, ⟨2 * n, by simp [hn, mul_comm, mul_assoc, mul_left_comm]⟩, by simp [hn]⟩⟩ lemma exp_eq_exp_iff_exp_sub_eq_one {x y : ℂ} : exp x = exp y ↔ exp (x - y) = 1 := by rw [exp_sub, div_eq_one_iff_eq _ (exp_ne_zero _)] lemma exp_eq_exp_iff_exists_int {x y : ℂ} : exp x = exp y ↔ ∃ n : ℤ, x = y + n * ((2 * π) * I) := by simp only [exp_eq_exp_iff_exp_sub_eq_one, exp_eq_one_iff, sub_eq_iff_eq_add'] @[simp] lemma cos_pi_div_two : cos (π / 2) = 0 := calc cos (π / 2) = real.cos (π / 2) : by rw [of_real_cos]; simp ... = 0 : by simp @[simp] lemma sin_pi_div_two : sin (π / 2) = 1 := calc sin (π / 2) = real.sin (π / 2) : by rw [of_real_sin]; simp ... = 1 : by simp @[simp] lemma sin_pi : sin π = 0 := by rw [← of_real_sin, real.sin_pi]; simp @[simp] lemma cos_pi : cos π = -1 := by rw [← of_real_cos, real.cos_pi]; simp @[simp] lemma sin_two_pi : sin (2 * π) = 0 := by simp [two_mul, sin_add] @[simp] lemma cos_two_pi : cos (2 * π) = 1 := by simp [two_mul, cos_add] lemma sin_add_pi (x : ℝ) : sin (x + π) = -sin x := by simp [sin_add] lemma sin_add_two_pi (x : ℝ) : sin (x + 2 * π) = sin x := by simp [sin_add_pi, sin_add, sin_two_pi, cos_two_pi] lemma cos_add_two_pi (x : ℝ) : cos (x + 2 * π) = cos x := by simp [cos_add, cos_two_pi, sin_two_pi] lemma sin_pi_sub (x : ℝ) : sin (π - x) = sin x := by simp [sin_add] lemma cos_add_pi (x : ℝ) : cos (x + π) = -cos x := by simp [cos_add] lemma cos_pi_sub (x : ℝ) : cos (π - x) = -cos x := by simp [cos_add] lemma sin_add_pi_div_two (x : ℝ) : sin (x + π / 2) = cos x := by simp [sin_add] lemma sin_sub_pi_div_two (x : ℝ) : sin (x - π / 2) = -cos x := by simp [sin_add] lemma sin_pi_div_two_sub (x : ℝ) : sin (π / 2 - x) = cos x := by simp [sin_add] lemma cos_add_pi_div_two (x : ℝ) : cos (x + π / 2) = -sin x := by simp [cos_add] lemma cos_sub_pi_div_two (x : ℝ) : cos (x - π / 2) = sin x := by simp [cos_add] lemma cos_pi_div_two_sub (x : ℝ) : cos (π / 2 - x) = sin x := by rw [← cos_neg, neg_sub, cos_sub_pi_div_two] lemma sin_nat_mul_pi (n : ℕ) : sin (n * π) = 0 := by induction n; simp [add_mul, sin_add, *] lemma sin_int_mul_pi (n : ℤ) : sin (n * π) = 0 := by cases n; simp [add_mul, sin_add, *, sin_nat_mul_pi] lemma cos_nat_mul_two_pi (n : ℕ) : cos (n * (2 * π)) = 1 := by induction n; simp [*, mul_add, cos_add, add_mul, cos_two_pi, sin_two_pi] lemma cos_int_mul_two_pi (n : ℤ) : cos (n * (2 * π)) = 1 := by cases n; simp only [cos_nat_mul_two_pi, int.of_nat_eq_coe, int.neg_succ_of_nat_coe, int.cast_coe_nat, int.cast_neg, (neg_mul_eq_neg_mul _ _).symm, cos_neg] lemma cos_int_mul_two_pi_add_pi (n : ℤ) : cos (n * (2 * π) + π) = -1 := by simp [cos_add, sin_add, cos_int_mul_two_pi] section pow noncomputable def cpow (x y : ℂ) : ℂ := if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) noncomputable instance : has_pow ℂ ℂ := ⟨cpow⟩ lemma cpow_def (x y : ℂ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) := rfl @[simp] lemma cpow_zero (x : ℂ) : x ^ (0 : ℂ) = 1 := by simp [cpow_def] @[simp] lemma zero_cpow {x : ℂ} (h : x ≠ 0) : (0 : ℂ) ^ x = 0 := by simp [cpow_def, *] @[simp] lemma cpow_one (x : ℂ) : x ^ (1 : ℂ) = x := if hx : x = 0 then by simp [hx, cpow_def] else by rw [cpow_def, if_neg (@one_ne_zero ℂ _), if_neg hx, mul_one, exp_log hx] @[simp] lemma one_cpow (x : ℂ) : (1 : ℂ) ^ x = 1 := by rw cpow_def; split_ifs; simp [one_ne_zero, *] at * lemma cpow_add {x : ℂ} (y z : ℂ) (hx : x ≠ 0) : x ^ (y + z) = x ^ y * x ^ z := by simp [cpow_def]; split_ifs; simp [*, exp_add, mul_add] at * lemma cpow_mul {x y : ℂ} (z : ℂ) (h₁ : -π < (log x * y).im) (h₂ : (log x * y).im ≤ π) : x ^ (y * z) = (x ^ y) ^ z := begin simp [cpow_def], split_ifs; simp [*, exp_ne_zero, log_exp h₁ h₂, mul_assoc] at * end lemma cpow_neg (x y : ℂ) : x ^ -y = (x ^ y)⁻¹ := by simp [cpow_def]; split_ifs; simp [exp_neg] @[simp] lemma cpow_nat_cast (x : ℂ) : ∀ (n : ℕ), x ^ (n : ℂ) = x ^ n | 0 := by simp | (n + 1) := if hx : x = 0 then by simp only [hx, pow_succ, complex.zero_cpow (nat.cast_ne_zero.2 (nat.succ_ne_zero _)), zero_mul] else by simp [cpow_def, hx, mul_add, exp_add, pow_succ, (cpow_nat_cast n).symm, exp_log hx] @[simp] lemma cpow_int_cast (x : ℂ) : ∀ (n : ℤ), x ^ (n : ℂ) = x ^ n | (n : ℕ) := by simp; refl | -[1+ n] := by rw fpow_neg_succ_of_nat; simp only [int.neg_succ_of_nat_coe, int.cast_neg, complex.cpow_neg, inv_eq_one_div, int.cast_coe_nat, cpow_nat_cast] lemma cpow_nat_inv_pow (x : ℂ) {n : ℕ} (hn : 0 < n) : (x ^ (n⁻¹ : ℂ)) ^ n = x := have (log x * (↑n)⁻¹).im = (log x).im / n, by rw [div_eq_mul_inv, ← of_real_nat_cast, ← of_real_inv, mul_im, of_real_re, of_real_im]; simp, have h : -π < (log x * (↑n)⁻¹).im ∧ (log x * (↑n)⁻¹).im ≤ π, from (le_total (log x).im 0).elim (λ h, ⟨calc -π < (log x).im : by simp [log, neg_pi_lt_arg] ... ≤ ((log x).im * 1) / n : le_div_of_mul_le (nat.cast_pos.2 hn) (mul_le_mul_of_nonpos_left (by rw ← nat.cast_one; exact nat.cast_le.2 hn) h) ... = (log x * (↑n)⁻¹).im : by simp [this], this.symm ▸ le_trans (div_nonpos_of_nonpos_of_pos h (nat.cast_pos.2 hn)) (le_of_lt real.pi_pos)⟩) (λ h, ⟨this.symm ▸ lt_of_lt_of_le (neg_neg_of_pos real.pi_pos) (div_nonneg h (nat.cast_pos.2 hn)), calc (log x * (↑n)⁻¹).im = (1 * (log x).im) / n : by simp [this] ... ≤ (log x).im : (div_le_of_le_mul (nat.cast_pos.2 hn) (mul_le_mul_of_nonneg_right (by rw ← nat.cast_one; exact nat.cast_le.2 hn) h)) ... ≤ _ : by simp [log, arg_le_pi]⟩), by rw [← cpow_nat_cast, ← cpow_mul _ h.1 h.2, inv_mul_cancel (show (n : ℂ) ≠ 0, from nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 hn)), cpow_one] end pow end complex namespace real noncomputable def rpow (x y : ℝ) := ((x : ℂ) ^ (y : ℂ)).re noncomputable instance : has_pow ℝ ℝ := ⟨rpow⟩ lemma rpow_def (x y : ℝ) : x ^ y = ((x : ℂ) ^ (y : ℂ)).re := rfl lemma rpow_def_of_nonneg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) := by simp only [rpow_def, complex.cpow_def]; split_ifs; simp [*, (complex.of_real_log hx).symm, -complex.of_real_mul, (complex.of_real_mul _ _).symm, complex.exp_of_real_re] at * lemma rpow_def_of_pos {x : ℝ} (hx : 0 < x) (y : ℝ) : x ^ y = exp (log x * y) := by rw [rpow_def_of_nonneg (le_of_lt hx), if_neg (ne_of_gt hx)] open_locale real lemma rpow_def_of_neg {x : ℝ} (hx : x < 0) (y : ℝ) : x ^ y = exp (log (-x) * y) * cos (y * π) := begin rw [rpow_def, complex.cpow_def, if_neg], have : complex.log x * y = ↑(log(-x) * y) + ↑(y * π) * complex.I, simp only [complex.log, abs_of_neg hx, complex.arg_of_real_of_neg hx, complex.abs_of_real, complex.of_real_mul], ring, { rw [this, complex.exp_add_mul_I, ← complex.of_real_exp, ← complex.of_real_cos, ← complex.of_real_sin, mul_add, ← complex.of_real_mul, ← mul_assoc, ← complex.of_real_mul, complex.add_re, complex.of_real_re, complex.mul_re, complex.I_re, complex.of_real_im], ring }, { rw complex.of_real_eq_zero, exact ne_of_lt hx } end lemma rpow_def_of_nonpos {x : ℝ} (hx : x ≤ 0) (y : ℝ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log (-x) * y) * cos (y * π) := by split_ifs; simp [rpow_def, *]; exact rpow_def_of_neg (lt_of_le_of_ne hx h) _ lemma rpow_pos_of_pos {x : ℝ} (hx : 0 < x) (y : ℝ) : 0 < x ^ y := by rw rpow_def_of_pos hx; apply exp_pos lemma abs_rpow_le_abs_rpow (x y : ℝ) : abs (x ^ y) ≤ abs (x) ^ y := abs_le_of_le_of_neg_le begin cases lt_trichotomy 0 x, { rw abs_of_pos h }, cases h, { simp [h.symm] }, rw [rpow_def_of_neg h, rpow_def_of_pos (abs_pos_of_neg h), abs_of_neg h], calc exp (log (-x) * y) * cos (y * π) ≤ exp (log (-x) * y) * 1 : mul_le_mul_of_nonneg_left (cos_le_one _) (le_of_lt $ exp_pos _) ... = _ : mul_one _ end begin cases lt_trichotomy 0 x, { rw abs_of_pos h, have : 0 < x^y := rpow_pos_of_pos h _, linarith }, cases h, { simp only [h.symm, abs_zero, rpow_def_of_nonneg], split_ifs, repeat {norm_num}}, rw [rpow_def_of_neg h, rpow_def_of_pos (abs_pos_of_neg h), abs_of_neg h], calc -(exp (log (-x) * y) * cos (y * π)) = exp (log (-x) * y) * (-cos (y * π)) : by ring ... ≤ exp (log (-x) * y) * 1 : mul_le_mul_of_nonneg_left (neg_le.2 $ neg_one_le_cos _) (le_of_lt $ exp_pos _) ... = exp (log (-x) * y) : mul_one _ end end real namespace complex lemma of_real_cpow {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : ((x ^ y : ℝ) : ℂ) = (x : ℂ) ^ (y : ℂ) := by simp [real.rpow_def_of_nonneg hx, complex.cpow_def]; split_ifs; simp [complex.of_real_log hx] @[simp] lemma abs_cpow_real (x : ℂ) (y : ℝ) : abs (x ^ (y : ℂ)) = x.abs ^ y := begin rw [real.rpow_def_of_nonneg (abs_nonneg _), complex.cpow_def], split_ifs; simp [*, abs_of_nonneg (le_of_lt (real.exp_pos _)), complex.log, complex.exp_add, add_mul, mul_right_comm _ I, exp_mul_I, abs_cos_add_sin_mul_I, (complex.of_real_mul _ _).symm, -complex.of_real_mul] at * end @[simp] lemma abs_cpow_inv_nat (x : ℂ) (n : ℕ) : abs (x ^ (n⁻¹ : ℂ)) = x.abs ^ (n⁻¹ : ℝ) := by rw ← abs_cpow_real; simp [-abs_cpow_real] end complex namespace real open_locale real variables {x y z : ℝ} @[simp] lemma rpow_zero (x : ℝ) : x ^ (0 : ℝ) = 1 := by simp [rpow_def] @[simp] lemma zero_rpow {x : ℝ} (h : x ≠ 0) : (0 : ℝ) ^ x = 0 := by simp [rpow_def, *] @[simp] lemma rpow_one (x : ℝ) : x ^ (1 : ℝ) = x := by simp [rpow_def] @[simp] lemma one_rpow (x : ℝ) : (1 : ℝ) ^ x = 1 := by simp [rpow_def] lemma rpow_nonneg_of_nonneg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : 0 ≤ x ^ y := by rw [rpow_def_of_nonneg hx]; split_ifs; simp only [zero_le_one, le_refl, le_of_lt (exp_pos _)] lemma rpow_add {x : ℝ} (y z : ℝ) (hx : 0 < x) : x ^ (y + z) = x ^ y * x ^ z := by simp only [rpow_def_of_pos hx, mul_add, exp_add] lemma rpow_mul {x : ℝ} (hx : 0 ≤ x) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z := by rw [← complex.of_real_inj, complex.of_real_cpow (rpow_nonneg_of_nonneg hx _), complex.of_real_cpow hx, complex.of_real_mul, complex.cpow_mul, complex.of_real_cpow hx]; simp only [(complex.of_real_mul _ _).symm, (complex.of_real_log hx).symm, complex.of_real_im, neg_lt_zero, pi_pos, le_of_lt pi_pos] lemma rpow_neg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : x ^ -y = (x ^ y)⁻¹ := by simp only [rpow_def_of_nonneg hx]; split_ifs; simp [*, exp_neg] at * @[simp] lemma rpow_nat_cast (x : ℝ) (n : ℕ) : x ^ (n : ℝ) = x ^ n := by simp only [rpow_def, (complex.of_real_pow _ _).symm, complex.cpow_nat_cast, complex.of_real_nat_cast, complex.of_real_re] @[simp] lemma rpow_int_cast (x : ℝ) (n : ℤ) : x ^ (n : ℝ) = x ^ n := by simp only [rpow_def, (complex.of_real_fpow _ _).symm, complex.cpow_int_cast, complex.of_real_int_cast, complex.of_real_re] lemma mul_rpow {x y z : ℝ} (h : 0 ≤ x) (h₁ : 0 ≤ y) : (x*y)^z = x^z * y^z := begin iterate 3 { rw real.rpow_def_of_nonneg }, split_ifs; simp * at *, { have hx : 0 < x, cases lt_or_eq_of_le h with h₂ h₂, exact h₂, exfalso, apply h_2, exact eq.symm h₂, have hy : 0 < y, cases lt_or_eq_of_le h₁ with h₂ h₂, exact h₂, exfalso, apply h_3, exact eq.symm h₂, rw [log_mul hx hy, add_mul, exp_add]}, { exact h₁}, { exact h}, { exact mul_nonneg h h₁}, end lemma one_le_rpow {x z : ℝ} (h : 1 ≤ x) (h₁ : 0 ≤ z) : 1 ≤ x^z := begin rw real.rpow_def_of_nonneg, split_ifs with h₂ h₃, { refl}, { simp [*, not_le_of_gt zero_lt_one] at *}, { have hx : 0 < x, exact lt_of_lt_of_le zero_lt_one h, rw [←log_le_log zero_lt_one hx, log_one] at h, have pos : 0 ≤ log x * z, exact mul_nonneg h h₁, rwa [←exp_le_exp, exp_zero] at pos}, { exact le_trans zero_le_one h}, end lemma rpow_le_rpow {x y z: ℝ} (h : 0 ≤ x) (h₁ : x ≤ y) (h₂ : 0 ≤ z) : x^z ≤ y^z := begin rw le_iff_eq_or_lt at h h₂, cases h₂, { rw [←h₂, rpow_zero, rpow_zero]}, { cases h, { rw [←h, zero_rpow], rw real.rpow_def_of_nonneg, split_ifs, { exact zero_le_one}, { refl}, { exact le_of_lt (exp_pos (log y * z))}, { rwa ←h at h₁}, { exact ne.symm (ne_of_lt h₂)}}, { have one_le : 1 ≤ y / x, rw one_le_div_iff_le h, exact h₁, have one_le_pow : 1 ≤ (y / x)^z, exact one_le_rpow one_le (le_of_lt h₂), rw [←mul_div_cancel y (ne.symm (ne_of_lt h)), mul_comm, mul_div_assoc], rw [mul_rpow (le_of_lt h) (le_trans zero_le_one one_le), mul_comm], exact (le_mul_of_ge_one_left (rpow_nonneg_of_nonneg (le_of_lt h) z) one_le_pow) } } end lemma rpow_lt_rpow (hx : 0 ≤ x) (hxy : x < y) (hz : 0 < z) : x^z < y^z := begin rw le_iff_eq_or_lt at hx, cases hx, { rw [← hx, zero_rpow (ne_of_gt hz)], exact rpow_pos_of_pos (by rwa ← hx at hxy) _ }, rw [rpow_def_of_pos hx, rpow_def_of_pos (lt_trans hx hxy), exp_lt_exp], exact mul_lt_mul_of_pos_right (log_lt_log hx hxy) hz end lemma rpow_lt_rpow_of_exponent_lt (hx : 1 < x) (hyz : y < z) : x^y < x^z := begin repeat {rw [rpow_def_of_pos (lt_trans zero_lt_one hx)]}, rw exp_lt_exp, exact mul_lt_mul_of_pos_left hyz (log_pos hx), end lemma rpow_le_rpow_of_exponent_le (hx : 1 ≤ x) (hyz : y ≤ z) : x^y ≤ x^z := begin repeat {rw [rpow_def_of_pos (lt_of_lt_of_le zero_lt_one hx)]}, rw exp_le_exp, exact mul_le_mul_of_nonneg_left hyz (log_nonneg hx), end lemma rpow_lt_rpow_of_exponent_gt (hx0 : 0 < x) (hx1 : x < 1) (hyz : z < y) : x^y < x^z := begin repeat {rw [rpow_def_of_pos hx0]}, rw exp_lt_exp, exact mul_lt_mul_of_neg_left hyz (log_neg hx0 hx1), end lemma rpow_le_rpow_of_exponent_ge (hx0 : 0 < x) (hx1 : x ≤ 1) (hyz : z ≤ y) : x^y ≤ x^z := begin repeat {rw [rpow_def_of_pos hx0]}, rw exp_le_exp, exact mul_le_mul_of_nonpos_left hyz (log_nonpos hx1), end lemma rpow_le_one {x e : ℝ} (he : 0 ≤ e) (hx : 0 ≤ x) (hx2 : x ≤ 1) : x^e ≤ 1 := by rw ←one_rpow e; apply rpow_le_rpow; assumption lemma one_lt_rpow (hx : 1 < x) (hz : 0 < z) : 1 < x^z := by { rw ← one_rpow z, exact rpow_lt_rpow zero_le_one hx hz } lemma rpow_lt_one (hx : 0 < x) (hx1 : x < 1) (hz : 0 < z) : x^z < 1 := by { rw ← one_rpow z, exact rpow_lt_rpow (le_of_lt hx) hx1 hz } lemma pow_nat_rpow_nat_inv {x : ℝ} (hx : 0 ≤ x) {n : ℕ} (hn : 0 < n) : (x ^ n) ^ (n⁻¹ : ℝ) = x := have hn0 : (n : ℝ) ≠ 0, by simpa [nat.pos_iff_ne_zero] using hn, by rw [← rpow_nat_cast, ← rpow_mul hx, mul_inv_cancel hn0, rpow_one] section prove_rpow_is_continuous lemma continuous_rpow_aux1 : continuous (λp : {p:ℝ×ℝ // 0 < p.1}, p.val.1 ^ p.val.2) := suffices h : continuous (λ p : {p:ℝ×ℝ // 0 < p.1 }, exp (log p.val.1 * p.val.2)), by { convert h, ext p, rw rpow_def_of_pos p.2 }, continuous_exp.comp $ continuous_mul (show continuous ((λp:{p:ℝ//0 < p}, log (p.val)) ∘ (λp:{p:ℝ×ℝ//0<p.fst}, ⟨p.val.1, p.2⟩)), from continuous_log'.comp $ continuous_subtype_mk _ $ continuous_fst.comp continuous_subtype_val) (continuous_snd.comp $ continuous_subtype_val.comp continuous_id) lemma continuous_rpow_aux2 : continuous (λ p : {p:ℝ×ℝ // p.1 < 0}, p.val.1 ^ p.val.2) := suffices h : continuous (λp:{p:ℝ×ℝ // p.1 < 0}, exp (log (-p.val.1) * p.val.2) * cos (p.val.2 * π)), by { convert h, ext p, rw [rpow_def_of_neg p.2] }, continuous_mul (continuous_exp.comp $ continuous_mul (show continuous $ (λp:{p:ℝ//0<p}, log (p.val))∘(λp:{p:ℝ×ℝ//p.1<0}, ⟨-p.val.1, neg_pos_of_neg p.2⟩), from continuous_log'.comp $ continuous_subtype_mk _ $ continuous_neg'.comp $ continuous_fst.comp continuous_subtype_val) (continuous_snd.comp $ continuous_subtype_val.comp continuous_id)) (continuous_cos.comp $ continuous_mul (continuous_snd.comp $ continuous_subtype_val.comp continuous_id) continuous_const) lemma continuous_at_rpow_of_ne_zero (hx : x ≠ 0) (y : ℝ) : continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) := begin cases lt_trichotomy 0 x, exact continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_rpow_aux1 _ h) (mem_nhds_sets (by { convert is_open_prod (is_open_lt' (0:ℝ)) is_open_univ, ext, finish }) h), cases h, { exact absurd h.symm hx }, exact continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_rpow_aux2 _ h) (mem_nhds_sets (by { convert is_open_prod (is_open_gt' (0:ℝ)) is_open_univ, ext, finish }) h) end lemma continuous_rpow_aux3 : continuous (λ p : {p:ℝ×ℝ // 0 < p.2}, p.val.1 ^ p.val.2) := continuous_iff_continuous_at.2 $ λ ⟨(x₀, y₀), hy₀⟩, begin by_cases hx₀ : x₀ = 0, { simp only [continuous_at, hx₀, zero_rpow (ne_of_gt hy₀), tendsto_nhds_nhds], assume ε ε0, rcases exists_pos_rat_lt (half_pos hy₀) with ⟨q, q_pos, q_lt⟩, let q := (q:ℝ), replace q_pos : 0 < q := rat.cast_pos.2 q_pos, let δ := min (min q (ε ^ (1 / q))) (1/2), have δ0 : 0 < δ := lt_min (lt_min q_pos (rpow_pos_of_pos ε0 _)) (by norm_num), have : δ ≤ q := le_trans (min_le_left _ _) (min_le_left _ _), have : δ ≤ ε ^ (1 / q) := le_trans (min_le_left _ _) (min_le_right _ _), have : δ < 1 := lt_of_le_of_lt (min_le_right _ _) (by norm_num), use δ, use δ0, rintros ⟨⟨x, y⟩, hy⟩, simp only [subtype.dist_eq, real.dist_eq, prod.dist_eq, sub_zero], assume h, rw max_lt_iff at h, cases h with xδ yy₀, have qy : q < y, calc q < y₀ / 2 : q_lt ... = y₀ - y₀ / 2 : (sub_half _).symm ... ≤ y₀ - δ : by linarith ... < y : sub_lt_of_abs_sub_lt_left yy₀, calc abs(x^y) ≤ abs(x)^y : abs_rpow_le_abs_rpow _ _ ... < δ ^ y : rpow_lt_rpow (abs_nonneg _) xδ hy ... < δ ^ q : by { refine rpow_lt_rpow_of_exponent_gt _ _ _, repeat {linarith} } ... ≤ (ε ^ (1 / q)) ^ q : by { refine rpow_le_rpow _ _ _, repeat {linarith} } ... = ε : by { rw [← rpow_mul, div_mul_cancel, rpow_one], exact ne_of_gt q_pos, linarith }}, { exact (continuous_within_at_iff_continuous_at_restrict (λp:ℝ×ℝ, p.1^p.2) _).1 (continuous_at_rpow_of_ne_zero hx₀ _).continuous_within_at } end lemma continuous_at_rpow_of_pos (hy : 0 < y) (x : ℝ) : continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) := continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_rpow_aux3 _ hy) (mem_nhds_sets (by { convert is_open_prod is_open_univ (is_open_lt' (0:ℝ)), ext, finish }) hy) variables {α : Type*} [topological_space α] {f g : α → ℝ} /-- `real.rpow` is continuous at all points except for the lower half of the y-axis. In other words, the function `λp:ℝ×ℝ, p.1^p.2` is continuous at `(x, y)` if `x ≠ 0` or `y > 0`. Multiple forms of the claim is provided in the current section. -/ lemma continuous_rpow (h : ∀a, f a ≠ 0 ∨ 0 < g a) (hf : continuous f) (hg : continuous g): continuous (λa:α, (f a) ^ (g a)) := continuous_iff_continuous_at.2 $ λ a, begin show continuous_at ((λp:ℝ×ℝ, p.1^p.2) ∘ (λa, (f a, g a))) a, refine continuous_at.comp _ (continuous_iff_continuous_at.1 (hf.prod_mk hg) _), { replace h := h a, cases h, { exact continuous_at_rpow_of_ne_zero h _ }, { exact continuous_at_rpow_of_pos h _ }}, end lemma continuous_rpow_of_ne_zero (h : ∀a, f a ≠ 0) (hf : continuous f) (hg : continuous g): continuous (λa:α, (f a) ^ (g a)) := continuous_rpow (λa, or.inl $ h a) hf hg lemma continuous_rpow_of_pos (h : ∀a, 0 < g a) (hf : continuous f) (hg : continuous g): continuous (λa:α, (f a) ^ (g a)) := continuous_rpow (λa, or.inr $ h a) hf hg end prove_rpow_is_continuous section sqrt lemma sqrt_eq_rpow : sqrt = λx:ℝ, x ^ (1/(2:ℝ)) := begin funext, by_cases h : 0 ≤ x, { rw [← mul_self_inj_of_nonneg, mul_self_sqrt h, ← pow_two, ← rpow_nat_cast, ← rpow_mul h], norm_num, exact sqrt_nonneg _, exact rpow_nonneg_of_nonneg h _ }, { replace h : x < 0 := lt_of_not_ge h, have : 1 / (2:ℝ) * π = π / (2:ℝ), ring, rw [sqrt_eq_zero_of_nonpos (le_of_lt h), rpow_def_of_neg h, this, cos_pi_div_two, mul_zero] } end lemma continuous_sqrt : continuous sqrt := by rw sqrt_eq_rpow; exact continuous_rpow_of_pos (λa, by norm_num) continuous_id continuous_const end sqrt end real
7dace98c901bbfa4931034fd8820d6fb1b88ca19
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Server/InfoUtils.lean
44669da11c815eb2106650c36e30283037c7e7c4
[ "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
10,041
lean
/- Copyright (c) 2021 Wojciech Nawrocki. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki -/ import Lean.DocString import Lean.Elab.InfoTree import Lean.PrettyPrinter.Delaborator.Options import Lean.Util.Sorry protected structure String.Range where start : String.Pos stop : String.Pos deriving Inhabited, Repr def String.Range.contains (r : String.Range) (pos : String.Pos) : Bool := r.start <= pos && pos < r.stop def Lean.Syntax.getRange? (stx : Syntax) (originalOnly := false) : Option String.Range := match stx.getPos? originalOnly, stx.getTailPos? originalOnly with | some start, some stop => some { start, stop } | _, _ => none namespace Lean.Elab /-- For every branch, find the deepest node in that branch matching `p` with a surrounding context (the innermost one) and return all of them. -/ partial def InfoTree.deepestNodes (p : ContextInfo → Info → Std.PersistentArray InfoTree → Option α) : InfoTree → List α := go none where go ctx? | context ctx t => go ctx t | n@(node i cs) => let ccs := cs.toList.map (go <| i.updateContext? ctx?) let cs' := ccs.join if !cs'.isEmpty then cs' else match ctx? with | some ctx => match p ctx i cs with | some a => [a] | _ => [] | _ => [] | _ => [] partial def InfoTree.foldInfo (f : ContextInfo → Info → α → α) (init : α) : InfoTree → α := go none init where go ctx? a | context ctx t => go ctx a t | node i ts => let a := match ctx? with | none => a | some ctx => f ctx i a ts.foldl (init := a) (go <| i.updateContext? ctx?) | _ => a def Info.isTerm : Info → Bool | ofTermInfo _ => true | _ => false def Info.isCompletion : Info → Bool | ofCompletionInfo .. => true | _ => false def InfoTree.getCompletionInfos (infoTree : InfoTree) : Array (ContextInfo × CompletionInfo) := infoTree.foldInfo (init := #[]) fun ctx info result => match info with | Info.ofCompletionInfo info => result.push (ctx, info) | _ => result def Info.stx : Info → Syntax | ofTacticInfo i => i.stx | ofTermInfo i => i.stx | ofCommandInfo i => i.stx | ofMacroExpansionInfo i => i.stx | ofFieldInfo i => i.stx | ofCompletionInfo i => i.stx def Info.lctx : Info → LocalContext | Info.ofTermInfo i => i.lctx | Info.ofFieldInfo i => i.lctx | _ => LocalContext.empty def Info.pos? (i : Info) : Option String.Pos := i.stx.getPos? (originalOnly := true) def Info.tailPos? (i : Info) : Option String.Pos := i.stx.getTailPos? (originalOnly := true) def Info.range? (i : Info) : Option String.Range := i.stx.getRange? (originalOnly := true) def Info.contains (i : Info) (pos : String.Pos) : Bool := i.range?.any (·.contains pos) def Info.size? (i : Info) : Option Nat := OptionM.run do let pos ← i.pos? let tailPos ← i.tailPos? return tailPos - pos -- `Info` without position information are considered to have "infinite" size def Info.isSmaller (i₁ i₂ : Info) : Bool := match i₁.size?, i₂.pos? with | some sz₁, some sz₂ => sz₁ < sz₂ | some _, none => true | _, _ => false def Info.occursBefore? (i : Info) (hoverPos : String.Pos) : Option Nat := OptionM.run do let tailPos ← i.tailPos? guard (tailPos ≤ hoverPos) return hoverPos - tailPos def Info.occursInside? (i : Info) (hoverPos : String.Pos) : Option Nat := OptionM.run do let headPos ← i.pos? let tailPos ← i.tailPos? guard (headPos ≤ hoverPos && hoverPos < tailPos) return hoverPos - headPos def InfoTree.smallestInfo? (p : Info → Bool) (t : InfoTree) : Option (ContextInfo × Info) := let ts := t.deepestNodes fun ctx i _ => if p i then some (ctx, i) else none let infos := ts.map fun (ci, i) => let diff := i.tailPos?.get! - i.pos?.get! (diff, ci, i) infos.toArray.getMax? (fun a b => a.1 > b.1) |>.map fun (_, ci, i) => (ci, i) /-- Find an info node, if any, which should be shown on hover/cursor at position `hoverPos`. -/ partial def InfoTree.hoverableInfoAt? (t : InfoTree) (hoverPos : String.Pos) : Option (ContextInfo × Info) := Id.run <| do let res := t.smallestInfo? fun i => Id.run <| do if i matches Info.ofFieldInfo _ || i.toElabInfo?.isSome then return i.contains hoverPos return false if let some (_, Info.ofTermInfo ti) := res then if ti.expr.isSyntheticSorry then return none res def Info.type? (i : Info) : MetaM (Option Expr) := match i with | Info.ofTermInfo ti => Meta.inferType ti.expr | Info.ofFieldInfo fi => Meta.inferType fi.val | _ => return none def Info.docString? (i : Info) : MetaM (Option String) := do let env ← getEnv if let Info.ofTermInfo ti := i then if let some n := ti.expr.constName? then return ← findDocString? env n if let Info.ofFieldInfo fi := i then return ← findDocString? env fi.projName if let some ei := i.toElabInfo? then return ← findDocString? env ei.elaborator <||> findDocString? env ei.stx.getKind return none /-- Construct a hover popup, if any, from an info node in a context.-/ def Info.fmtHover? (ci : ContextInfo) (i : Info) : IO (Option Format) := do ci.runMetaM i.lctx do let mut fmts := #[] try if let some f ← fmtTerm? then fmts := fmts.push f catch _ => pure () if let some m ← i.docString? then fmts := fmts.push m if fmts.isEmpty then none else f!"\n***\n".joinSep fmts.toList where fmtTerm? : MetaM (Option Format) := do match i with | Info.ofTermInfo ti => if ti.expr.isSort then -- types of sorts are funny to look at in widgets, but ultimately not very helpful return none let tp ← Meta.inferType ti.expr let eFmt ← Lean.withOptions (Lean.pp.fullNames.set · true |> (Lean.pp.universes.set · true)) do Meta.ppExpr ti.expr let tpFmt ← Meta.ppExpr tp -- try not to show too scary internals let fmt := if ti.expr.isConst || isAtomicFormat eFmt then f!"{eFmt} : {tpFmt}" else f!"{tpFmt}" return some f!"```lean {fmt} ```" | Info.ofFieldInfo fi => let tp ← Meta.inferType fi.val let tpFmt ← Meta.ppExpr tp return some f!"```lean {fi.fieldName} : {tpFmt} ```" | _ => return none isAtomicFormat : Format → Bool | Std.Format.text _ => true | Std.Format.group f _ => isAtomicFormat f | Std.Format.nest _ f => isAtomicFormat f | Std.Format.tag _ f => isAtomicFormat f | _ => false structure GoalsAtResult where ctxInfo : ContextInfo tacticInfo : TacticInfo useAfter : Bool /- Try to retrieve `TacticInfo` for `hoverPos`. We retrieve the `TacticInfo` `info`, if there is a node of the form `node (ofTacticInfo info) children` s.t. - `hoverPos` is sufficiently inside `info`'s range (see code), and - None of the `children` satisfy the condition above. That is, for composite tactics such as `induction`, we always give preference for information stored in nested (children) tactics. Moreover, we instruct the LSP server to use the state after the tactic execution if the hover is inside the info *and* there is no nested tactic info (i.e. it is a leaf tactic; tactic combinators should decide for themselves where to show intermediate/final states) -/ partial def InfoTree.goalsAt? (text : FileMap) (t : InfoTree) (hoverPos : String.Pos) : List GoalsAtResult := Id.run <| do t.deepestNodes fun | ctx, i@(Info.ofTacticInfo ti), cs => OptionM.run do if let (some pos, some tailPos) := (i.pos?, i.tailPos?) then let trailSize := i.stx.getTrailingSize -- show info at EOF even if strictly outside token + trail let atEOF := tailPos + trailSize == text.source.bsize guard <| pos ≤ hoverPos ∧ (hoverPos < tailPos + trailSize || atEOF) return { ctxInfo := ctx, tacticInfo := ti, useAfter := hoverPos > pos && (hoverPos >= tailPos || !cs.any (hasNestedTactic pos tailPos)) } else failure | _, _, _ => none where hasNestedTactic (pos tailPos) : InfoTree → Bool | InfoTree.node i@(Info.ofTacticInfo _) cs => Id.run <| do if let `(by $t) := i.stx then return false -- ignore term-nested proofs such as in `simp [show p by ...]` if let (some pos', some tailPos') := (i.pos?, i.tailPos?) then -- ignore nested infos of the same tactic, e.g. from expansion if (pos', tailPos') != (pos, tailPos) then return true cs.any (hasNestedTactic pos tailPos) | InfoTree.node (Info.ofMacroExpansionInfo _) cs => cs.any (hasNestedTactic pos tailPos) | _ => false /-- Find info nodes that should be used for the term goal feature. The main complication concerns applications like `f a b` where `f` is an identifier. In this case, the term goal at `f` should be the goal for the full application `f a b`. Therefore we first gather the position of these head function symbols such as `f`, and later ignore identifiers at these positions. -/ partial def InfoTree.termGoalAt? (t : InfoTree) (hoverPos : String.Pos) : Option (ContextInfo × Info) := let headFns : Std.HashSet String.Pos := t.foldInfo (init := {}) fun ctx i headFns => if let some pos := getHeadFnPos? i.stx then headFns.insert pos else headFns t.smallestInfo? fun i => Id.run <| do if i.contains hoverPos then if let Info.ofTermInfo ti := i then return !ti.stx.isIdent || !headFns.contains i.pos?.get! false where /- Returns the position of the head function symbol, if it is an identifier. -/ getHeadFnPos? (s : Syntax) (foundArgs := false) : Option String.Pos := match s with | `(($s)) => getHeadFnPos? s foundArgs | `($f $as*) => getHeadFnPos? f (foundArgs := foundArgs || !as.isEmpty) | stx => if foundArgs && stx.isIdent then stx.getPos? else none end Lean.Elab
c358afc79c57b6b3f87f33cdf009dd8ab1af7b08
3f7026ea8bef0825ca0339a275c03b911baef64d
/src/category_theory/limits/limits.lean
f94a94b768cf12bde6efe465f64e1ecf9f4b426c
[ "Apache-2.0" ]
permissive
rspencer01/mathlib
b1e3afa5c121362ef0881012cc116513ab09f18c
c7d36292c6b9234dc40143c16288932ae38fdc12
refs/heads/master
1,595,010,346,708
1,567,511,503,000
1,567,511,503,000
206,071,681
0
0
Apache-2.0
1,567,513,643,000
1,567,513,643,000
null
UTF-8
Lean
false
false
36,705
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Mario Carneiro, Scott Morrison, Floris van Doorn -/ import category_theory.whiskering import category_theory.yoneda import category_theory.limits.cones import category_theory.eq_to_hom open category_theory category_theory.category category_theory.functor opposite namespace category_theory.limits universes v u u' u'' w -- declare the `v`'s first; see `category_theory.category` for an explanation -- See the notes at the top of cones.lean, explaining why we can't allow `J : Prop` here. variables {J K : Type v} [small_category J] [small_category K] variables {C : Type u} [𝒞 : category.{v+1} C] include 𝒞 variables {F : J ⥤ C} /-- A cone `t` on `F` is a limit cone if each cone on `F` admits a unique cone morphism to `t`. -/ structure is_limit (t : cone F) := (lift : Π (s : cone F), s.X ⟶ t.X) (fac' : ∀ (s : cone F) (j : J), lift s ≫ t.π.app j = s.π.app j . obviously) (uniq' : ∀ (s : cone F) (m : s.X ⟶ t.X) (w : ∀ j : J, m ≫ t.π.app j = s.π.app j), m = lift s . obviously) restate_axiom is_limit.fac' attribute [simp] is_limit.fac restate_axiom is_limit.uniq' attribute [class] is_limit namespace is_limit instance subsingleton {t : cone F} : subsingleton (is_limit t) := ⟨by intros P Q; cases P; cases Q; congr; ext; solve_by_elim⟩ /- Repackaging the definition in terms of cone morphisms. -/ def lift_cone_morphism {t : cone F} (h : is_limit t) (s : cone F) : s ⟶ t := { hom := h.lift s } lemma uniq_cone_morphism {s t : cone F} (h : is_limit t) {f f' : s ⟶ t} : f = f' := have ∀ {g : s ⟶ t}, g = h.lift_cone_morphism s, by intro g; ext; exact h.uniq _ _ g.w, this.trans this.symm def mk_cone_morphism {t : cone F} (lift : Π (s : cone F), s ⟶ t) (uniq' : ∀ (s : cone F) (m : s ⟶ t), m = lift s) : is_limit t := { lift := λ s, (lift s).hom, uniq' := λ s m w, have cone_morphism.mk m w = lift s, by apply uniq', congr_arg cone_morphism.hom this } /-- Limit cones on `F` are unique up to isomorphism. -/ def unique_up_to_iso {s t : cone F} (P : is_limit s) (Q : is_limit t) : s ≅ t := { hom := Q.lift_cone_morphism s, inv := P.lift_cone_morphism t, hom_inv_id' := P.uniq_cone_morphism, inv_hom_id' := Q.uniq_cone_morphism } def of_iso_limit {r t : cone F} (P : is_limit r) (i : r ≅ t) : is_limit t := is_limit.mk_cone_morphism (λ s, P.lift_cone_morphism s ≫ i.hom) (λ s m, by rw ←i.comp_inv_eq; apply P.uniq_cone_morphism) variables {t : cone F} lemma hom_lift (h : is_limit t) {W : C} (m : W ⟶ t.X) : m = h.lift { X := W, π := { app := λ b, m ≫ t.π.app b } } := h.uniq { X := W, π := { app := λ b, m ≫ t.π.app b } } m (λ b, rfl) /-- Two morphisms into a limit are equal if their compositions with each cone morphism are equal. -/ lemma hom_ext (h : is_limit t) {W : C} {f f' : W ⟶ t.X} (w : ∀ j, f ≫ t.π.app j = f' ≫ t.π.app j) : f = f' := by rw [h.hom_lift f, h.hom_lift f']; congr; exact funext w /-- The universal property of a limit cone: a map `W ⟶ X` is the same as a cone on `F` with vertex `W`. -/ def hom_iso (h : is_limit t) (W : C) : (W ⟶ t.X) ≅ ((const J).obj W ⟶ F) := { hom := λ f, (t.extend f).π, inv := λ π, h.lift { X := W, π := π }, hom_inv_id' := by ext f; apply h.hom_ext; intro j; simp; dsimp; refl } @[simp] lemma hom_iso_hom (h : is_limit t) {W : C} (f : W ⟶ t.X) : (is_limit.hom_iso h W).hom f = (t.extend f).π := rfl /-- The limit of `F` represents the functor taking `W` to the set of cones on `F` with vertex `W`. -/ def nat_iso (h : is_limit t) : yoneda.obj t.X ≅ F.cones := nat_iso.of_components (λ W, is_limit.hom_iso h (unop W)) (by tidy). def hom_iso' (h : is_limit t) (W : C) : ((W ⟶ t.X) : Type v) ≅ { p : Π j, W ⟶ F.obj j // ∀ {j j'} (f : j ⟶ j'), p j ≫ F.map f = p j' } := h.hom_iso W ≪≫ { hom := λ π, ⟨λ j, π.app j, λ j j' f, by convert ←(π.naturality f).symm; apply id_comp⟩, inv := λ p, { app := λ j, p.1 j, naturality' := λ j j' f, begin dsimp, rw [id_comp], exact (p.2 f).symm end } } /-- If G : C → D is a faithful functor which sends t to a limit cone, then it suffices to check that the induced maps for the image of t can be lifted to maps of C. -/ def of_faithful {t : cone F} {D : Type u'} [category.{v+1} D] (G : C ⥤ D) [faithful G] (ht : is_limit (G.map_cone t)) (lift : Π (s : cone F), s.X ⟶ t.X) (h : ∀ s, G.map (lift s) = ht.lift (G.map_cone s)) : is_limit t := { lift := lift, fac' := λ s j, by apply G.injectivity; rw [G.map_comp, h]; apply ht.fac, uniq' := λ s m w, begin apply G.injectivity, rw h, refine ht.uniq (G.map_cone s) _ (λ j, _), convert ←congr_arg (λ f, G.map f) (w j), apply G.map_comp end } def iso_unique_cone_morphism {t : cone F} : is_limit t ≅ Π s, unique (s ⟶ t) := { hom := λ h s, { default := h.lift_cone_morphism s, uniq := λ _, h.uniq_cone_morphism }, inv := λ h, { lift := λ s, (h s).default.hom, uniq' := λ s f w, congr_arg cone_morphism.hom ((h s).uniq ⟨f, w⟩) } } namespace of_nat_iso variables {X : C} (h : yoneda.obj X ≅ F.cones) /-- If `F.cones` is represented by `X`, each morphism `f : Y ⟶ X` gives a cone with cone point `Y`. -/ def cone_of_hom {Y : C} (f : Y ⟶ X) : cone F := { X := Y, π := h.hom.app (op Y) f } /-- If `F.cones` is represented by `X`, each cone `s` gives a morphism `s.X ⟶ X`. -/ def hom_of_cone (s : cone F) : s.X ⟶ X := h.inv.app (op s.X) s.π @[simp] lemma cone_of_hom_of_cone (s : cone F) : cone_of_hom h (hom_of_cone h s) = s := begin dsimp [cone_of_hom, hom_of_cone], cases s, congr, dsimp, exact congr_fun (congr_fun (congr_arg nat_trans.app h.inv_hom_id) (op s_X)) s_π, end @[simp] lemma hom_of_cone_of_hom {Y : C} (f : Y ⟶ X) : hom_of_cone h (cone_of_hom h f) = f := congr_fun (congr_fun (congr_arg nat_trans.app h.hom_inv_id) (op Y)) f /-- If `F.cones` is represented by `X`, the cone corresponding to the identity morphism on `X` will be a limit cone. -/ def limit_cone : cone F := cone_of_hom h (𝟙 X) /-- If `F.cones` is represented by `X`, the cone corresponding to a morphism `f : Y ⟶ X` is the limit cone extended by `f`. -/ lemma cone_of_hom_fac {Y : C} (f : Y ⟶ X) : cone_of_hom h f = (limit_cone h).extend f := begin dsimp [cone_of_hom, limit_cone, cone.extend], congr, ext j, have t := congr_fun (h.hom.naturality f.op) (𝟙 X), dsimp at t, simp only [comp_id] at t, rw congr_fun (congr_arg nat_trans.app t) j, refl, end /-- If `F.cones` is represented by `X`, any cone is the extension of the limit cone by the corresponding morphism. -/ lemma cone_fac (s : cone F) : (limit_cone h).extend (hom_of_cone h s) = s := begin rw ←cone_of_hom_of_cone h s, conv_lhs { simp only [hom_of_cone_of_hom] }, apply (cone_of_hom_fac _ _).symm, end end of_nat_iso section open of_nat_iso /-- If `F.cones` is representable, then the cone corresponding to the identity morphism on the representing object is a limit cone. -/ def of_nat_iso {X : C} (h : yoneda.obj X ≅ F.cones) : is_limit (limit_cone h) := { lift := λ s, hom_of_cone h s, fac' := λ s j, begin have h := cone_fac h s, cases s, injection h with h₁ h₂, simp only [heq_iff_eq] at h₂, conv_rhs { rw ← h₂ }, refl, end, uniq' := λ s m w, begin rw ←hom_of_cone_of_hom h m, congr, rw cone_of_hom_fac, dsimp, cases s, congr, ext j, exact w j, end } end end is_limit /-- A cocone `t` on `F` is a colimit cocone if each cocone on `F` admits a unique cocone morphism from `t`. -/ structure is_colimit (t : cocone F) := (desc : Π (s : cocone F), t.X ⟶ s.X) (fac' : ∀ (s : cocone F) (j : J), t.ι.app j ≫ desc s = s.ι.app j . obviously) (uniq' : ∀ (s : cocone F) (m : t.X ⟶ s.X) (w : ∀ j : J, t.ι.app j ≫ m = s.ι.app j), m = desc s . obviously) restate_axiom is_colimit.fac' attribute [simp] is_colimit.fac restate_axiom is_colimit.uniq' attribute [class] is_colimit namespace is_colimit instance subsingleton {t : cocone F} : subsingleton (is_colimit t) := ⟨by intros P Q; cases P; cases Q; congr; ext; solve_by_elim⟩ /- Repackaging the definition in terms of cone morphisms. -/ def desc_cocone_morphism {t : cocone F} (h : is_colimit t) (s : cocone F) : t ⟶ s := { hom := h.desc s } lemma uniq_cocone_morphism {s t : cocone F} (h : is_colimit t) {f f' : t ⟶ s} : f = f' := have ∀ {g : t ⟶ s}, g = h.desc_cocone_morphism s, by intro g; ext; exact h.uniq _ _ g.w, this.trans this.symm def mk_cocone_morphism {t : cocone F} (desc : Π (s : cocone F), t ⟶ s) (uniq' : ∀ (s : cocone F) (m : t ⟶ s), m = desc s) : is_colimit t := { desc := λ s, (desc s).hom, uniq' := λ s m w, have cocone_morphism.mk m w = desc s, by apply uniq', congr_arg cocone_morphism.hom this } /-- Limit cones on `F` are unique up to isomorphism. -/ def unique_up_to_iso {s t : cocone F} (P : is_colimit s) (Q : is_colimit t) : s ≅ t := { hom := P.desc_cocone_morphism t, inv := Q.desc_cocone_morphism s, hom_inv_id' := P.uniq_cocone_morphism, inv_hom_id' := Q.uniq_cocone_morphism } def of_iso_colimit {r t : cocone F} (P : is_colimit r) (i : r ≅ t) : is_colimit t := is_colimit.mk_cocone_morphism (λ s, i.inv ≫ P.desc_cocone_morphism s) (λ s m, by rw i.eq_inv_comp; apply P.uniq_cocone_morphism) variables {t : cocone F} lemma hom_desc (h : is_colimit t) {W : C} (m : t.X ⟶ W) : m = h.desc { X := W, ι := { app := λ b, t.ι.app b ≫ m, naturality' := by intros; erw [←assoc, t.ι.naturality, comp_id, comp_id] } } := h.uniq { X := W, ι := { app := λ b, t.ι.app b ≫ m, naturality' := _ } } m (λ b, rfl) /-- Two morphisms out of a colimit are equal if their compositions with each cocone morphism are equal. -/ lemma hom_ext (h : is_colimit t) {W : C} {f f' : t.X ⟶ W} (w : ∀ j, t.ι.app j ≫ f = t.ι.app j ≫ f') : f = f' := by rw [h.hom_desc f, h.hom_desc f']; congr; exact funext w /-- The universal property of a colimit cocone: a map `X ⟶ W` is the same as a cocone on `F` with vertex `W`. -/ def hom_iso (h : is_colimit t) (W : C) : (t.X ⟶ W) ≅ (F ⟶ (const J).obj W) := { hom := λ f, (t.extend f).ι, inv := λ ι, h.desc { X := W, ι := ι }, hom_inv_id' := by ext f; apply h.hom_ext; intro j; simp; dsimp; refl } @[simp] lemma hom_iso_hom (h : is_colimit t) {W : C} (f : t.X ⟶ W) : (is_colimit.hom_iso h W).hom f = (t.extend f).ι := rfl /-- The colimit of `F` represents the functor taking `W` to the set of cocones on `F` with vertex `W`. -/ def nat_iso (h : is_colimit t) : coyoneda.obj (op t.X) ≅ F.cocones := nat_iso.of_components (is_colimit.hom_iso h) (by intros; ext; dsimp; rw ←assoc; refl) def hom_iso' (h : is_colimit t) (W : C) : ((t.X ⟶ W) : Type v) ≅ { p : Π j, F.obj j ⟶ W // ∀ {j j' : J} (f : j ⟶ j'), F.map f ≫ p j' = p j } := h.hom_iso W ≪≫ { hom := λ ι, ⟨λ j, ι.app j, λ j j' f, by convert ←(ι.naturality f); apply comp_id⟩, inv := λ p, { app := λ j, p.1 j, naturality' := λ j j' f, begin dsimp, rw [comp_id], exact (p.2 f) end } } /-- If G : C → D is a faithful functor which sends t to a colimit cocone, then it suffices to check that the induced maps for the image of t can be lifted to maps of C. -/ def of_faithful {t : cocone F} {D : Type u'} [category.{v+1} D] (G : C ⥤ D) [faithful G] (ht : is_colimit (G.map_cocone t)) (desc : Π (s : cocone F), t.X ⟶ s.X) (h : ∀ s, G.map (desc s) = ht.desc (G.map_cocone s)) : is_colimit t := { desc := desc, fac' := λ s j, by apply G.injectivity; rw [G.map_comp, h]; apply ht.fac, uniq' := λ s m w, begin apply G.injectivity, rw h, refine ht.uniq (G.map_cocone s) _ (λ j, _), convert ←congr_arg (λ f, G.map f) (w j), apply G.map_comp end } def iso_unique_cocone_morphism {t : cocone F} : is_colimit t ≅ Π s, unique (t ⟶ s) := { hom := λ h s, { default := h.desc_cocone_morphism s, uniq := λ _, h.uniq_cocone_morphism }, inv := λ h, { desc := λ s, (h s).default.hom, uniq' := λ s f w, congr_arg cocone_morphism.hom ((h s).uniq ⟨f, w⟩) } } namespace of_nat_iso variables {X : C} (h : coyoneda.obj (op X) ≅ F.cocones) /-- If `F.cocones` is corepresented by `X`, each morphism `f : X ⟶ Y` gives a cocone with cone point `Y`. -/ def cocone_of_hom {Y : C} (f : X ⟶ Y) : cocone F := { X := Y, ι := h.hom.app Y f } /-- If `F.cocones` is corepresented by `X`, each cocone `s` gives a morphism `X ⟶ s.X`. -/ def hom_of_cocone (s : cocone F) : X ⟶ s.X := h.inv.app s.X s.ι @[simp] lemma cocone_of_hom_of_cocone (s : cocone F) : cocone_of_hom h (hom_of_cocone h s) = s := begin dsimp [cocone_of_hom, hom_of_cocone], cases s, congr, dsimp, exact congr_fun (congr_fun (congr_arg nat_trans.app h.inv_hom_id) s_X) s_ι, end @[simp] lemma hom_of_cocone_of_hom {Y : C} (f : X ⟶ Y) : hom_of_cocone h (cocone_of_hom h f) = f := congr_fun (congr_fun (congr_arg nat_trans.app h.hom_inv_id) Y) f /-- If `F.cocones` is corepresented by `X`, the cocone corresponding to the identity morphism on `X` will be a colimit cocone. -/ def colimit_cocone : cocone F := cocone_of_hom h (𝟙 X) /-- If `F.cocones` is corepresented by `X`, the cocone corresponding to a morphism `f : Y ⟶ X` is the colimit cocone extended by `f`. -/ lemma cocone_of_hom_fac {Y : C} (f : X ⟶ Y) : cocone_of_hom h f = (colimit_cocone h).extend f := begin dsimp [cocone_of_hom, colimit_cocone, cocone.extend], congr, ext j, have t := congr_fun (h.hom.naturality f) (𝟙 X), dsimp at t, simp only [id_comp] at t, rw congr_fun (congr_arg nat_trans.app t) j, refl, end /-- If `F.cocones` is corepresented by `X`, any cocone is the extension of the colimit cocone by the corresponding morphism. -/ lemma cocone_fac (s : cocone F) : (colimit_cocone h).extend (hom_of_cocone h s) = s := begin rw ←cocone_of_hom_of_cocone h s, conv_lhs { simp only [hom_of_cocone_of_hom] }, apply (cocone_of_hom_fac _ _).symm, end end of_nat_iso section open of_nat_iso /-- If `F.cocones` is corepresentable, then the cocone corresponding to the identity morphism on the representing object is a colimit cocone. -/ def of_nat_iso {X : C} (h : coyoneda.obj (op X) ≅ F.cocones) : is_colimit (colimit_cocone h) := { desc := λ s, hom_of_cocone h s, fac' := λ s j, begin have h := cocone_fac h s, cases s, injection h with h₁ h₂, simp only [heq_iff_eq] at h₂, conv_rhs { rw ← h₂ }, refl, end, uniq' := λ s m w, begin rw ←hom_of_cocone_of_hom h m, congr, rw cocone_of_hom_fac, dsimp, cases s, congr, ext j, exact w j, end } end end is_colimit section limit /-- `has_limit F` represents a particular chosen limit of the diagram `F`. -/ class has_limit (F : J ⥤ C) := (cone : cone F) (is_limit : is_limit cone . tactic.apply_instance) variables (J C) /-- `C` has limits of shape `J` if we have chosen a particular limit of every functor `F : J ⥤ C`. -/ class has_limits_of_shape := (has_limit : Π F : J ⥤ C, has_limit F) /-- `C` has all (small) limits if it has limits of every shape. -/ class has_limits := (has_limits_of_shape : Π (J : Type v) [𝒥 : small_category J], has_limits_of_shape J C) variables {J C} instance has_limit_of_has_limits_of_shape {J : Type v} [small_category J] [H : has_limits_of_shape J C] (F : J ⥤ C) : has_limit F := has_limits_of_shape.has_limit F instance has_limits_of_shape_of_has_limits {J : Type v} [small_category J] [H : has_limits.{v} C] : has_limits_of_shape J C := has_limits.has_limits_of_shape C J /- Interface to the `has_limit` class. -/ def limit.cone (F : J ⥤ C) [has_limit F] : cone F := has_limit.cone F def limit (F : J ⥤ C) [has_limit F] := (limit.cone F).X def limit.π (F : J ⥤ C) [has_limit F] (j : J) : limit F ⟶ F.obj j := (limit.cone F).π.app j @[simp] lemma limit.cone_π {F : J ⥤ C} [has_limit F] (j : J) : (limit.cone F).π.app j = limit.π _ j := rfl @[simp] lemma limit.w (F : J ⥤ C) [has_limit F] {j j' : J} (f : j ⟶ j') : limit.π F j ≫ F.map f = limit.π F j' := (limit.cone F).w f instance limit.is_limit (F : J ⥤ C) [has_limit F] : is_limit (limit.cone F) := has_limit.is_limit.{v} F def limit.lift (F : J ⥤ C) [has_limit F] (c : cone F) : c.X ⟶ limit F := (limit.is_limit F).lift c @[simp] lemma limit.is_limit_lift {F : J ⥤ C} [has_limit F] (c : cone F) : (limit.is_limit F).lift c = limit.lift F c := rfl @[simp,reassoc] lemma limit.lift_π {F : J ⥤ C} [has_limit F] (c : cone F) (j : J) : limit.lift F c ≫ limit.π F j = c.π.app j := is_limit.fac _ c j def limit.cone_morphism {F : J ⥤ C} [has_limit F] (c : cone F) : cone_morphism c (limit.cone F) := (limit.is_limit F).lift_cone_morphism c @[simp] lemma limit.cone_morphism_hom {F : J ⥤ C} [has_limit F] (c : cone F) : (limit.cone_morphism c).hom = limit.lift F c := rfl @[simp] lemma limit.cone_morphism_π {F : J ⥤ C} [has_limit F] (c : cone F) (j : J) : (limit.cone_morphism c).hom ≫ limit.π F j = c.π.app j := by erw is_limit.fac @[extensionality] lemma limit.hom_ext {F : J ⥤ C} [has_limit F] {X : C} {f f' : X ⟶ limit F} (w : ∀ j, f ≫ limit.π F j = f' ≫ limit.π F j) : f = f' := (limit.is_limit F).hom_ext w def limit.hom_iso (F : J ⥤ C) [has_limit F] (W : C) : (W ⟶ limit F) ≅ (F.cones.obj (op W)) := (limit.is_limit F).hom_iso W @[simp] lemma limit.hom_iso_hom (F : J ⥤ C) [has_limit F] {W : C} (f : W ⟶ limit F) : (limit.hom_iso F W).hom f = (const J).map f ≫ (limit.cone F).π := (limit.is_limit F).hom_iso_hom f def limit.hom_iso' (F : J ⥤ C) [has_limit F] (W : C) : ((W ⟶ limit F) : Type v) ≅ { p : Π j, W ⟶ F.obj j // ∀ {j j' : J} (f : j ⟶ j'), p j ≫ F.map f = p j' } := (limit.is_limit F).hom_iso' W lemma limit.lift_extend {F : J ⥤ C} [has_limit F] (c : cone F) {X : C} (f : X ⟶ c.X) : limit.lift F (c.extend f) = f ≫ limit.lift F c := by obviously def has_limit_of_iso {F G : J ⥤ C} [has_limit F] (α : F ≅ G) : has_limit G := { cone := (cones.postcompose α.hom).obj (limit.cone F), is_limit := { lift := λ s, limit.lift F ((cones.postcompose α.inv).obj s), fac' := λ s j, begin rw [cones.postcompose_obj_π, nat_trans.comp_app, limit.cone_π], rw [category.assoc_symm, limit.lift_π], simp end, uniq' := λ s m w, begin apply limit.hom_ext, intro j, rw [limit.lift_π, cones.postcompose_obj_π, nat_trans.comp_app, ←nat_iso.app_inv, iso.eq_comp_inv], simpa using w j end } } /-- If a functor `G` has the same collection of cones as a functor `F` which has a limit, then `G` also has a limit. -/ -- See the construction of limits from products and equalizers -- for an example usage. def has_limit.of_cones_iso {J K : Type v} [small_category J] [small_category K] (F : J ⥤ C) (G : K ⥤ C) (h : F.cones ≅ G.cones) [has_limit F] : has_limit G := ⟨_, is_limit.of_nat_iso ((is_limit.nat_iso (limit.is_limit F)) ≪≫ h)⟩ section pre variables (F) [has_limit F] (E : K ⥤ J) [has_limit (E ⋙ F)] def limit.pre : limit F ⟶ limit (E ⋙ F) := limit.lift (E ⋙ F) { X := limit F, π := { app := λ k, limit.π F (E.obj k) } } @[simp] lemma limit.pre_π (k : K) : limit.pre F E ≫ limit.π (E ⋙ F) k = limit.π F (E.obj k) := by erw is_limit.fac @[simp] lemma limit.lift_pre (c : cone F) : limit.lift F c ≫ limit.pre F E = limit.lift (E ⋙ F) (c.whisker E) := by ext; simp variables {L : Type v} [small_category L] variables (D : L ⥤ K) [has_limit (D ⋙ E ⋙ F)] @[simp] lemma limit.pre_pre : limit.pre F E ≫ limit.pre (E ⋙ F) D = limit.pre F (D ⋙ E) := by ext j; erw [assoc, limit.pre_π, limit.pre_π, limit.pre_π]; refl end pre section post variables {D : Type u'} [𝒟 : category.{v+1} D] include 𝒟 variables (F) [has_limit F] (G : C ⥤ D) [has_limit (F ⋙ G)] def limit.post : G.obj (limit F) ⟶ limit (F ⋙ G) := limit.lift (F ⋙ G) { X := G.obj (limit F), π := { app := λ j, G.map (limit.π F j), naturality' := by intros j j' f; erw [←G.map_comp, limits.cone.w, id_comp]; refl } } @[simp] lemma limit.post_π (j : J) : limit.post F G ≫ limit.π (F ⋙ G) j = G.map (limit.π F j) := by erw is_limit.fac @[simp] lemma limit.lift_post (c : cone F) : G.map (limit.lift F c) ≫ limit.post F G = limit.lift (F ⋙ G) (G.map_cone c) := by ext; rw [assoc, limit.post_π, ←G.map_comp, limit.lift_π, limit.lift_π]; refl @[simp] lemma limit.post_post {E : Type u''} [category.{v+1} E] (H : D ⥤ E) [has_limit ((F ⋙ G) ⋙ H)] : /- H G (limit F) ⟶ H (limit (F ⋙ G)) ⟶ limit ((F ⋙ G) ⋙ H) equals -/ /- H G (limit F) ⟶ limit (F ⋙ (G ⋙ H)) -/ H.map (limit.post F G) ≫ limit.post (F ⋙ G) H = limit.post F (G ⋙ H) := by ext; erw [assoc, limit.post_π, ←H.map_comp, limit.post_π, limit.post_π]; refl end post lemma limit.pre_post {D : Type u'} [category.{v+1} D] (E : K ⥤ J) (F : J ⥤ C) (G : C ⥤ D) [has_limit F] [has_limit (E ⋙ F)] [has_limit (F ⋙ G)] [has_limit ((E ⋙ F) ⋙ G)] : /- G (limit F) ⟶ G (limit (E ⋙ F)) ⟶ limit ((E ⋙ F) ⋙ G) vs -/ /- G (limit F) ⟶ limit F ⋙ G ⟶ limit (E ⋙ (F ⋙ G)) or -/ G.map (limit.pre F E) ≫ limit.post (E ⋙ F) G = limit.post F G ≫ limit.pre (F ⋙ G) E := by ext; erw [assoc, limit.post_π, ←G.map_comp, limit.pre_π, assoc, limit.pre_π, limit.post_π]; refl open category_theory.equivalence instance has_limit_equivalence_comp (e : K ≌ J) [has_limit F] : has_limit (e.functor ⋙ F) := { cone := cone.whisker e.functor (limit.cone F), is_limit := let e' := cones.postcompose (e.inv_fun_id_assoc F).hom in { lift := λ s, limit.lift F (e'.obj (cone.whisker e.inverse s)), fac' := λ s j, begin dsimp, rw [limit.lift_π], dsimp [e'], erw [inv_fun_id_assoc_hom_app, counit_functor, ←s.π.naturality, id_comp] end, uniq' := λ s m w, begin apply limit.hom_ext, intro j, erw [limit.lift_π, ←limit.w F (e.counit_iso.hom.app j)], slice_lhs 1 2 { erw [w (e.inverse.obj j)] }, simp end } } def has_limit_of_equivalence_comp (e : K ≌ J) [has_limit (e.functor ⋙ F)] : has_limit F := begin haveI : has_limit (e.inverse ⋙ e.functor ⋙ F) := limits.has_limit_equivalence_comp e.symm, apply has_limit_of_iso (e.inv_fun_id_assoc F), end -- `has_limit_comp_equivalence` and `has_limit_of_comp_equivalence` -- are proved in `category_theory/adjunction/limits.lean`. section lim_functor variables [has_limits_of_shape J C] /-- `limit F` is functorial in `F`, when `C` has all limits of shape `J`. -/ def lim : (J ⥤ C) ⥤ C := { obj := λ F, limit F, map := λ F G α, limit.lift G { X := limit F, π := { app := λ j, limit.π F j ≫ α.app j, naturality' := λ j j' f, by erw [id_comp, assoc, ←α.naturality, ←assoc, limit.w] } }, map_comp' := λ F G H α β, by ext; erw [assoc, is_limit.fac, is_limit.fac, ←assoc, is_limit.fac, assoc]; refl } variables {F} {G : J ⥤ C} (α : F ⟶ G) @[simp,reassoc] lemma lim.map_π (j : J) : lim.map α ≫ limit.π G j = limit.π F j ≫ α.app j := by apply is_limit.fac @[simp] lemma limit.lift_map (c : cone F) : limit.lift F c ≫ lim.map α = limit.lift G ((cones.postcompose α).obj c) := by ext; rw [assoc, lim.map_π, ←assoc, limit.lift_π, limit.lift_π]; refl lemma limit.map_pre [has_limits_of_shape K C] (E : K ⥤ J) : lim.map α ≫ limit.pre G E = limit.pre F E ≫ lim.map (whisker_left E α) := by ext; rw [assoc, limit.pre_π, lim.map_π, assoc, lim.map_π, ←assoc, limit.pre_π]; refl lemma limit.map_pre' [has_limits_of_shape.{v} K C] (F : J ⥤ C) {E₁ E₂ : K ⥤ J} (α : E₁ ⟶ E₂) : limit.pre F E₂ = limit.pre F E₁ ≫ lim.map (whisker_right α F) := by ext1; simp [(category.assoc _ _ _ _).symm] lemma limit.id_pre (F : J ⥤ C) : limit.pre F (𝟭 _) = lim.map (functor.left_unitor F).inv := by tidy lemma limit.map_post {D : Type u'} [category.{v+1} D] [has_limits_of_shape J D] (H : C ⥤ D) : /- H (limit F) ⟶ H (limit G) ⟶ limit (G ⋙ H) vs H (limit F) ⟶ limit (F ⋙ H) ⟶ limit (G ⋙ H) -/ H.map (lim.map α) ≫ limit.post G H = limit.post F H ≫ lim.map (whisker_right α H) := begin ext, rw [assoc, limit.post_π, ←H.map_comp, lim.map_π, H.map_comp], rw [assoc, lim.map_π, ←assoc, limit.post_π], refl end def lim_yoneda : lim ⋙ yoneda ≅ category_theory.cones J C := nat_iso.of_components (λ F, nat_iso.of_components (λ W, limit.hom_iso F (unop W)) (by tidy)) (by tidy) end lim_functor def has_limits_of_shape_of_equivalence {J' : Type v} [small_category J'] (e : J ≌ J') [has_limits_of_shape J C] : has_limits_of_shape J' C := by { constructor, intro F, apply has_limit_of_equivalence_comp e, apply_instance } end limit section colimit /-- `has_colimit F` represents a particular chosen colimit of the diagram `F`. -/ class has_colimit (F : J ⥤ C) := (cocone : cocone F) (is_colimit : is_colimit cocone . tactic.apply_instance) variables (J C) /-- `C` has colimits of shape `J` if we have chosen a particular colimit of every functor `F : J ⥤ C`. -/ class has_colimits_of_shape := (has_colimit : Π F : J ⥤ C, has_colimit F) /-- `C` has all (small) colimits if it has colimits of every shape. -/ class has_colimits := (has_colimits_of_shape : Π (J : Type v) [𝒥 : small_category J], has_colimits_of_shape J C) variables {J C} instance has_colimit_of_has_colimits_of_shape {J : Type v} [small_category J] [H : has_colimits_of_shape J C] (F : J ⥤ C) : has_colimit F := has_colimits_of_shape.has_colimit F instance has_colimits_of_shape_of_has_colimits {J : Type v} [small_category J] [H : has_colimits.{v} C] : has_colimits_of_shape J C := has_colimits.has_colimits_of_shape C J /- Interface to the `has_colimit` class. -/ def colimit.cocone (F : J ⥤ C) [has_colimit F] : cocone F := has_colimit.cocone F def colimit (F : J ⥤ C) [has_colimit F] := (colimit.cocone F).X def colimit.ι (F : J ⥤ C) [has_colimit F] (j : J) : F.obj j ⟶ colimit F := (colimit.cocone F).ι.app j @[simp] lemma colimit.cocone_ι {F : J ⥤ C} [has_colimit F] (j : J) : (colimit.cocone F).ι.app j = colimit.ι _ j := rfl @[simp] lemma colimit.w (F : J ⥤ C) [has_colimit F] {j j' : J} (f : j ⟶ j') : F.map f ≫ colimit.ι F j' = colimit.ι F j := (colimit.cocone F).w f instance colimit.is_colimit (F : J ⥤ C) [has_colimit F] : is_colimit (colimit.cocone F) := has_colimit.is_colimit.{v} F def colimit.desc (F : J ⥤ C) [has_colimit F] (c : cocone F) : colimit F ⟶ c.X := (colimit.is_colimit F).desc c @[simp] lemma colimit.is_colimit_desc {F : J ⥤ C} [has_colimit F] (c : cocone F) : (colimit.is_colimit F).desc c = colimit.desc F c := rfl /-- We have lots of lemmas describing how to simplify `colimit.ι F j ≫ _`, and combined with `colimit.ext` we rely on these lemmas for many calculations. However, since `category.assoc` is a `@[simp]` lemma, often expressions are right associated, and it's hard to apply these lemmas about `colimit.ι`. We thus use `reassoc` to define additional `@[simp]` lemmas, with an arbitrary extra morphism. (see `tactic/reassoc_axiom.lean`) -/ @[simp, reassoc] lemma colimit.ι_desc {F : J ⥤ C} [has_colimit F] (c : cocone F) (j : J) : colimit.ι F j ≫ colimit.desc F c = c.ι.app j := is_colimit.fac _ c j def colimit.cocone_morphism {F : J ⥤ C} [has_colimit F] (c : cocone F) : cocone_morphism (colimit.cocone F) c := (colimit.is_colimit F).desc_cocone_morphism c @[simp] lemma colimit.cocone_morphism_hom {F : J ⥤ C} [has_colimit F] (c : cocone F) : (colimit.cocone_morphism c).hom = colimit.desc F c := rfl @[simp] lemma colimit.ι_cocone_morphism {F : J ⥤ C} [has_colimit F] (c : cocone F) (j : J) : colimit.ι F j ≫ (colimit.cocone_morphism c).hom = c.ι.app j := by erw is_colimit.fac @[extensionality] lemma colimit.hom_ext {F : J ⥤ C} [has_colimit F] {X : C} {f f' : colimit F ⟶ X} (w : ∀ j, colimit.ι F j ≫ f = colimit.ι F j ≫ f') : f = f' := (colimit.is_colimit F).hom_ext w def colimit.hom_iso (F : J ⥤ C) [has_colimit F] (W : C) : (colimit F ⟶ W) ≅ (F.cocones.obj W) := (colimit.is_colimit F).hom_iso W @[simp] lemma colimit.hom_iso_hom (F : J ⥤ C) [has_colimit F] {W : C} (f : colimit F ⟶ W) : (colimit.hom_iso F W).hom f = (colimit.cocone F).ι ≫ (const J).map f := (colimit.is_colimit F).hom_iso_hom f def colimit.hom_iso' (F : J ⥤ C) [has_colimit F] (W : C) : ((colimit F ⟶ W) : Type v) ≅ { p : Π j, F.obj j ⟶ W // ∀ {j j'} (f : j ⟶ j'), F.map f ≫ p j' = p j } := (colimit.is_colimit F).hom_iso' W lemma colimit.desc_extend (F : J ⥤ C) [has_colimit F] (c : cocone F) {X : C} (f : c.X ⟶ X) : colimit.desc F (c.extend f) = colimit.desc F c ≫ f := begin ext1, rw [←category.assoc], simp end def has_colimit_of_iso {F G : J ⥤ C} [has_colimit F] (α : G ≅ F) : has_colimit G := { cocone := (cocones.precompose α.hom).obj (colimit.cocone F), is_colimit := { desc := λ s, colimit.desc F ((cocones.precompose α.inv).obj s), fac' := λ s j, begin rw [cocones.precompose_obj_ι, nat_trans.comp_app, colimit.cocone_ι], rw [category.assoc, colimit.ι_desc, ←nat_iso.app_hom, ←iso.eq_inv_comp], refl end, uniq' := λ s m w, begin apply colimit.hom_ext, intro j, rw [colimit.ι_desc, cocones.precompose_obj_ι, nat_trans.comp_app, ←nat_iso.app_inv, iso.eq_inv_comp], simpa using w j end } } /-- If a functor `G` has the same collection of cocones as a functor `F` which has a colimit, then `G` also has a colimit. -/ def has_colimit.of_cocones_iso {J K : Type v} [small_category J] [small_category K] (F : J ⥤ C) (G : K ⥤ C) (h : F.cocones ≅ G.cocones) [has_colimit F] : has_colimit G := ⟨_, is_colimit.of_nat_iso ((is_colimit.nat_iso (colimit.is_colimit F)) ≪≫ h)⟩ section pre variables (F) [has_colimit F] (E : K ⥤ J) [has_colimit (E ⋙ F)] def colimit.pre : colimit (E ⋙ F) ⟶ colimit F := colimit.desc (E ⋙ F) { X := colimit F, ι := { app := λ k, colimit.ι F (E.obj k) } } @[simp, reassoc] lemma colimit.ι_pre (k : K) : colimit.ι (E ⋙ F) k ≫ colimit.pre F E = colimit.ι F (E.obj k) := by erw is_colimit.fac @[simp] lemma colimit.pre_desc (c : cocone F) : colimit.pre F E ≫ colimit.desc F c = colimit.desc (E ⋙ F) (c.whisker E) := by ext; rw [←assoc, colimit.ι_pre]; simp variables {L : Type v} [small_category L] variables (D : L ⥤ K) [has_colimit (D ⋙ E ⋙ F)] @[simp] lemma colimit.pre_pre : colimit.pre (E ⋙ F) D ≫ colimit.pre F E = colimit.pre F (D ⋙ E) := begin ext j, rw [←assoc, colimit.ι_pre, colimit.ι_pre], letI : has_colimit ((D ⋙ E) ⋙ F) := show has_colimit (D ⋙ E ⋙ F), by apply_instance, exact (colimit.ι_pre F (D ⋙ E) j).symm end end pre section post variables {D : Type u'} [𝒟 : category.{v+1} D] include 𝒟 variables (F) [has_colimit F] (G : C ⥤ D) [has_colimit (F ⋙ G)] def colimit.post : colimit (F ⋙ G) ⟶ G.obj (colimit F) := colimit.desc (F ⋙ G) { X := G.obj (colimit F), ι := { app := λ j, G.map (colimit.ι F j), naturality' := by intros j j' f; erw [←G.map_comp, limits.cocone.w, comp_id]; refl } } @[simp, reassoc] lemma colimit.ι_post (j : J) : colimit.ι (F ⋙ G) j ≫ colimit.post F G = G.map (colimit.ι F j) := by erw is_colimit.fac @[simp] lemma colimit.post_desc (c : cocone F) : colimit.post F G ≫ G.map (colimit.desc F c) = colimit.desc (F ⋙ G) (G.map_cocone c) := by ext; rw [←assoc, colimit.ι_post, ←G.map_comp, colimit.ι_desc, colimit.ι_desc]; refl @[simp] lemma colimit.post_post {E : Type u''} [category.{v+1} E] (H : D ⥤ E) [has_colimit ((F ⋙ G) ⋙ H)] : /- H G (colimit F) ⟶ H (colimit (F ⋙ G)) ⟶ colimit ((F ⋙ G) ⋙ H) equals -/ /- H G (colimit F) ⟶ colimit (F ⋙ (G ⋙ H)) -/ colimit.post (F ⋙ G) H ≫ H.map (colimit.post F G) = colimit.post F (G ⋙ H) := begin ext, rw [←assoc, colimit.ι_post, ←H.map_comp, colimit.ι_post], exact (colimit.ι_post F (G ⋙ H) j).symm end end post lemma colimit.pre_post {D : Type u'} [category.{v+1} D] (E : K ⥤ J) (F : J ⥤ C) (G : C ⥤ D) [has_colimit F] [has_colimit (E ⋙ F)] [has_colimit (F ⋙ G)] [has_colimit ((E ⋙ F) ⋙ G)] : /- G (colimit F) ⟶ G (colimit (E ⋙ F)) ⟶ colimit ((E ⋙ F) ⋙ G) vs -/ /- G (colimit F) ⟶ colimit F ⋙ G ⟶ colimit (E ⋙ (F ⋙ G)) or -/ colimit.post (E ⋙ F) G ≫ G.map (colimit.pre F E) = colimit.pre (F ⋙ G) E ≫ colimit.post F G := begin ext, rw [←assoc, colimit.ι_post, ←G.map_comp, colimit.ι_pre, ←assoc], letI : has_colimit (E ⋙ F ⋙ G) := show has_colimit ((E ⋙ F) ⋙ G), by apply_instance, erw [colimit.ι_pre (F ⋙ G) E j, colimit.ι_post] end open category_theory.equivalence instance has_colimit_equivalence_comp (e : K ≌ J) [has_colimit F] : has_colimit (e.functor ⋙ F) := { cocone := cocone.whisker e.functor (colimit.cocone F), is_colimit := let e' := cocones.precompose (e.inv_fun_id_assoc F).inv in { desc := λ s, colimit.desc F (e'.obj (cocone.whisker e.inverse s)), fac' := λ s j, begin dsimp, rw [colimit.ι_desc], dsimp [e'], erw [inv_fun_id_assoc_inv_app, ←functor_unit, s.ι.naturality, comp_id], refl end, uniq' := λ s m w, begin apply colimit.hom_ext, intro j, erw [colimit.ι_desc], have := w (e.inverse.obj j), simp at this, erw [←colimit.w F (e.counit_iso.hom.app j)] at this, erw [assoc, ←iso.eq_inv_comp (F.map_iso $ e.counit_iso.app j)] at this, erw [this], simp end } } def has_colimit_of_equivalence_comp (e : K ≌ J) [has_colimit (e.functor ⋙ F)] : has_colimit F := begin haveI : has_colimit (e.inverse ⋙ e.functor ⋙ F) := limits.has_colimit_equivalence_comp e.symm, apply has_colimit_of_iso (e.inv_fun_id_assoc F).symm, end section colim_functor variables [has_colimits_of_shape J C] /-- `colimit F` is functorial in `F`, when `C` has all colimits of shape `J`. -/ def colim : (J ⥤ C) ⥤ C := { obj := λ F, colimit F, map := λ F G α, colimit.desc F { X := colimit G, ι := { app := λ j, α.app j ≫ colimit.ι G j, naturality' := λ j j' f, by erw [comp_id, ←assoc, α.naturality, assoc, colimit.w] } }, map_comp' := λ F G H α β, by ext; erw [←assoc, is_colimit.fac, is_colimit.fac, assoc, is_colimit.fac, ←assoc]; refl } variables {F} {G : J ⥤ C} (α : F ⟶ G) @[simp, reassoc] lemma colim.ι_map (j : J) : colimit.ι F j ≫ colim.map α = α.app j ≫ colimit.ι G j := by apply is_colimit.fac @[simp] lemma colimit.map_desc (c : cocone G) : colim.map α ≫ colimit.desc G c = colimit.desc F ((cocones.precompose α).obj c) := by ext; rw [←assoc, colim.ι_map, assoc, colimit.ι_desc, colimit.ι_desc]; refl lemma colimit.pre_map [has_colimits_of_shape K C] (E : K ⥤ J) : colimit.pre F E ≫ colim.map α = colim.map (whisker_left E α) ≫ colimit.pre G E := by ext; rw [←assoc, colimit.ι_pre, colim.ι_map, ←assoc, colim.ι_map, assoc, colimit.ι_pre]; refl lemma colimit.pre_map' [has_colimits_of_shape.{v} K C] (F : J ⥤ C) {E₁ E₂ : K ⥤ J} (α : E₁ ⟶ E₂) : colimit.pre F E₁ = colim.map (whisker_right α F) ≫ colimit.pre F E₂ := by ext1; simp [(category.assoc _ _ _ _).symm] lemma colimit.pre_id (F : J ⥤ C) : colimit.pre F (𝟭 _) = colim.map (functor.left_unitor F).hom := by tidy lemma colimit.map_post {D : Type u'} [category.{v+1} D] [has_colimits_of_shape J D] (H : C ⥤ D) : /- H (colimit F) ⟶ H (colimit G) ⟶ colimit (G ⋙ H) vs H (colimit F) ⟶ colimit (F ⋙ H) ⟶ colimit (G ⋙ H) -/ colimit.post F H ≫ H.map (colim.map α) = colim.map (whisker_right α H) ≫ colimit.post G H:= begin ext, rw [←assoc, colimit.ι_post, ←H.map_comp, colim.ι_map, H.map_comp], rw [←assoc, colim.ι_map, assoc, colimit.ι_post], refl end def colim_coyoneda : colim.op ⋙ coyoneda ≅ category_theory.cocones J C := nat_iso.of_components (λ F, nat_iso.of_components (colimit.hom_iso (unop F)) (by tidy)) (by tidy) end colim_functor def has_colimits_of_shape_of_equivalence {J' : Type v} [small_category J'] (e : J ≌ J') [has_colimits_of_shape J C] : has_colimits_of_shape J' C := by { constructor, intro F, apply has_colimit_of_equivalence_comp e, apply_instance } end colimit end category_theory.limits
e634753a721c1499b39efdf62ffc78933c69515c
17d3c61bf162bf88be633867ed4cb201378a8769
/library/init/meta/smt/ematch.lean
bb2a90bf570a7c86d779a8a077c14c2bd69d9b6b
[ "Apache-2.0" ]
permissive
u20024804/lean
11def01468fb4796fb0da76015855adceac7e311
d315e424ff17faf6fe096a0a1407b70193009726
refs/heads/master
1,611,388,567,561
1,485,836,506,000
1,485,836,625,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,181
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.smt.congruence_closure import init.meta.attribute init.meta.simp_tactic open tactic /- Heuristic instantiation lemma -/ meta constant hinst_lemma : Type meta constant hinst_lemmas : Type /- (mk_core m e as_simp), m is used to decide which definitions will be unfolded in patterns. If as_simp is tt, then this tactic will try to use the left-hand-side of the conclusion as a pattern. -/ meta constant hinst_lemma.mk_core : transparency → expr → bool → tactic hinst_lemma meta constant hinst_lemma.mk_from_decl_core : transparency → name → bool → tactic hinst_lemma meta constant hinst_lemma.pp : hinst_lemma → tactic format meta constant hinst_lemma.id : hinst_lemma → name meta instance : has_to_tactic_format hinst_lemma := ⟨hinst_lemma.pp⟩ meta def hinst_lemma.mk (h : expr) : tactic hinst_lemma := hinst_lemma.mk_core reducible h ff meta def hinst_lemma.mk_from_decl (h : name) : tactic hinst_lemma := hinst_lemma.mk_from_decl_core reducible h ff meta constant hinst_lemmas.mk : hinst_lemmas meta constant hinst_lemmas.add : hinst_lemmas → hinst_lemma → hinst_lemmas meta constant hinst_lemmas.fold {α : Type} : hinst_lemmas → α → (hinst_lemma → α → α) → α meta constant hinst_lemmas.merge : hinst_lemmas → hinst_lemmas → hinst_lemmas meta def mk_hinst_singleton : hinst_lemma → hinst_lemmas := hinst_lemmas.add hinst_lemmas.mk meta def hinst_lemmas.pp (s : hinst_lemmas) : tactic format := let tac := s^.fold (return format.nil) (λ h tac, do hpp ← h^.pp, r ← tac, if r^.is_nil then return hpp else return (r ++ to_fmt "," ++ format.line ++ hpp)) in do r ← tac, return $ format.cbrace (format.group r) meta instance : has_to_tactic_format hinst_lemmas := ⟨hinst_lemmas.pp⟩ open tactic meta def to_hinst_lemmas_core (m : transparency) : bool → list name → hinst_lemmas → tactic hinst_lemmas | as_simp [] hs := return hs | as_simp (n::ns) hs := let add_core n := do h ← hinst_lemma.mk_from_decl_core m n as_simp, new_hs ← return $ hs^.add h, to_hinst_lemmas_core as_simp ns new_hs in do /- First check if n is the name of a function with equational lemmas associated with it -/ eqns ← tactic.get_eqn_lemmas_for tt n, match eqns with | [] := do /- n is not the name of a function definition or it does not have equational lemmas, then check if it is a lemma -/ add_core n | _ := do p ← is_prop_decl n, if p then add_core n /- n is a proposition -/ else do /- Add equational lemmas to resulting hinst_lemmas -/ new_hs ← to_hinst_lemmas_core tt eqns hs, to_hinst_lemmas_core as_simp ns new_hs end meta def mk_hinst_lemma_attr_core (attr_name : name) (as_simp : bool) : command := do t ← to_expr `(caching_user_attribute hinst_lemmas), a ← attr_name^.to_expr, b ← if as_simp then to_expr `(tt) else to_expr `(ff), v ← to_expr `(({ name := %%a, descr := "hinst_lemma attribute", mk_cache := λ ns, to_hinst_lemmas_core reducible %%b ns hinst_lemmas.mk, dependencies := [`reducibility] } : caching_user_attribute hinst_lemmas)), add_decl (declaration.defn attr_name [] t v reducibility_hints.abbrev ff), attribute.register attr_name meta def mk_hinst_lemma_attrs_core (as_simp : bool) : list name → command | [] := skip | (n::ns) := (mk_hinst_lemma_attr_core n as_simp >> mk_hinst_lemma_attrs_core ns) <|> (do type ← infer_type (expr.const n []), expected ← to_expr `(caching_user_attribute hinst_lemmas), (is_def_eq type expected <|> fail ("failed to create hinst_lemma attribute '" ++ n^.to_string ++ "', declaration already exists and has different type.")), mk_hinst_lemma_attrs_core ns) meta def merge_hinst_lemma_attrs (m : transparency) (as_simp : bool) : list name → hinst_lemmas → tactic hinst_lemmas | [] hs := return hs | (attr::attrs) hs := do ns ← attribute.get_instances attr, new_hs ← to_hinst_lemmas_core m as_simp ns hs, merge_hinst_lemma_attrs attrs new_hs /-- Create a new "cached" attribute (attr_name : caching_user_attribute hinst_lemmas). It also creates "cached" attributes for each attr_names and simp_attr_names if they have not been defined yet. Moreover, the hinst_lemmas for attr_name will be the union of the lemmas tagged with attr_name, attrs_name, and simp_attr_names. For the ones in simp_attr_names, we use the left-hand-side of the conclusion as the pattern. -/ meta def mk_hinst_lemma_attr_set (attr_name : name) (attr_names : list name) (simp_attr_names : list name) : command := do mk_hinst_lemma_attrs_core ff attr_names, mk_hinst_lemma_attrs_core tt simp_attr_names, t ← to_expr `(caching_user_attribute hinst_lemmas), a ← attr_name^.to_expr, l1 : expr ← list_name.to_expr attr_names, l2 : expr ← list_name.to_expr simp_attr_names, v ← to_expr `(({ name := %%a, descr := "hinst_lemma attribute set", mk_cache := λ ns, let aux1 : list name := %%l1, aux2 : list name := %%l2 in do { hs₁ ← to_hinst_lemmas_core reducible ff ns hinst_lemmas.mk, hs₂ ← merge_hinst_lemma_attrs reducible ff aux1 hs₁, merge_hinst_lemma_attrs reducible tt aux2 hs₂}, dependencies := [`reducibility] ++ %%l1 ++ %%l2 } : caching_user_attribute hinst_lemmas)), add_decl (declaration.defn attr_name [] t v reducibility_hints.abbrev ff), attribute.register attr_name meta def get_hinst_lemmas_for_attr (attr_name : name) : tactic hinst_lemmas := do cnst ← return (expr.const attr_name []), attr ← eval_expr (caching_user_attribute hinst_lemmas) cnst, caching_user_attribute.get_cache attr structure ematch_config := (max_instances : nat := 10000) (max_generation : nat := 10) /- Ematching -/ meta constant ematch_state : Type meta constant ematch_state.mk : ematch_config → ematch_state meta constant ematch_state.internalize : ematch_state → expr → tactic ematch_state namespace tactic meta constant ematch_core : transparency → cc_state → ematch_state → hinst_lemma → expr → tactic (list (expr × expr) × cc_state × ematch_state) meta constant ematch_all_core : transparency → cc_state → ematch_state → hinst_lemma → bool → tactic (list (expr × expr) × cc_state × ematch_state) meta def ematch : cc_state → ematch_state → hinst_lemma → expr → tactic (list (expr × expr) × cc_state × ematch_state) := ematch_core reducible meta def ematch_all : cc_state → ematch_state → hinst_lemma → bool → tactic (list (expr × expr) × cc_state × ematch_state) := ematch_all_core reducible end tactic
c6d1e75d63f4cacb91f887c85bfd180c280105e0
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/measure_theory/function/jacobian.lean
edb51c6fe39ff6f1255214e7c153ce9d37a50c77
[ "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
69,692
lean
/- Copyright (c) 2022 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import measure_theory.covering.besicovitch_vector_space import measure_theory.measure.haar_lebesgue import analysis.normed_space.pointwise import measure_theory.constructions.polish /-! # Change of variables in higher-dimensional integrals Let `μ` be a Lebesgue measure on a finite-dimensional real vector space `E`. Let `f : E → E` be a function which is injective and differentiable on a measurable set `s`, with derivative `f'`. Then we prove that `f '' s` is measurable, and its measure is given by the formula `μ (f '' s) = ∫⁻ x in s, |(f' x).det| ∂μ` (where `(f' x).det` is almost everywhere measurable, but not Borel-measurable in general). This formula is proved in `lintegral_abs_det_fderiv_eq_add_haar_image`. We deduce the change of variables formula for the Lebesgue and Bochner integrals, in `lintegral_image_eq_lintegral_abs_det_fderiv_mul` and `integral_image_eq_integral_abs_det_fderiv_smul` respectively. ## Main results * `add_haar_image_eq_zero_of_differentiable_on_of_add_haar_eq_zero`: if `f` is differentiable on a set `s` with zero measure, then `f '' s` also has zero measure. * `add_haar_image_eq_zero_of_det_fderiv_within_eq_zero`: if `f` is differentiable on a set `s`, and its derivative is never invertible, then `f '' s` has zero measure (a version of Sard's lemma). * `ae_measurable_fderiv_within`: if `f` is differentiable on a measurable set `s`, then `f'` is almost everywhere measurable on `s`. For the next statements, `s` is a measurable set and `f` is differentiable on `s` (with a derivative `f'`) and injective on `s`. * `measurable_image_of_fderiv_within`: the image `f '' s` is measurable. * `measurable_embedding_of_fderiv_within`: the function `s.restrict f` is a measurable embedding. * `lintegral_abs_det_fderiv_eq_add_haar_image`: the image measure is given by `μ (f '' s) = ∫⁻ x in s, |(f' x).det| ∂μ`. * `lintegral_image_eq_lintegral_abs_det_fderiv_mul`: for `g : E → ℝ≥0∞`, one has `∫⁻ x in f '' s, g x ∂μ = ∫⁻ x in s, ennreal.of_real (|(f' x).det|) * g (f x) ∂μ`. * `integral_image_eq_integral_abs_det_fderiv_smul`: for `g : E → F`, one has `∫ x in f '' s, g x ∂μ = ∫ x in s, |(f' x).det| • g (f x) ∂μ`. * `integrable_on_image_iff_integrable_on_abs_det_fderiv_smul`: for `g : E → F`, the function `g` is integrable on `f '' s` if and only if `|(f' x).det| • g (f x))` is integrable on `s`. ## Implementation Typical versions of these results in the literature have much stronger assumptions: `s` would typically be open, and the derivative `f' x` would depend continuously on `x` and be invertible everywhere, to have the local inverse theorem at our disposal. The proof strategy under our weaker assumptions is more involved. We follow [Fremlin, *Measure Theory* (volume 2)][fremlin_vol2]. The first remark is that, if `f` is sufficiently well approximated by a linear map `A` on a set `s`, then `f` expands the volume of `s` by at least `A.det - ε` and at most `A.det + ε`, where the closeness condition depends on `A` in a non-explicit way (see `add_haar_image_le_mul_of_det_lt` and `mul_le_add_haar_image_of_lt_det`). This fact holds for balls by a simple inclusion argument, and follows for general sets using the Besicovitch covering theorem to cover the set by balls with measures adding up essentially to `μ s`. When `f` is differentiable on `s`, one may partition `s` into countably many subsets `s ∩ t n` (where `t n` is measurable), on each of which `f` is well approximated by a linear map, so that the above results apply. See `exists_partition_approximates_linear_on_of_has_fderiv_within_at`, which follows from the pointwise differentiability (in a non-completely trivial way, as one should ensure a form of uniformity on the sets of the partition). Combining the above two results would give the conclusion, except for two difficulties: it is not obvious why `f '' s` and `f'` should be measurable, which prevents us from using countable additivity for the measure and the integral. It turns out that `f '' s` is indeed measurable, and that `f'` is almost everywhere measurable, which is enough to recover countable additivity. The measurability of `f '' s` follows from the deep Lusin-Souslin theorem ensuring that, in a Polish space, a continuous injective image of a measurable set is measurable. The key point to check the almost everywhere measurability of `f'` is that, if `f` is approximated up to `δ` by a linear map on a set `s`, then `f'` is within `δ` of `A` on a full measure subset of `s` (namely, its density points). With the above approximation argument, it follows that `f'` is the almost everywhere limit of a sequence of measurable functions (which are constant on the pieces of the good discretization), and is therefore almost everywhere measurable. ## Tags Change of variables in integrals ## References [Fremlin, *Measure Theory* (volume 2)][fremlin_vol2] -/ open measure_theory measure_theory.measure metric filter set finite_dimensional asymptotics topological_space open_locale nnreal ennreal topological_space pointwise variables {E F : Type*} [normed_add_comm_group E] [normed_space ℝ E] [finite_dimensional ℝ E] [normed_add_comm_group F] [normed_space ℝ F] {s : set E} {f : E → E} {f' : E → E →L[ℝ] E} /-! ### Decomposition lemmas We state lemmas ensuring that a differentiable function can be approximated, on countably many measurable pieces, by linear maps (with a prescribed precision depending on the linear map). -/ /-- Assume that a function `f` has a derivative at every point of a set `s`. Then one may cover `s` with countably many closed sets `t n` on which `f` is well approximated by linear maps `A n`. -/ lemma exists_closed_cover_approximates_linear_on_of_has_fderiv_within_at [second_countable_topology F] (f : E → F) (s : set E) (f' : E → E →L[ℝ] F) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (r : (E →L[ℝ] F) → ℝ≥0) (rpos : ∀ A, r A ≠ 0) : ∃ (t : ℕ → set E) (A : ℕ → (E →L[ℝ] F)), (∀ n, is_closed (t n)) ∧ (s ⊆ ⋃ n, t n) ∧ (∀ n, approximates_linear_on f (A n) (s ∩ t n) (r (A n))) ∧ (s.nonempty → ∀ n, ∃ y ∈ s, A n = f' y) := begin /- Choose countably many linear maps `f' z`. For every such map, if `f` has a derivative at `x` close enough to `f' z`, then `f y - f x` is well approximated by `f' z (y - x)` for `y` close enough to `x`, say on a ball of radius `r` (or even `u n` for some `n`, where `u` is a fixed sequence tending to `0`). Let `M n z` be the points where this happens. Then this set is relatively closed inside `s`, and moreover in every closed ball of radius `u n / 3` inside it the map is well approximated by `f' z`. Using countably many closed balls to split `M n z` into small diameter subsets `K n z p`, one obtains the desired sets `t q` after reindexing. -/ -- exclude the trivial case where `s` is empty rcases eq_empty_or_nonempty s with rfl|hs, { refine ⟨λ n, ∅, λ n, 0, _, _, _, _⟩; simp }, -- we will use countably many linear maps. Select these from all the derivatives since the -- space of linear maps is second-countable obtain ⟨T, T_count, hT⟩ : ∃ T : set s, T.countable ∧ (⋃ x ∈ T, ball (f' (x : E)) (r (f' x))) = ⋃ (x : s), ball (f' x) (r (f' x)) := topological_space.is_open_Union_countable _ (λ x, is_open_ball), -- fix a sequence `u` of positive reals tending to zero. obtain ⟨u, u_anti, u_pos, u_lim⟩ : ∃ (u : ℕ → ℝ), strict_anti u ∧ (∀ (n : ℕ), 0 < u n) ∧ tendsto u at_top (𝓝 0) := exists_seq_strict_anti_tendsto (0 : ℝ), -- `M n z` is the set of points `x` such that `f y - f x` is close to `f' z (y - x)` for `y` -- in the ball of radius `u n` around `x`. let M : ℕ → T → set E := λ n z, {x | x ∈ s ∧ ∀ y ∈ s ∩ ball x (u n), ‖f y - f x - f' z (y - x)‖ ≤ r (f' z) * ‖y - x‖}, -- As `f` is differentiable everywhere on `s`, the sets `M n z` cover `s` by design. have s_subset : ∀ x ∈ s, ∃ (n : ℕ) (z : T), x ∈ M n z, { assume x xs, obtain ⟨z, zT, hz⟩ : ∃ z ∈ T, f' x ∈ ball (f' (z : E)) (r (f' z)), { have : f' x ∈ ⋃ (z ∈ T), ball (f' (z : E)) (r (f' z)), { rw hT, refine mem_Union.2 ⟨⟨x, xs⟩, _⟩, simpa only [mem_ball, subtype.coe_mk, dist_self] using (rpos (f' x)).bot_lt }, rwa mem_Union₂ at this }, obtain ⟨ε, εpos, hε⟩ : ∃ (ε : ℝ), 0 < ε ∧ ‖f' x - f' z‖ + ε ≤ r (f' z), { refine ⟨r (f' z) - ‖f' x - f' z‖, _, le_of_eq (by abel)⟩, simpa only [sub_pos] using mem_ball_iff_norm.mp hz }, obtain ⟨δ, δpos, hδ⟩ : ∃ (δ : ℝ) (H : 0 < δ), ball x δ ∩ s ⊆ {y | ‖f y - f x - (f' x) (y - x)‖ ≤ ε * ‖y - x‖} := metric.mem_nhds_within_iff.1 (is_o.def (hf' x xs) εpos), obtain ⟨n, hn⟩ : ∃ n, u n < δ := ((tendsto_order.1 u_lim).2 _ δpos).exists, refine ⟨n, ⟨z, zT⟩, ⟨xs, _⟩⟩, assume y hy, calc ‖f y - f x - (f' z) (y - x)‖ = ‖(f y - f x - (f' x) (y - x)) + (f' x - f' z) (y - x)‖ : begin congr' 1, simp only [continuous_linear_map.coe_sub', map_sub, pi.sub_apply], abel, end ... ≤ ‖f y - f x - (f' x) (y - x)‖ + ‖(f' x - f' z) (y - x)‖ : norm_add_le _ _ ... ≤ ε * ‖y - x‖ + ‖f' x - f' z‖ * ‖y - x‖ : begin refine add_le_add (hδ _) (continuous_linear_map.le_op_norm _ _), rw inter_comm, exact inter_subset_inter_right _ (ball_subset_ball hn.le) hy, end ... ≤ r (f' z) * ‖y - x‖ : begin rw [← add_mul, add_comm], exact mul_le_mul_of_nonneg_right hε (norm_nonneg _), end }, -- the sets `M n z` are relatively closed in `s`, as all the conditions defining it are clearly -- closed have closure_M_subset : ∀ n z, s ∩ closure (M n z) ⊆ M n z, { rintros n z x ⟨xs, hx⟩, refine ⟨xs, λ y hy, _⟩, obtain ⟨a, aM, a_lim⟩ : ∃ (a : ℕ → E), (∀ k, a k ∈ M n z) ∧ tendsto a at_top (𝓝 x) := mem_closure_iff_seq_limit.1 hx, have L1 : tendsto (λ (k : ℕ), ‖f y - f (a k) - (f' z) (y - a k)‖) at_top (𝓝 ‖f y - f x - (f' z) (y - x)‖), { apply tendsto.norm, have L : tendsto (λ k, f (a k)) at_top (𝓝 (f x)), { apply (hf' x xs).continuous_within_at.tendsto.comp, apply tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ a_lim, exact eventually_of_forall (λ k, (aM k).1) }, apply tendsto.sub (tendsto_const_nhds.sub L), exact ((f' z).continuous.tendsto _).comp (tendsto_const_nhds.sub a_lim) }, have L2 : tendsto (λ (k : ℕ), (r (f' z) : ℝ) * ‖y - a k‖) at_top (𝓝 (r (f' z) * ‖y - x‖)) := (tendsto_const_nhds.sub a_lim).norm.const_mul _, have I : ∀ᶠ k in at_top, ‖f y - f (a k) - (f' z) (y - a k)‖ ≤ r (f' z) * ‖y - a k‖, { have L : tendsto (λ k, dist y (a k)) at_top (𝓝 (dist y x)) := tendsto_const_nhds.dist a_lim, filter_upwards [(tendsto_order.1 L).2 _ hy.2], assume k hk, exact (aM k).2 y ⟨hy.1, hk⟩ }, exact le_of_tendsto_of_tendsto L1 L2 I }, -- choose a dense sequence `d p` rcases topological_space.exists_dense_seq E with ⟨d, hd⟩, -- split `M n z` into subsets `K n z p` of small diameters by intersecting with the ball -- `closed_ball (d p) (u n / 3)`. let K : ℕ → T → ℕ → set E := λ n z p, closure (M n z) ∩ closed_ball (d p) (u n / 3), -- on the sets `K n z p`, the map `f` is well approximated by `f' z` by design. have K_approx : ∀ n (z : T) p, approximates_linear_on f (f' z) (s ∩ K n z p) (r (f' z)), { assume n z p x hx y hy, have yM : y ∈ M n z := closure_M_subset _ _ ⟨hy.1, hy.2.1⟩, refine yM.2 _ ⟨hx.1, _⟩, calc dist x y ≤ dist x (d p) + dist y (d p) : dist_triangle_right _ _ _ ... ≤ u n / 3 + u n / 3 : add_le_add hx.2.2 hy.2.2 ... < u n : by linarith [u_pos n] }, -- the sets `K n z p` are also closed, again by design. have K_closed : ∀ n (z : T) p, is_closed (K n z p) := λ n z p, is_closed_closure.inter is_closed_ball, -- reindex the sets `K n z p`, to let them only depend on an integer parameter `q`. obtain ⟨F, hF⟩ : ∃ F : ℕ → ℕ × T × ℕ, function.surjective F, { haveI : encodable T := T_count.to_encodable, haveI : nonempty T, { unfreezingI { rcases eq_empty_or_nonempty T with rfl|hT }, { rcases hs with ⟨x, xs⟩, rcases s_subset x xs with ⟨n, z, hnz⟩, exact false.elim z.2 }, { exact hT.coe_sort } }, inhabit (ℕ × T × ℕ), exact ⟨_, encodable.surjective_decode_iget _⟩ }, -- these sets `t q = K n z p` will do refine ⟨λ q, K (F q).1 (F q).2.1 (F q).2.2, λ q, f' (F q).2.1, λ n, K_closed _ _ _, λ x xs, _, λ q, K_approx _ _ _, λ h's q, ⟨(F q).2.1, (F q).2.1.1.2, rfl⟩⟩, -- the only fact that needs further checking is that they cover `s`. -- we already know that any point `x ∈ s` belongs to a set `M n z`. obtain ⟨n, z, hnz⟩ : ∃ (n : ℕ) (z : T), x ∈ M n z := s_subset x xs, -- by density, it also belongs to a ball `closed_ball (d p) (u n / 3)`. obtain ⟨p, hp⟩ : ∃ (p : ℕ), x ∈ closed_ball (d p) (u n / 3), { have : set.nonempty (ball x (u n / 3)), { simp only [nonempty_ball], linarith [u_pos n] }, obtain ⟨p, hp⟩ : ∃ (p : ℕ), d p ∈ ball x (u n / 3) := hd.exists_mem_open is_open_ball this, exact ⟨p, (mem_ball'.1 hp).le⟩ }, -- choose `q` for which `t q = K n z p`. obtain ⟨q, hq⟩ : ∃ q, F q = (n, z, p) := hF _, -- then `x` belongs to `t q`. apply mem_Union.2 ⟨q, _⟩, simp only [hq, subset_closure hnz, hp, mem_inter_iff, and_self], end variables [measurable_space E] [borel_space E] (μ : measure E) [is_add_haar_measure μ] /-- Assume that a function `f` has a derivative at every point of a set `s`. Then one may partition `s` into countably many disjoint relatively measurable sets (i.e., intersections of `s` with measurable sets `t n`) on which `f` is well approximated by linear maps `A n`. -/ lemma exists_partition_approximates_linear_on_of_has_fderiv_within_at [second_countable_topology F] (f : E → F) (s : set E) (f' : E → E →L[ℝ] F) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (r : (E →L[ℝ] F) → ℝ≥0) (rpos : ∀ A, r A ≠ 0) : ∃ (t : ℕ → set E) (A : ℕ → (E →L[ℝ] F)), pairwise (disjoint on t) ∧ (∀ n, measurable_set (t n)) ∧ (s ⊆ ⋃ n, t n) ∧ (∀ n, approximates_linear_on f (A n) (s ∩ t n) (r (A n))) ∧ (s.nonempty → ∀ n, ∃ y ∈ s, A n = f' y) := begin rcases exists_closed_cover_approximates_linear_on_of_has_fderiv_within_at f s f' hf' r rpos with ⟨t, A, t_closed, st, t_approx, ht⟩, refine ⟨disjointed t, A, disjoint_disjointed _, measurable_set.disjointed (λ n, (t_closed n).measurable_set), _, _, ht⟩, { rw Union_disjointed, exact st }, { assume n, exact (t_approx n).mono_set (inter_subset_inter_right _ (disjointed_subset _ _)) }, end namespace measure_theory /-! ### Local lemmas We check that a function which is well enough approximated by a linear map expands the volume essentially like this linear map, and that its derivative (if it exists) is almost everywhere close to the approximating linear map. -/ /-- Let `f` be a function which is sufficiently close (in the Lipschitz sense) to a given linear map `A`. Then it expands the volume of any set by at most `m` for any `m > det A`. -/ lemma add_haar_image_le_mul_of_det_lt (A : E →L[ℝ] E) {m : ℝ≥0} (hm : ennreal.of_real (|A.det|) < m) : ∀ᶠ δ in 𝓝[>] (0 : ℝ≥0), ∀ (s : set E) (f : E → E) (hf : approximates_linear_on f A s δ), μ (f '' s) ≤ m * μ s := begin apply nhds_within_le_nhds, let d := ennreal.of_real (|A.det|), -- construct a small neighborhood of `A '' (closed_ball 0 1)` with measure comparable to -- the determinant of `A`. obtain ⟨ε, hε, εpos⟩ : ∃ (ε : ℝ), μ (closed_ball 0 ε + A '' (closed_ball 0 1)) < m * μ (closed_ball 0 1) ∧ 0 < ε, { have HC : is_compact (A '' closed_ball 0 1) := (proper_space.is_compact_closed_ball _ _).image A.continuous, have L0 : tendsto (λ ε, μ (cthickening ε (A '' (closed_ball 0 1)))) (𝓝[>] 0) (𝓝 (μ (A '' (closed_ball 0 1)))), { apply tendsto.mono_left _ nhds_within_le_nhds, exact tendsto_measure_cthickening_of_is_compact HC }, have L1 : tendsto (λ ε, μ (closed_ball 0 ε + A '' (closed_ball 0 1))) (𝓝[>] 0) (𝓝 (μ (A '' (closed_ball 0 1)))), { apply L0.congr' _, filter_upwards [self_mem_nhds_within] with r hr, rw [←HC.add_closed_ball_zero (le_of_lt hr), add_comm] }, have L2 : tendsto (λ ε, μ (closed_ball 0 ε + A '' (closed_ball 0 1))) (𝓝[>] 0) (𝓝 (d * μ (closed_ball 0 1))), { convert L1, exact (add_haar_image_continuous_linear_map _ _ _).symm }, have I : d * μ (closed_ball 0 1) < m * μ (closed_ball 0 1) := (ennreal.mul_lt_mul_right ((measure_closed_ball_pos μ _ zero_lt_one).ne') measure_closed_ball_lt_top.ne).2 hm, have H : ∀ᶠ (b : ℝ) in 𝓝[>] 0, μ (closed_ball 0 b + A '' closed_ball 0 1) < m * μ (closed_ball 0 1) := (tendsto_order.1 L2).2 _ I, exact (H.and self_mem_nhds_within).exists }, have : Iio (⟨ε, εpos.le⟩ : ℝ≥0) ∈ 𝓝 (0 : ℝ≥0), { apply Iio_mem_nhds, exact εpos }, filter_upwards [this], -- fix a function `f` which is close enough to `A`. assume δ hδ s f hf, -- This function expands the volume of any ball by at most `m` have I : ∀ x r, x ∈ s → 0 ≤ r → μ (f '' (s ∩ closed_ball x r)) ≤ m * μ (closed_ball x r), { assume x r xs r0, have K : f '' (s ∩ closed_ball x r) ⊆ A '' (closed_ball 0 r) + closed_ball (f x) (ε * r), { rintros y ⟨z, ⟨zs, zr⟩, rfl⟩, apply set.mem_add.2 ⟨A (z - x), f z - f x - A (z - x) + f x, _, _, _⟩, { apply mem_image_of_mem, simpa only [dist_eq_norm, mem_closed_ball, mem_closed_ball_zero_iff] using zr }, { rw [mem_closed_ball_iff_norm, add_sub_cancel], calc ‖f z - f x - A (z - x)‖ ≤ δ * ‖z - x‖ : hf _ zs _ xs ... ≤ ε * r : mul_le_mul (le_of_lt hδ) (mem_closed_ball_iff_norm.1 zr) (norm_nonneg _) εpos.le }, { simp only [map_sub, pi.sub_apply], abel } }, have : A '' (closed_ball 0 r) + closed_ball (f x) (ε * r) = {f x} + r • (A '' (closed_ball 0 1) + closed_ball 0 ε), by rw [smul_add, ← add_assoc, add_comm ({f x}), add_assoc, smul_closed_ball _ _ εpos.le, smul_zero, singleton_add_closed_ball_zero, ← image_smul_set ℝ E E A, smul_closed_ball _ _ zero_le_one, smul_zero, real.norm_eq_abs, abs_of_nonneg r0, mul_one, mul_comm], rw this at K, calc μ (f '' (s ∩ closed_ball x r)) ≤ μ ({f x} + r • (A '' (closed_ball 0 1) + closed_ball 0 ε)) : measure_mono K ... = ennreal.of_real (r ^ finrank ℝ E) * μ (A '' closed_ball 0 1 + closed_ball 0 ε) : by simp only [abs_of_nonneg r0, add_haar_smul, image_add_left, abs_pow, singleton_add, measure_preimage_add] ... ≤ ennreal.of_real (r ^ finrank ℝ E) * (m * μ (closed_ball 0 1)) : by { rw add_comm, exact ennreal.mul_le_mul le_rfl hε.le } ... = m * μ (closed_ball x r) : by { simp only [add_haar_closed_ball' _ _ r0], ring } }, -- covering `s` by closed balls with total measure very close to `μ s`, one deduces that the -- measure of `f '' s` is at most `m * (μ s + a)` for any positive `a`. have J : ∀ᶠ a in 𝓝[>] (0 : ℝ≥0∞), μ (f '' s) ≤ m * (μ s + a), { filter_upwards [self_mem_nhds_within] with a ha, change 0 < a at ha, obtain ⟨t, r, t_count, ts, rpos, st, μt⟩ : ∃ (t : set E) (r : E → ℝ), t.countable ∧ t ⊆ s ∧ (∀ (x : E), x ∈ t → 0 < r x) ∧ (s ⊆ ⋃ (x ∈ t), closed_ball x (r x)) ∧ ∑' (x : ↥t), μ (closed_ball ↑x (r ↑x)) ≤ μ s + a := besicovitch.exists_closed_ball_covering_tsum_measure_le μ ha.ne' (λ x, Ioi 0) s (λ x xs δ δpos, ⟨δ/2, by simp [half_pos δpos, half_lt_self δpos]⟩), haveI : encodable t := t_count.to_encodable, calc μ (f '' s) ≤ μ (⋃ (x : t), f '' (s ∩ closed_ball x (r x))) : begin rw bUnion_eq_Union at st, apply measure_mono, rw [← image_Union, ← inter_Union], exact image_subset _ (subset_inter (subset.refl _) st) end ... ≤ ∑' (x : t), μ (f '' (s ∩ closed_ball x (r x))) : measure_Union_le _ ... ≤ ∑' (x : t), m * μ (closed_ball x (r x)) : ennreal.tsum_le_tsum (λ x, I x (r x) (ts x.2) (rpos x x.2).le) ... ≤ m * (μ s + a) : by { rw ennreal.tsum_mul_left, exact ennreal.mul_le_mul le_rfl μt } }, -- taking the limit in `a`, one obtains the conclusion have L : tendsto (λ a, (m : ℝ≥0∞) * (μ s + a)) (𝓝[>] 0) (𝓝 (m * (μ s + 0))), { apply tendsto.mono_left _ nhds_within_le_nhds, apply ennreal.tendsto.const_mul (tendsto_const_nhds.add tendsto_id), simp only [ennreal.coe_ne_top, ne.def, or_true, not_false_iff] }, rw add_zero at L, exact ge_of_tendsto L J, end /-- Let `f` be a function which is sufficiently close (in the Lipschitz sense) to a given linear map `A`. Then it expands the volume of any set by at least `m` for any `m < det A`. -/ lemma mul_le_add_haar_image_of_lt_det (A : E →L[ℝ] E) {m : ℝ≥0} (hm : (m : ℝ≥0∞) < ennreal.of_real (|A.det|)) : ∀ᶠ δ in 𝓝[>] (0 : ℝ≥0), ∀ (s : set E) (f : E → E) (hf : approximates_linear_on f A s δ), (m : ℝ≥0∞) * μ s ≤ μ (f '' s) := begin apply nhds_within_le_nhds, -- The assumption `hm` implies that `A` is invertible. If `f` is close enough to `A`, it is also -- invertible. One can then pass to the inverses, and deduce the estimate from -- `add_haar_image_le_mul_of_det_lt` applied to `f⁻¹` and `A⁻¹`. -- exclude first the trivial case where `m = 0`. rcases eq_or_lt_of_le (zero_le m) with rfl|mpos, { apply eventually_of_forall, simp only [forall_const, zero_mul, implies_true_iff, zero_le, ennreal.coe_zero] }, have hA : A.det ≠ 0, { assume h, simpa only [h, ennreal.not_lt_zero, ennreal.of_real_zero, abs_zero] using hm }, -- let `B` be the continuous linear equiv version of `A`. let B := A.to_continuous_linear_equiv_of_det_ne_zero hA, -- the determinant of `B.symm` is bounded by `m⁻¹` have I : ennreal.of_real (|(B.symm : E →L[ℝ] E).det|) < (m⁻¹ : ℝ≥0), { simp only [ennreal.of_real, abs_inv, real.to_nnreal_inv, continuous_linear_equiv.det_coe_symm, continuous_linear_map.coe_to_continuous_linear_equiv_of_det_ne_zero, ennreal.coe_lt_coe] at ⊢ hm, exact nnreal.inv_lt_inv mpos.ne' hm }, -- therefore, we may apply `add_haar_image_le_mul_of_det_lt` to `B.symm` and `m⁻¹`. obtain ⟨δ₀, δ₀pos, hδ₀⟩ : ∃ (δ : ℝ≥0), 0 < δ ∧ ∀ (t : set E) (g : E → E), approximates_linear_on g (B.symm : E →L[ℝ] E) t δ → μ (g '' t) ≤ ↑m⁻¹ * μ t, { have : ∀ᶠ (δ : ℝ≥0) in 𝓝[>] 0, ∀ (t : set E) (g : E → E), approximates_linear_on g (B.symm : E →L[ℝ] E) t δ → μ (g '' t) ≤ ↑m⁻¹ * μ t := add_haar_image_le_mul_of_det_lt μ B.symm I, rcases (this.and self_mem_nhds_within).exists with ⟨δ₀, h, h'⟩, exact ⟨δ₀, h', h⟩, }, -- record smallness conditions for `δ` that will be needed to apply `hδ₀` below. have L1 : ∀ᶠ δ in 𝓝 (0 : ℝ≥0), subsingleton E ∨ δ < ‖(B.symm : E →L[ℝ] E)‖₊⁻¹, { by_cases (subsingleton E), { simp only [h, true_or, eventually_const] }, simp only [h, false_or], apply Iio_mem_nhds, simpa only [h, false_or, nnreal.inv_pos] using B.subsingleton_or_nnnorm_symm_pos }, have L2 : ∀ᶠ δ in 𝓝 (0 : ℝ≥0), ‖(B.symm : E →L[ℝ] E)‖₊ * (‖(B.symm : E →L[ℝ] E)‖₊⁻¹ - δ)⁻¹ * δ < δ₀, { have : tendsto (λ δ, ‖(B.symm : E →L[ℝ] E)‖₊ * (‖(B.symm : E →L[ℝ] E)‖₊⁻¹ - δ)⁻¹ * δ) (𝓝 0) (𝓝 (‖(B.symm : E →L[ℝ] E)‖₊ * (‖(B.symm : E →L[ℝ] E)‖₊⁻¹ - 0)⁻¹ * 0)), { rcases eq_or_ne (‖(B.symm : E →L[ℝ] E)‖₊) 0 with H|H, { simpa only [H, zero_mul] using tendsto_const_nhds }, refine tendsto.mul (tendsto_const_nhds.mul _) tendsto_id, refine (tendsto.sub tendsto_const_nhds tendsto_id).inv₀ _, simpa only [tsub_zero, inv_eq_zero, ne.def] using H }, simp only [mul_zero] at this, exact (tendsto_order.1 this).2 δ₀ δ₀pos }, -- let `δ` be small enough, and `f` approximated by `B` up to `δ`. filter_upwards [L1, L2], assume δ h1δ h2δ s f hf, have hf' : approximates_linear_on f (B : E →L[ℝ] E) s δ, by { convert hf, exact A.coe_to_continuous_linear_equiv_of_det_ne_zero _ }, let F := hf'.to_local_equiv h1δ, -- the condition to be checked can be reformulated in terms of the inverse maps suffices H : μ ((F.symm) '' F.target) ≤ (m⁻¹ : ℝ≥0) * μ F.target, { change (m : ℝ≥0∞) * μ (F.source) ≤ μ (F.target), rwa [← F.symm_image_target_eq_source, mul_comm, ← ennreal.le_div_iff_mul_le, div_eq_mul_inv, mul_comm, ← ennreal.coe_inv (mpos.ne')], { apply or.inl, simpa only [ennreal.coe_eq_zero, ne.def] using mpos.ne'}, { simp only [ennreal.coe_ne_top, true_or, ne.def, not_false_iff] } }, -- as `f⁻¹` is well approximated by `B⁻¹`, the conclusion follows from `hδ₀` -- and our choice of `δ`. exact hδ₀ _ _ ((hf'.to_inv h1δ).mono_num h2δ.le), end /-- If a differentiable function `f` is approximated by a linear map `A` on a set `s`, up to `δ`, then at almost every `x` in `s` one has `‖f' x - A‖ ≤ δ`. -/ lemma _root_.approximates_linear_on.norm_fderiv_sub_le {A : E →L[ℝ] E} {δ : ℝ≥0} (hf : approximates_linear_on f A s δ) (hs : measurable_set s) (f' : E → E →L[ℝ] E) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) : ∀ᵐ x ∂(μ.restrict s), ‖f' x - A‖₊ ≤ δ := begin /- The conclusion will hold at the Lebesgue density points of `s` (which have full measure). At such a point `x`, for any `z` and any `ε > 0` one has for small `r` that `{x} + r • closed_ball z ε` intersects `s`. At a point `y` in the intersection, `f y - f x` is close both to `f' x (r z)` (by differentiability) and to `A (r z)` (by linear approximation), so these two quantities are close, i.e., `(f' x - A) z` is small. -/ filter_upwards [besicovitch.ae_tendsto_measure_inter_div μ s, ae_restrict_mem hs], -- start from a Lebesgue density point `x`, belonging to `s`. assume x hx xs, -- consider an arbitrary vector `z`. apply continuous_linear_map.op_norm_le_bound _ δ.2 (λ z, _), -- to show that `‖(f' x - A) z‖ ≤ δ ‖z‖`, it suffices to do it up to some error that vanishes -- asymptotically in terms of `ε > 0`. suffices H : ∀ ε, 0 < ε → ‖(f' x - A) z‖ ≤ (δ + ε) * (‖z‖ + ε) + ‖(f' x - A)‖ * ε, { have : tendsto (λ (ε : ℝ), ((δ : ℝ) + ε) * (‖z‖ + ε) + ‖(f' x - A)‖ * ε) (𝓝[>] 0) (𝓝 ((δ + 0) * (‖z‖ + 0) + ‖(f' x - A)‖ * 0)) := tendsto.mono_left (continuous.tendsto (by continuity) 0) nhds_within_le_nhds, simp only [add_zero, mul_zero] at this, apply le_of_tendsto_of_tendsto tendsto_const_nhds this, filter_upwards [self_mem_nhds_within], exact H }, -- fix a positive `ε`. assume ε εpos, -- for small enough `r`, the rescaled ball `r • closed_ball z ε` intersects `s`, as `x` is a -- density point have B₁ : ∀ᶠ r in 𝓝[>] (0 : ℝ), (s ∩ ({x} + r • closed_ball z ε)).nonempty := eventually_nonempty_inter_smul_of_density_one μ s x hx _ measurable_set_closed_ball (measure_closed_ball_pos μ z εpos).ne', obtain ⟨ρ, ρpos, hρ⟩ : ∃ ρ > 0, ball x ρ ∩ s ⊆ {y : E | ‖f y - f x - (f' x) (y - x)‖ ≤ ε * ‖y - x‖} := mem_nhds_within_iff.1 (is_o.def (hf' x xs) εpos), -- for small enough `r`, the rescaled ball `r • closed_ball z ε` is included in the set where -- `f y - f x` is well approximated by `f' x (y - x)`. have B₂ : ∀ᶠ r in 𝓝[>] (0 : ℝ), {x} + r • closed_ball z ε ⊆ ball x ρ := nhds_within_le_nhds (eventually_singleton_add_smul_subset bounded_closed_ball (ball_mem_nhds x ρpos)), -- fix a small positive `r` satisfying the above properties, as well as a corresponding `y`. obtain ⟨r, ⟨y, ⟨ys, hy⟩⟩, rρ, rpos⟩ : ∃ (r : ℝ), (s ∩ ({x} + r • closed_ball z ε)).nonempty ∧ {x} + r • closed_ball z ε ⊆ ball x ρ ∧ 0 < r := (B₁.and (B₂.and self_mem_nhds_within)).exists, -- write `y = x + r a` with `a ∈ closed_ball z ε`. obtain ⟨a, az, ya⟩ : ∃ a, a ∈ closed_ball z ε ∧ y = x + r • a, { simp only [mem_smul_set, image_add_left, mem_preimage, singleton_add] at hy, rcases hy with ⟨a, az, ha⟩, exact ⟨a, az, by simp only [ha, add_neg_cancel_left]⟩ }, have norm_a : ‖a‖ ≤ ‖z‖ + ε := calc ‖a‖ = ‖z + (a - z)‖ : by simp only [add_sub_cancel'_right] ... ≤ ‖z‖ + ‖a - z‖ : norm_add_le _ _ ... ≤ ‖z‖ + ε : add_le_add_left (mem_closed_ball_iff_norm.1 az) _, -- use the approximation properties to control `(f' x - A) a`, and then `(f' x - A) z` as `z` is -- close to `a`. have I : r * ‖(f' x - A) a‖ ≤ r * (δ + ε) * (‖z‖ + ε) := calc r * ‖(f' x - A) a‖ = ‖(f' x - A) (r • a)‖ : by simp only [continuous_linear_map.map_smul, norm_smul, real.norm_eq_abs, abs_of_nonneg rpos.le] ... = ‖(f y - f x - A (y - x)) - (f y - f x - (f' x) (y - x))‖ : begin congr' 1, simp only [ya, add_sub_cancel', sub_sub_sub_cancel_left, continuous_linear_map.coe_sub', eq_self_iff_true, sub_left_inj, pi.sub_apply, continuous_linear_map.map_smul, smul_sub], end ... ≤ ‖f y - f x - A (y - x)‖ + ‖f y - f x - (f' x) (y - x)‖ : norm_sub_le _ _ ... ≤ δ * ‖y - x‖ + ε * ‖y - x‖ : add_le_add (hf _ ys _ xs) (hρ ⟨rρ hy, ys⟩) ... = r * (δ + ε) * ‖a‖ : by { simp only [ya, add_sub_cancel', norm_smul, real.norm_eq_abs, abs_of_nonneg rpos.le], ring } ... ≤ r * (δ + ε) * (‖z‖ + ε) : mul_le_mul_of_nonneg_left norm_a (mul_nonneg rpos.le (add_nonneg δ.2 εpos.le)), show ‖(f' x - A) z‖ ≤ (δ + ε) * (‖z‖ + ε) + ‖(f' x - A)‖ * ε, from calc ‖(f' x - A) z‖ = ‖(f' x - A) a + (f' x - A) (z - a)‖ : begin congr' 1, simp only [continuous_linear_map.coe_sub', map_sub, pi.sub_apply], abel end ... ≤ ‖(f' x - A) a‖ + ‖(f' x - A) (z - a)‖ : norm_add_le _ _ ... ≤ (δ + ε) * (‖z‖ + ε) + ‖f' x - A‖ * ‖z - a‖ : begin apply add_le_add, { rw mul_assoc at I, exact (mul_le_mul_left rpos).1 I }, { apply continuous_linear_map.le_op_norm } end ... ≤ (δ + ε) * (‖z‖ + ε) + ‖f' x - A‖ * ε : add_le_add le_rfl (mul_le_mul_of_nonneg_left (mem_closed_ball_iff_norm'.1 az) (norm_nonneg _)), end /-! ### Measure zero of the image, over non-measurable sets If a set has measure `0`, then its image under a differentiable map has measure zero. This doesn't require the set to be measurable. In the same way, if `f` is differentiable on a set `s` with non-invertible derivative everywhere, then `f '' s` has measure `0`, again without measurability assumptions. -/ /-- A differentiable function maps sets of measure zero to sets of measure zero. -/ lemma add_haar_image_eq_zero_of_differentiable_on_of_add_haar_eq_zero (hf : differentiable_on ℝ f s) (hs : μ s = 0) : μ (f '' s) = 0 := begin refine le_antisymm _ (zero_le _), have : ∀ (A : E →L[ℝ] E), ∃ (δ : ℝ≥0), 0 < δ ∧ ∀ (t : set E) (hf : approximates_linear_on f A t δ), μ (f '' t) ≤ (real.to_nnreal (|A.det|) + 1 : ℝ≥0) * μ t, { assume A, let m : ℝ≥0 := real.to_nnreal ((|A.det|)) + 1, have I : ennreal.of_real (|A.det|) < m, by simp only [ennreal.of_real, m, lt_add_iff_pos_right, zero_lt_one, ennreal.coe_lt_coe], rcases ((add_haar_image_le_mul_of_det_lt μ A I).and self_mem_nhds_within).exists with ⟨δ, h, h'⟩, exact ⟨δ, h', λ t ht, h t f ht⟩ }, choose δ hδ using this, obtain ⟨t, A, t_disj, t_meas, t_cover, ht, -⟩ : ∃ (t : ℕ → set E) (A : ℕ → (E →L[ℝ] E)), pairwise (disjoint on t) ∧ (∀ (n : ℕ), measurable_set (t n)) ∧ (s ⊆ ⋃ (n : ℕ), t n) ∧ (∀ (n : ℕ), approximates_linear_on f (A n) (s ∩ t n) (δ (A n))) ∧ (s.nonempty → ∀ n, ∃ y ∈ s, A n = fderiv_within ℝ f s y) := exists_partition_approximates_linear_on_of_has_fderiv_within_at f s (fderiv_within ℝ f s) (λ x xs, (hf x xs).has_fderiv_within_at) δ (λ A, (hδ A).1.ne'), calc μ (f '' s) ≤ μ (⋃ n, f '' (s ∩ t n)) : begin apply measure_mono, rw [← image_Union, ← inter_Union], exact image_subset f (subset_inter subset.rfl t_cover) end ... ≤ ∑' n, μ (f '' (s ∩ t n)) : measure_Union_le _ ... ≤ ∑' n, (real.to_nnreal (|(A n).det|) + 1 : ℝ≥0) * μ (s ∩ t n) : begin apply ennreal.tsum_le_tsum (λ n, _), apply (hδ (A n)).2, exact ht n, end ... ≤ ∑' n, (real.to_nnreal (|(A n).det|) + 1 : ℝ≥0) * 0 : begin refine ennreal.tsum_le_tsum (λ n, ennreal.mul_le_mul le_rfl _), exact le_trans (measure_mono (inter_subset_left _ _)) (le_of_eq hs), end ... = 0 : by simp only [tsum_zero, mul_zero] end /-- A version of Sard lemma in fixed dimension: given a differentiable function from `E` to `E` and a set where the differential is not invertible, then the image of this set has zero measure. Here, we give an auxiliary statement towards this result. -/ lemma add_haar_image_eq_zero_of_det_fderiv_within_eq_zero_aux (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (R : ℝ) (hs : s ⊆ closed_ball 0 R) (ε : ℝ≥0) (εpos : 0 < ε) (h'f' : ∀ x ∈ s, (f' x).det = 0) : μ (f '' s) ≤ ε * μ (closed_ball 0 R) := begin rcases eq_empty_or_nonempty s with rfl|h's, { simp only [measure_empty, zero_le, image_empty] }, have : ∀ (A : E →L[ℝ] E), ∃ (δ : ℝ≥0), 0 < δ ∧ ∀ (t : set E) (hf : approximates_linear_on f A t δ), μ (f '' t) ≤ (real.to_nnreal (|A.det|) + ε : ℝ≥0) * μ t, { assume A, let m : ℝ≥0 := real.to_nnreal (|A.det|) + ε, have I : ennreal.of_real (|A.det|) < m, by simp only [ennreal.of_real, m, lt_add_iff_pos_right, εpos, ennreal.coe_lt_coe], rcases ((add_haar_image_le_mul_of_det_lt μ A I).and self_mem_nhds_within).exists with ⟨δ, h, h'⟩, exact ⟨δ, h', λ t ht, h t f ht⟩ }, choose δ hδ using this, obtain ⟨t, A, t_disj, t_meas, t_cover, ht, Af'⟩ : ∃ (t : ℕ → set E) (A : ℕ → (E →L[ℝ] E)), pairwise (disjoint on t) ∧ (∀ (n : ℕ), measurable_set (t n)) ∧ (s ⊆ ⋃ (n : ℕ), t n) ∧ (∀ (n : ℕ), approximates_linear_on f (A n) (s ∩ t n) (δ (A n))) ∧ (s.nonempty → ∀ n, ∃ y ∈ s, A n = f' y) := exists_partition_approximates_linear_on_of_has_fderiv_within_at f s f' hf' δ (λ A, (hδ A).1.ne'), calc μ (f '' s) ≤ μ (⋃ n, f '' (s ∩ t n)) : begin apply measure_mono, rw [← image_Union, ← inter_Union], exact image_subset f (subset_inter subset.rfl t_cover) end ... ≤ ∑' n, μ (f '' (s ∩ t n)) : measure_Union_le _ ... ≤ ∑' n, (real.to_nnreal (|(A n).det|) + ε : ℝ≥0) * μ (s ∩ t n) : begin apply ennreal.tsum_le_tsum (λ n, _), apply (hδ (A n)).2, exact ht n, end ... = ∑' n, ε * μ (s ∩ t n) : begin congr' with n, rcases Af' h's n with ⟨y, ys, hy⟩, simp only [hy, h'f' y ys, real.to_nnreal_zero, abs_zero, zero_add] end ... ≤ ε * ∑' n, μ (closed_ball 0 R ∩ t n) : begin rw ennreal.tsum_mul_left, refine ennreal.mul_le_mul le_rfl (ennreal.tsum_le_tsum (λ n, measure_mono _)), exact inter_subset_inter_left _ hs, end ... = ε * μ (⋃ n, closed_ball 0 R ∩ t n) : begin rw measure_Union, { exact pairwise_disjoint.mono t_disj (λ n, inter_subset_right _ _) }, { assume n, exact measurable_set_closed_ball.inter (t_meas n) } end ... ≤ ε * μ (closed_ball 0 R) : begin rw ← inter_Union, exact ennreal.mul_le_mul le_rfl (measure_mono (inter_subset_left _ _)), end end /-- A version of Sard lemma in fixed dimension: given a differentiable function from `E` to `E` and a set where the differential is not invertible, then the image of this set has zero measure. -/ lemma add_haar_image_eq_zero_of_det_fderiv_within_eq_zero (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (h'f' : ∀ x ∈ s, (f' x).det = 0) : μ (f '' s) = 0 := begin suffices H : ∀ R, μ (f '' (s ∩ closed_ball 0 R)) = 0, { apply le_antisymm _ (zero_le _), rw ← Union_inter_closed_ball_nat s 0, calc μ (f '' ⋃ (n : ℕ), s ∩ closed_ball 0 n) ≤ ∑' (n : ℕ), μ (f '' (s ∩ closed_ball 0 n)) : by { rw image_Union, exact measure_Union_le _ } ... ≤ 0 : by simp only [H, tsum_zero, nonpos_iff_eq_zero] }, assume R, have A : ∀ (ε : ℝ≥0) (εpos : 0 < ε), μ (f '' (s ∩ closed_ball 0 R)) ≤ ε * μ (closed_ball 0 R) := λ ε εpos, add_haar_image_eq_zero_of_det_fderiv_within_eq_zero_aux μ (λ x hx, (hf' x hx.1).mono (inter_subset_left _ _)) R (inter_subset_right _ _) ε εpos (λ x hx, h'f' x hx.1), have B : tendsto (λ (ε : ℝ≥0), (ε : ℝ≥0∞) * μ (closed_ball 0 R)) (𝓝[>] 0) (𝓝 0), { have : tendsto (λ (ε : ℝ≥0), (ε : ℝ≥0∞) * μ (closed_ball 0 R)) (𝓝 0) (𝓝 (((0 : ℝ≥0) : ℝ≥0∞) * μ (closed_ball 0 R))) := ennreal.tendsto.mul_const (ennreal.tendsto_coe.2 tendsto_id) (or.inr ((measure_closed_ball_lt_top).ne)), simp only [zero_mul, ennreal.coe_zero] at this, exact tendsto.mono_left this nhds_within_le_nhds }, apply le_antisymm _ (zero_le _), apply ge_of_tendsto B, filter_upwards [self_mem_nhds_within], exact A, end /-! ### Weak measurability statements We show that the derivative of a function on a set is almost everywhere measurable, and that the image `f '' s` is measurable if `f` is injective on `s`. The latter statement follows from the Lusin-Souslin theorem. -/ /-- The derivative of a function on a measurable set is almost everywhere measurable on this set with respect to Lebesgue measure. Note that, in general, it is not genuinely measurable there, as `f'` is not unique (but only on a set of measure `0`, as the argument shows). -/ lemma ae_measurable_fderiv_within (hs : measurable_set s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) : ae_measurable f' (μ.restrict s) := begin /- It suffices to show that `f'` can be uniformly approximated by a measurable function. Fix `ε > 0`. Thanks to `exists_partition_approximates_linear_on_of_has_fderiv_within_at`, one can find a countable measurable partition of `s` into sets `s ∩ t n` on which `f` is well approximated by linear maps `A n`. On almost all of `s ∩ t n`, it follows from `approximates_linear_on.norm_fderiv_sub_le` that `f'` is uniformly approximated by `A n`, which gives the conclusion. -/ -- fix a precision `ε` refine ae_measurable_of_unif_approx (λ ε εpos, _), let δ : ℝ≥0 := ⟨ε, le_of_lt εpos⟩, have δpos : 0 < δ := εpos, -- partition `s` into sets `s ∩ t n` on which `f` is approximated by linear maps `A n`. obtain ⟨t, A, t_disj, t_meas, t_cover, ht, Af'⟩ : ∃ (t : ℕ → set E) (A : ℕ → (E →L[ℝ] E)), pairwise (disjoint on t) ∧ (∀ (n : ℕ), measurable_set (t n)) ∧ (s ⊆ ⋃ (n : ℕ), t n) ∧ (∀ (n : ℕ), approximates_linear_on f (A n) (s ∩ t n) δ) ∧ (s.nonempty → ∀ n, ∃ y ∈ s, A n = f' y) := exists_partition_approximates_linear_on_of_has_fderiv_within_at f s f' hf' (λ A, δ) (λ A, δpos.ne'), -- define a measurable function `g` which coincides with `A n` on `t n`. obtain ⟨g, g_meas, hg⟩ : ∃ g : E → (E →L[ℝ] E), measurable g ∧ ∀ (n : ℕ) (x : E), x ∈ t n → g x = A n := exists_measurable_piecewise_nat t t_meas t_disj (λ n x, A n) (λ n, measurable_const), refine ⟨g, g_meas.ae_measurable, _⟩, -- reduce to checking that `f'` and `g` are close on almost all of `s ∩ t n`, for all `n`. suffices H : ∀ᵐ (x : E) ∂(sum (λ n, μ.restrict (s ∩ t n))), dist (g x) (f' x) ≤ ε, { have : μ.restrict s ≤ sum (λ n, μ.restrict (s ∩ t n)), { have : s = ⋃ n, s ∩ t n, { rw ← inter_Union, exact subset.antisymm (subset_inter subset.rfl t_cover) (inter_subset_left _ _) }, conv_lhs { rw this }, exact restrict_Union_le }, exact ae_mono this H }, -- fix such an `n`. refine ae_sum_iff.2 (λ n, _), -- on almost all `s ∩ t n`, `f' x` is close to `A n` thanks to -- `approximates_linear_on.norm_fderiv_sub_le`. have E₁ : ∀ᵐ (x : E) ∂μ.restrict (s ∩ t n), ‖f' x - A n‖₊ ≤ δ := (ht n).norm_fderiv_sub_le μ (hs.inter (t_meas n)) f' (λ x hx, (hf' x hx.1).mono (inter_subset_left _ _)), -- moreover, `g x` is equal to `A n` there. have E₂ : ∀ᵐ (x : E) ∂μ.restrict (s ∩ t n), g x = A n, { suffices H : ∀ᵐ (x : E) ∂μ.restrict (t n), g x = A n, from ae_mono (restrict_mono (inter_subset_right _ _) le_rfl) H, filter_upwards [ae_restrict_mem (t_meas n)], exact hg n }, -- putting these two properties together gives the conclusion. filter_upwards [E₁, E₂] with x hx1 hx2, rw ← nndist_eq_nnnorm at hx1, rw [hx2, dist_comm], exact hx1, end lemma ae_measurable_of_real_abs_det_fderiv_within (hs : measurable_set s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) : ae_measurable (λ x, ennreal.of_real (|(f' x).det|)) (μ.restrict s) := begin apply ennreal.measurable_of_real.comp_ae_measurable, refine continuous_abs.measurable.comp_ae_measurable _, refine continuous_linear_map.continuous_det.measurable.comp_ae_measurable _, exact ae_measurable_fderiv_within μ hs hf' end lemma ae_measurable_to_nnreal_abs_det_fderiv_within (hs : measurable_set s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) : ae_measurable (λ x, |(f' x).det|.to_nnreal) (μ.restrict s) := begin apply measurable_real_to_nnreal.comp_ae_measurable, refine continuous_abs.measurable.comp_ae_measurable _, refine continuous_linear_map.continuous_det.measurable.comp_ae_measurable _, exact ae_measurable_fderiv_within μ hs hf' end /-- If a function is differentiable and injective on a measurable set, then the image is measurable.-/ lemma measurable_image_of_fderiv_within (hs : measurable_set s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (hf : inj_on f s) : measurable_set (f '' s) := begin have : differentiable_on ℝ f s := λ x hx, (hf' x hx).differentiable_within_at, exact hs.image_of_continuous_on_inj_on (differentiable_on.continuous_on this) hf, end /-- If a function is differentiable and injective on a measurable set `s`, then its restriction to `s` is a measurable embedding. -/ lemma measurable_embedding_of_fderiv_within (hs : measurable_set s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (hf : inj_on f s) : measurable_embedding (s.restrict f) := begin have : differentiable_on ℝ f s := λ x hx, (hf' x hx).differentiable_within_at, exact this.continuous_on.measurable_embedding hs hf end /-! ### Proving the estimate for the measure of the image We show the formula `∫⁻ x in s, ennreal.of_real (|(f' x).det|) ∂μ = μ (f '' s)`, in `lintegral_abs_det_fderiv_eq_add_haar_image`. For this, we show both inequalities in both directions, first up to controlled errors and then letting these errors tend to `0`. -/ lemma add_haar_image_le_lintegral_abs_det_fderiv_aux1 (hs : measurable_set s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) {ε : ℝ≥0} (εpos : 0 < ε) : μ (f '' s) ≤ ∫⁻ x in s, ennreal.of_real (|(f' x).det|) ∂μ + 2 * ε * μ s := begin /- To bound `μ (f '' s)`, we cover `s` by sets where `f` is well-approximated by linear maps `A n` (and where `f'` is almost everywhere close to `A n`), and then use that `f` expands the measure of such a set by at most `(A n).det + ε`. -/ have : ∀ (A : E →L[ℝ] E), ∃ (δ : ℝ≥0), 0 < δ ∧ (∀ (B : E →L[ℝ] E), ‖B - A‖ ≤ δ → |B.det - A.det| ≤ ε) ∧ ∀ (t : set E) (g : E → E) (hf : approximates_linear_on g A t δ), μ (g '' t) ≤ (ennreal.of_real (|A.det|) + ε) * μ t, { assume A, let m : ℝ≥0 := real.to_nnreal (|A.det|) + ε, have I : ennreal.of_real (|A.det|) < m, by simp only [ennreal.of_real, m, lt_add_iff_pos_right, εpos, ennreal.coe_lt_coe], rcases ((add_haar_image_le_mul_of_det_lt μ A I).and self_mem_nhds_within).exists with ⟨δ, h, δpos⟩, obtain ⟨δ', δ'pos, hδ'⟩ : ∃ (δ' : ℝ) (H : 0 < δ'), ∀ B, dist B A < δ' → dist B.det A.det < ↑ε := continuous_at_iff.1 continuous_linear_map.continuous_det.continuous_at ε εpos, let δ'' : ℝ≥0 := ⟨δ' / 2, (half_pos δ'pos).le⟩, refine ⟨min δ δ'', lt_min δpos (half_pos δ'pos), _, _⟩, { assume B hB, rw ← real.dist_eq, apply (hδ' B _).le, rw dist_eq_norm, calc ‖B - A‖ ≤ (min δ δ'' : ℝ≥0) : hB ... ≤ δ'' : by simp only [le_refl, nnreal.coe_min, min_le_iff, or_true] ... < δ' : half_lt_self δ'pos }, { assume t g htg, exact h t g (htg.mono_num (min_le_left _ _)) } }, choose δ hδ using this, obtain ⟨t, A, t_disj, t_meas, t_cover, ht, -⟩ : ∃ (t : ℕ → set E) (A : ℕ → (E →L[ℝ] E)), pairwise (disjoint on t) ∧ (∀ (n : ℕ), measurable_set (t n)) ∧ (s ⊆ ⋃ (n : ℕ), t n) ∧ (∀ (n : ℕ), approximates_linear_on f (A n) (s ∩ t n) (δ (A n))) ∧ (s.nonempty → ∀ n, ∃ y ∈ s, A n = f' y) := exists_partition_approximates_linear_on_of_has_fderiv_within_at f s f' hf' δ (λ A, (hδ A).1.ne'), calc μ (f '' s) ≤ μ (⋃ n, f '' (s ∩ t n)) : begin apply measure_mono, rw [← image_Union, ← inter_Union], exact image_subset f (subset_inter subset.rfl t_cover) end ... ≤ ∑' n, μ (f '' (s ∩ t n)) : measure_Union_le _ ... ≤ ∑' n, (ennreal.of_real (|(A n).det|) + ε) * μ (s ∩ t n) : begin apply ennreal.tsum_le_tsum (λ n, _), apply (hδ (A n)).2.2, exact ht n, end ... = ∑' n, ∫⁻ x in s ∩ t n, ennreal.of_real (|(A n).det|) + ε ∂μ : by simp only [lintegral_const, measurable_set.univ, measure.restrict_apply, univ_inter] ... ≤ ∑' n, ∫⁻ x in s ∩ t n, ennreal.of_real (|(f' x).det|) + 2 * ε ∂μ : begin apply ennreal.tsum_le_tsum (λ n, _), apply lintegral_mono_ae, filter_upwards [(ht n).norm_fderiv_sub_le μ (hs.inter (t_meas n)) f' (λ x hx, (hf' x hx.1).mono (inter_subset_left _ _))], assume x hx, have I : |(A n).det| ≤ |(f' x).det| + ε := calc |(A n).det| = |(f' x).det - ((f' x).det - (A n).det)| : by { congr' 1, abel } ... ≤ |(f' x).det| + |(f' x).det - (A n).det| : abs_sub _ _ ... ≤ |(f' x).det| + ε : add_le_add le_rfl ((hδ (A n)).2.1 _ hx), calc ennreal.of_real (|(A n).det|) + ε ≤ ennreal.of_real (|(f' x).det| + ε) + ε : add_le_add (ennreal.of_real_le_of_real I) le_rfl ... = ennreal.of_real (|(f' x).det|) + 2 * ε : by simp only [ennreal.of_real_add, abs_nonneg, two_mul, add_assoc, nnreal.zero_le_coe, ennreal.of_real_coe_nnreal], end ... = ∫⁻ x in ⋃ n, s ∩ t n, ennreal.of_real (|(f' x).det|) + 2 * ε ∂μ : begin have M : ∀ (n : ℕ), measurable_set (s ∩ t n) := λ n, hs.inter (t_meas n), rw lintegral_Union M, exact pairwise_disjoint.mono t_disj (λ n, inter_subset_right _ _), end ... = ∫⁻ x in s, ennreal.of_real (|(f' x).det|) + 2 * ε ∂μ : begin have : s = ⋃ n, s ∩ t n, { rw ← inter_Union, exact subset.antisymm (subset_inter subset.rfl t_cover) (inter_subset_left _ _) }, rw ← this, end ... = ∫⁻ x in s, ennreal.of_real (|(f' x).det|) ∂μ + 2 * ε * μ s : by simp only [lintegral_add_right' _ ae_measurable_const, set_lintegral_const] end lemma add_haar_image_le_lintegral_abs_det_fderiv_aux2 (hs : measurable_set s) (h's : μ s ≠ ∞) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) : μ (f '' s) ≤ ∫⁻ x in s, ennreal.of_real (|(f' x).det|) ∂μ := begin /- We just need to let the error tend to `0` in the previous lemma. -/ have : tendsto (λ (ε : ℝ≥0), ∫⁻ x in s, ennreal.of_real (|(f' x).det|) ∂μ + 2 * ε * μ s) (𝓝[>] 0) (𝓝 (∫⁻ x in s, ennreal.of_real (|(f' x).det|) ∂μ + 2 * (0 : ℝ≥0) * μ s)), { apply tendsto.mono_left _ nhds_within_le_nhds, refine tendsto_const_nhds.add _, refine ennreal.tendsto.mul_const _ (or.inr h's), exact ennreal.tendsto.const_mul (ennreal.tendsto_coe.2 tendsto_id) (or.inr ennreal.coe_ne_top) }, simp only [add_zero, zero_mul, mul_zero, ennreal.coe_zero] at this, apply ge_of_tendsto this, filter_upwards [self_mem_nhds_within], rintros ε (εpos : 0 < ε), exact add_haar_image_le_lintegral_abs_det_fderiv_aux1 μ hs hf' εpos, end lemma add_haar_image_le_lintegral_abs_det_fderiv (hs : measurable_set s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) : μ (f '' s) ≤ ∫⁻ x in s, ennreal.of_real (|(f' x).det|) ∂μ := begin /- We already know the result for finite-measure sets. We cover `s` by finite-measure sets using `spanning_sets μ`, and apply the previous result to each of these parts. -/ let u := λ n, disjointed (spanning_sets μ) n, have u_meas : ∀ n, measurable_set (u n), { assume n, apply measurable_set.disjointed (λ i, _), exact measurable_spanning_sets μ i }, have A : s = ⋃ n, s ∩ u n, by rw [← inter_Union, Union_disjointed, Union_spanning_sets, inter_univ], calc μ (f '' s) ≤ ∑' n, μ (f '' (s ∩ u n)) : begin conv_lhs { rw [A, image_Union] }, exact measure_Union_le _, end ... ≤ ∑' n, ∫⁻ x in s ∩ u n, ennreal.of_real (|(f' x).det|) ∂μ : begin apply ennreal.tsum_le_tsum (λ n, _), apply add_haar_image_le_lintegral_abs_det_fderiv_aux2 μ (hs.inter (u_meas n)) _ (λ x hx, (hf' x hx.1).mono (inter_subset_left _ _)), have : μ (u n) < ∞ := lt_of_le_of_lt (measure_mono (disjointed_subset _ _)) (measure_spanning_sets_lt_top μ n), exact ne_of_lt (lt_of_le_of_lt (measure_mono (inter_subset_right _ _)) this), end ... = ∫⁻ x in s, ennreal.of_real (|(f' x).det|) ∂μ : begin conv_rhs { rw A }, rw lintegral_Union, { assume n, exact hs.inter (u_meas n) }, { exact pairwise_disjoint.mono (disjoint_disjointed _) (λ n, inter_subset_right _ _) } end end lemma lintegral_abs_det_fderiv_le_add_haar_image_aux1 (hs : measurable_set s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (hf : inj_on f s) {ε : ℝ≥0} (εpos : 0 < ε) : ∫⁻ x in s, ennreal.of_real (|(f' x).det|) ∂μ ≤ μ (f '' s) + 2 * ε * μ s := begin /- To bound `∫⁻ x in s, ennreal.of_real (|(f' x).det|) ∂μ`, we cover `s` by sets where `f` is well-approximated by linear maps `A n` (and where `f'` is almost everywhere close to `A n`), and then use that `f` expands the measure of such a set by at least `(A n).det - ε`. -/ have : ∀ (A : E →L[ℝ] E), ∃ (δ : ℝ≥0), 0 < δ ∧ (∀ (B : E →L[ℝ] E), ‖B - A‖ ≤ δ → |B.det - A.det| ≤ ε) ∧ ∀ (t : set E) (g : E → E) (hf : approximates_linear_on g A t δ), ennreal.of_real (|A.det|) * μ t ≤ μ (g '' t) + ε * μ t, { assume A, obtain ⟨δ', δ'pos, hδ'⟩ : ∃ (δ' : ℝ) (H : 0 < δ'), ∀ B, dist B A < δ' → dist B.det A.det < ↑ε := continuous_at_iff.1 continuous_linear_map.continuous_det.continuous_at ε εpos, let δ'' : ℝ≥0 := ⟨δ' / 2, (half_pos δ'pos).le⟩, have I'' : ∀ (B : E →L[ℝ] E), ‖B - A‖ ≤ ↑δ'' → |B.det - A.det| ≤ ↑ε, { assume B hB, rw ← real.dist_eq, apply (hδ' B _).le, rw dist_eq_norm, exact hB.trans_lt (half_lt_self δ'pos) }, rcases eq_or_ne A.det 0 with hA|hA, { refine ⟨δ'', half_pos δ'pos, I'', _⟩, simp only [hA, forall_const, zero_mul, ennreal.of_real_zero, implies_true_iff, zero_le, abs_zero] }, let m : ℝ≥0 := real.to_nnreal (|A.det|) - ε, have I : (m : ℝ≥0∞) < ennreal.of_real (|A.det|), { simp only [ennreal.of_real, with_top.coe_sub], apply ennreal.sub_lt_self ennreal.coe_ne_top, { simpa only [abs_nonpos_iff, real.to_nnreal_eq_zero, ennreal.coe_eq_zero, ne.def] using hA }, { simp only [εpos.ne', ennreal.coe_eq_zero, ne.def, not_false_iff] } }, rcases ((mul_le_add_haar_image_of_lt_det μ A I).and self_mem_nhds_within).exists with ⟨δ, h, δpos⟩, refine ⟨min δ δ'', lt_min δpos (half_pos δ'pos), _, _⟩, { assume B hB, apply I'' _ (hB.trans _), simp only [le_refl, nnreal.coe_min, min_le_iff, or_true] }, { assume t g htg, rcases eq_or_ne (μ t) ∞ with ht|ht, { simp only [ht, εpos.ne', with_top.mul_top, ennreal.coe_eq_zero, le_top, ne.def, not_false_iff, ennreal.add_top] }, have := h t g (htg.mono_num (min_le_left _ _)), rwa [with_top.coe_sub, ennreal.sub_mul, tsub_le_iff_right] at this, simp only [ht, implies_true_iff, ne.def, not_false_iff] } }, choose δ hδ using this, obtain ⟨t, A, t_disj, t_meas, t_cover, ht, -⟩ : ∃ (t : ℕ → set E) (A : ℕ → (E →L[ℝ] E)), pairwise (disjoint on t) ∧ (∀ (n : ℕ), measurable_set (t n)) ∧ (s ⊆ ⋃ (n : ℕ), t n) ∧ (∀ (n : ℕ), approximates_linear_on f (A n) (s ∩ t n) (δ (A n))) ∧ (s.nonempty → ∀ n, ∃ y ∈ s, A n = f' y) := exists_partition_approximates_linear_on_of_has_fderiv_within_at f s f' hf' δ (λ A, (hδ A).1.ne'), have s_eq : s = ⋃ n, s ∩ t n, { rw ← inter_Union, exact subset.antisymm (subset_inter subset.rfl t_cover) (inter_subset_left _ _) }, calc ∫⁻ x in s, ennreal.of_real (|(f' x).det|) ∂μ = ∑' n, ∫⁻ x in s ∩ t n, ennreal.of_real (|(f' x).det|) ∂μ : begin conv_lhs { rw s_eq }, rw lintegral_Union, { exact λ n, hs.inter (t_meas n) }, { exact pairwise_disjoint.mono t_disj (λ n, inter_subset_right _ _) } end ... ≤ ∑' n, ∫⁻ x in s ∩ t n, ennreal.of_real (|(A n).det|) + ε ∂μ : begin apply ennreal.tsum_le_tsum (λ n, _), apply lintegral_mono_ae, filter_upwards [(ht n).norm_fderiv_sub_le μ (hs.inter (t_meas n)) f' (λ x hx, (hf' x hx.1).mono (inter_subset_left _ _))], assume x hx, have I : |(f' x).det| ≤ |(A n).det| + ε := calc |(f' x).det| = |(A n).det + ((f' x).det - (A n).det)| : by { congr' 1, abel } ... ≤ |(A n).det| + |(f' x).det - (A n).det| : abs_add _ _ ... ≤ |(A n).det| + ε : add_le_add le_rfl ((hδ (A n)).2.1 _ hx), calc ennreal.of_real (|(f' x).det|) ≤ ennreal.of_real (|(A n).det| + ε) : ennreal.of_real_le_of_real I ... = ennreal.of_real (|(A n).det|) + ε : by simp only [ennreal.of_real_add, abs_nonneg, nnreal.zero_le_coe, ennreal.of_real_coe_nnreal] end ... = ∑' n, (ennreal.of_real (|(A n).det|) * μ (s ∩ t n) + ε * μ (s ∩ t n)) : by simp only [set_lintegral_const, lintegral_add_right _ measurable_const] ... ≤ ∑' n, ((μ (f '' (s ∩ t n)) + ε * μ (s ∩ t n)) + ε * μ (s ∩ t n)) : begin refine ennreal.tsum_le_tsum (λ n, add_le_add_right _ _), exact (hδ (A n)).2.2 _ _ (ht n), end ... = μ (f '' s) + 2 * ε * μ s : begin conv_rhs { rw s_eq }, rw [image_Union, measure_Union], rotate, { assume i j hij, apply (disjoint.image _ hf (inter_subset_left _ _) (inter_subset_left _ _)), exact disjoint.mono (inter_subset_right _ _) (inter_subset_right _ _) (t_disj hij) }, { assume i, exact measurable_image_of_fderiv_within (hs.inter (t_meas i)) (λ x hx, (hf' x hx.1).mono (inter_subset_left _ _)) (hf.mono (inter_subset_left _ _)) }, rw measure_Union, rotate, { exact pairwise_disjoint.mono t_disj (λ i, inter_subset_right _ _) }, { exact λ i, hs.inter (t_meas i) }, rw [← ennreal.tsum_mul_left, ← ennreal.tsum_add], congr' 1, ext1 i, rw [mul_assoc, two_mul, add_assoc], end end lemma lintegral_abs_det_fderiv_le_add_haar_image_aux2 (hs : measurable_set s) (h's : μ s ≠ ∞) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (hf : inj_on f s) : ∫⁻ x in s, ennreal.of_real (|(f' x).det|) ∂μ ≤ μ (f '' s) := begin /- We just need to let the error tend to `0` in the previous lemma. -/ have : tendsto (λ (ε : ℝ≥0), μ (f '' s) + 2 * ε * μ s) (𝓝[>] 0) (𝓝 (μ (f '' s) + 2 * (0 : ℝ≥0) * μ s)), { apply tendsto.mono_left _ nhds_within_le_nhds, refine tendsto_const_nhds.add _, refine ennreal.tendsto.mul_const _ (or.inr h's), exact ennreal.tendsto.const_mul (ennreal.tendsto_coe.2 tendsto_id) (or.inr ennreal.coe_ne_top) }, simp only [add_zero, zero_mul, mul_zero, ennreal.coe_zero] at this, apply ge_of_tendsto this, filter_upwards [self_mem_nhds_within], rintros ε (εpos : 0 < ε), exact lintegral_abs_det_fderiv_le_add_haar_image_aux1 μ hs hf' hf εpos end lemma lintegral_abs_det_fderiv_le_add_haar_image (hs : measurable_set s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (hf : inj_on f s) : ∫⁻ x in s, ennreal.of_real (|(f' x).det|) ∂μ ≤ μ (f '' s) := begin /- We already know the result for finite-measure sets. We cover `s` by finite-measure sets using `spanning_sets μ`, and apply the previous result to each of these parts. -/ let u := λ n, disjointed (spanning_sets μ) n, have u_meas : ∀ n, measurable_set (u n), { assume n, apply measurable_set.disjointed (λ i, _), exact measurable_spanning_sets μ i }, have A : s = ⋃ n, s ∩ u n, by rw [← inter_Union, Union_disjointed, Union_spanning_sets, inter_univ], calc ∫⁻ x in s, ennreal.of_real (|(f' x).det|) ∂μ = ∑' n, ∫⁻ x in s ∩ u n, ennreal.of_real (|(f' x).det|) ∂μ : begin conv_lhs { rw A }, rw lintegral_Union, { assume n, exact hs.inter (u_meas n) }, { exact pairwise_disjoint.mono (disjoint_disjointed _) (λ n, inter_subset_right _ _) } end ... ≤ ∑' n, μ (f '' (s ∩ u n)) : begin apply ennreal.tsum_le_tsum (λ n, _), apply lintegral_abs_det_fderiv_le_add_haar_image_aux2 μ (hs.inter (u_meas n)) _ (λ x hx, (hf' x hx.1).mono (inter_subset_left _ _)) (hf.mono (inter_subset_left _ _)), have : μ (u n) < ∞ := lt_of_le_of_lt (measure_mono (disjointed_subset _ _)) (measure_spanning_sets_lt_top μ n), exact ne_of_lt (lt_of_le_of_lt (measure_mono (inter_subset_right _ _)) this), end ... = μ (f '' s) : begin conv_rhs { rw [A, image_Union] }, rw measure_Union, { assume i j hij, apply disjoint.image _ hf (inter_subset_left _ _) (inter_subset_left _ _), exact disjoint.mono (inter_subset_right _ _) (inter_subset_right _ _) (disjoint_disjointed _ hij) }, { assume i, exact measurable_image_of_fderiv_within (hs.inter (u_meas i)) (λ x hx, (hf' x hx.1).mono (inter_subset_left _ _)) (hf.mono (inter_subset_left _ _)) }, end end /-- Change of variable formula for differentiable functions, set version: if a function `f` is injective and differentiable on a measurable set `s`, then the measure of `f '' s` is given by the integral of `|(f' x).det|` on `s`. Note that the measurability of `f '' s` is given by `measurable_image_of_fderiv_within`. -/ theorem lintegral_abs_det_fderiv_eq_add_haar_image (hs : measurable_set s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (hf : inj_on f s) : ∫⁻ x in s, ennreal.of_real (|(f' x).det|) ∂μ = μ (f '' s) := le_antisymm (lintegral_abs_det_fderiv_le_add_haar_image μ hs hf' hf) (add_haar_image_le_lintegral_abs_det_fderiv μ hs hf') /-- Change of variable formula for differentiable functions, set version: if a function `f` is injective and differentiable on a measurable set `s`, then the pushforward of the measure with density `|(f' x).det|` on `s` is the Lebesgue measure on the image set. This version requires that `f` is measurable, as otherwise `measure.map f` is zero per our definitions. For a version without measurability assumption but dealing with the restricted function `s.restrict f`, see `restrict_map_with_density_abs_det_fderiv_eq_add_haar`. -/ theorem map_with_density_abs_det_fderiv_eq_add_haar (hs : measurable_set s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (hf : inj_on f s) (h'f : measurable f) : measure.map f ((μ.restrict s).with_density (λ x, ennreal.of_real (|(f' x).det|))) = μ.restrict (f '' s) := begin apply measure.ext (λ t ht, _), rw [map_apply h'f ht, with_density_apply _ (h'f ht), measure.restrict_apply ht, restrict_restrict (h'f ht), lintegral_abs_det_fderiv_eq_add_haar_image μ ((h'f ht).inter hs) (λ x hx, (hf' x hx.2).mono (inter_subset_right _ _)) (hf.mono (inter_subset_right _ _)), image_preimage_inter] end /-- Change of variable formula for differentiable functions, set version: if a function `f` is injective and differentiable on a measurable set `s`, then the pushforward of the measure with density `|(f' x).det|` on `s` is the Lebesgue measure on the image set. This version is expressed in terms of the restricted function `s.restrict f`. For a version for the original function, but with a measurability assumption, see `map_with_density_abs_det_fderiv_eq_add_haar`. -/ theorem restrict_map_with_density_abs_det_fderiv_eq_add_haar (hs : measurable_set s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (hf : inj_on f s) : measure.map (s.restrict f) (comap coe (μ.with_density (λ x, ennreal.of_real (|(f' x).det|)))) = μ.restrict (f '' s) := begin obtain ⟨u, u_meas, uf⟩ : ∃ u, measurable u ∧ eq_on u f s, { classical, refine ⟨piecewise s f 0, _, piecewise_eq_on _ _ _⟩, refine continuous_on.measurable_piecewise _ continuous_zero.continuous_on hs, have : differentiable_on ℝ f s := λ x hx, (hf' x hx).differentiable_within_at, exact this.continuous_on }, have u' : ∀ x ∈ s, has_fderiv_within_at u (f' x) s x := λ x hx, (hf' x hx).congr (λ y hy, uf hy) (uf hx), set F : s → E := u ∘ coe with hF, have A : measure.map F (comap coe (μ.with_density (λ x, ennreal.of_real (|(f' x).det|)))) = μ.restrict (u '' s), { rw [hF, ← measure.map_map u_meas measurable_subtype_coe, map_comap_subtype_coe hs, restrict_with_density hs], exact map_with_density_abs_det_fderiv_eq_add_haar μ hs u' (hf.congr uf.symm) u_meas }, rw uf.image_eq at A, have : F = s.restrict f, { ext x, exact uf x.2 }, rwa this at A, end /-! ### Change of variable formulas in integrals -/ /- Change of variable formula for differentiable functions: if a function `f` is injective and differentiable on a measurable set `s`, then the Lebesgue integral of a function `g : E → ℝ≥0∞` on `f '' s` coincides with the integral of `|(f' x).det| * g ∘ f` on `s`. Note that the measurability of `f '' s` is given by `measurable_image_of_fderiv_within`. -/ theorem lintegral_image_eq_lintegral_abs_det_fderiv_mul (hs : measurable_set s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (hf : inj_on f s) (g : E → ℝ≥0∞) : ∫⁻ x in f '' s, g x ∂μ = ∫⁻ x in s, ennreal.of_real (|(f' x).det|) * g (f x) ∂μ := begin rw [← restrict_map_with_density_abs_det_fderiv_eq_add_haar μ hs hf' hf, (measurable_embedding_of_fderiv_within hs hf' hf).lintegral_map], have : ∀ (x : s), g (s.restrict f x) = (g ∘ f) x := λ x, rfl, simp only [this], rw [← (measurable_embedding.subtype_coe hs).lintegral_map, map_comap_subtype_coe hs, set_lintegral_with_density_eq_set_lintegral_mul_non_measurable₀ _ _ _ hs], { refl }, { simp only [eventually_true, ennreal.of_real_lt_top] }, { exact ae_measurable_of_real_abs_det_fderiv_within μ hs hf' } end /-- Integrability in the change of variable formula for differentiable functions: if a function `f` is injective and differentiable on a measurable set `s`, then a function `g : E → F` is integrable on `f '' s` if and only if `|(f' x).det| • g ∘ f` is integrable on `s`. -/ theorem integrable_on_image_iff_integrable_on_abs_det_fderiv_smul (hs : measurable_set s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (hf : inj_on f s) (g : E → F) : integrable_on g (f '' s) μ ↔ integrable_on (λ x, |(f' x).det| • g (f x)) s μ := begin rw [integrable_on, ← restrict_map_with_density_abs_det_fderiv_eq_add_haar μ hs hf' hf, (measurable_embedding_of_fderiv_within hs hf' hf).integrable_map_iff], change (integrable ((g ∘ f) ∘ (coe : s → E)) _) ↔ _, rw [← (measurable_embedding.subtype_coe hs).integrable_map_iff, map_comap_subtype_coe hs], simp only [ennreal.of_real], rw [restrict_with_density hs, integrable_with_density_iff_integrable_coe_smul₀, integrable_on], { congr' 2 with x, rw real.coe_to_nnreal, exact abs_nonneg _ }, { exact ae_measurable_to_nnreal_abs_det_fderiv_within μ hs hf' } end /-- Change of variable formula for differentiable functions: if a function `f` is injective and differentiable on a measurable set `s`, then the Bochner integral of a function `g : E → F` on `f '' s` coincides with the integral of `|(f' x).det| • g ∘ f` on `s`. -/ theorem integral_image_eq_integral_abs_det_fderiv_smul [complete_space F] (hs : measurable_set s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (hf : inj_on f s) (g : E → F) : ∫ x in f '' s, g x ∂μ = ∫ x in s, |(f' x).det| • g (f x) ∂μ := begin rw [← restrict_map_with_density_abs_det_fderiv_eq_add_haar μ hs hf' hf, (measurable_embedding_of_fderiv_within hs hf' hf).integral_map], have : ∀ (x : s), g (s.restrict f x) = (g ∘ f) x := λ x, rfl, simp only [this, ennreal.of_real], rw [← (measurable_embedding.subtype_coe hs).integral_map, map_comap_subtype_coe hs, set_integral_with_density_eq_set_integral_smul₀ (ae_measurable_to_nnreal_abs_det_fderiv_within μ hs hf') _ hs], congr' with x, conv_rhs { rw ← real.coe_to_nnreal _ (abs_nonneg (f' x).det) }, refl end /-- Change of variable formula for differentiable functions (one-variable version): if a function `f` is injective and differentiable on a measurable set `s ⊆ ℝ`, then the Bochner integral of a function `g : ℝ → F` on `f '' s` coincides with the integral of `|(f' x).det| • g ∘ f` on `s`. -/ theorem integral_image_eq_integral_abs_deriv_smul {s : set ℝ} {f : ℝ → ℝ} {f' : ℝ → ℝ} [complete_space F] (hs : measurable_set s) (hf' : ∀ x ∈ s, has_deriv_within_at f (f' x) s x) (hf : inj_on f s) (g : ℝ → F) : ∫ x in f '' s, g x = ∫ x in s, |(f' x)| • g (f x) := begin convert integral_image_eq_integral_abs_det_fderiv_smul volume hs (λ x hx, (hf' x hx).has_fderiv_within_at) hf g, ext1 x, rw (by { ext, simp } : (1 : ℝ →L[ℝ] ℝ).smul_right (f' x) = (f' x) • (1 : ℝ →L[ℝ] ℝ)), rw [continuous_linear_map.det, continuous_linear_map.coe_smul], have : ((1 : ℝ →L[ℝ] ℝ) : ℝ →ₗ[ℝ] ℝ) = (1 : ℝ →ₗ[ℝ] ℝ) := by refl, rw [this, linear_map.det_smul, finite_dimensional.finrank_self], suffices : (1 : ℝ →ₗ[ℝ] ℝ).det = 1, { rw this, simp }, exact linear_map.det_id, end theorem integral_target_eq_integral_abs_det_fderiv_smul [complete_space F] {f : local_homeomorph E E} (hf' : ∀ x ∈ f.source, has_fderiv_at f (f' x) x) (g : E → F) : ∫ x in f.target, g x ∂μ = ∫ x in f.source, |(f' x).det| • g (f x) ∂μ := begin have : f '' f.source = f.target := local_equiv.image_source_eq_target f.to_local_equiv, rw ← this, apply integral_image_eq_integral_abs_det_fderiv_smul μ f.open_source.measurable_set _ f.inj_on, assume x hx, exact (hf' x hx).has_fderiv_within_at end end measure_theory
8a8704291533aad92ac593e943d5f5e612ecb23c
4727251e0cd73359b15b664c3170e5d754078599
/src/ring_theory/localization/fraction_ring.lean
24db6a6ca6fc41a53677241f51001dc2a5260762
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
12,058
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro, Johan Commelin, Amelia Livingston, Anne Baanen -/ import algebra.algebra.tower import ring_theory.localization.basic /-! # Fraction ring / fraction field Frac(R) as localization ## Main definitions * `is_fraction_ring R K` expresses that `K` is a field of fractions of `R`, as an abbreviation of `is_localization (non_zero_divisors R) K` ## Main results * `is_fraction_ring.field`: a definition (not an instance) stating the localization of an integral domain `R` at `R \ {0}` is a field * `rat.is_fraction_ring` is an instance stating `ℚ` is the field of fractions of `ℤ` ## Implementation notes See `src/ring_theory/localization/basic.lean` for a design overview. ## Tags localization, ring localization, commutative ring localization, characteristic predicate, commutative ring, field of fractions -/ variables (R : Type*) [comm_ring R] {M : submonoid R} (S : Type*) [comm_ring S] variables [algebra R S] {P : Type*} [comm_ring P] variables {A : Type*} [comm_ring A] [is_domain A] (K : Type*) /-- `is_fraction_ring R K` states `K` is the field of fractions of an integral domain `R`. -/ -- TODO: should this extend `algebra` instead of assuming it? abbreviation is_fraction_ring [comm_ring K] [algebra R K] := is_localization (non_zero_divisors R) K /-- The cast from `int` to `rat` as a `fraction_ring`. -/ instance rat.is_fraction_ring : is_fraction_ring ℤ ℚ := { map_units := begin rintro ⟨x, hx⟩, rw mem_non_zero_divisors_iff_ne_zero at hx, simpa only [ring_hom.eq_int_cast, is_unit_iff_ne_zero, int.cast_eq_zero, ne.def, subtype.coe_mk] using hx, end, surj := begin rintro ⟨n, d, hd, h⟩, refine ⟨⟨n, ⟨d, _⟩⟩, rat.mul_denom_eq_num⟩, rwa [mem_non_zero_divisors_iff_ne_zero, int.coe_nat_ne_zero_iff_pos] end, eq_iff_exists := begin intros x y, rw [ring_hom.eq_int_cast, ring_hom.eq_int_cast, int.cast_inj], refine ⟨by { rintro rfl, use 1 }, _⟩, rintro ⟨⟨c, hc⟩, h⟩, apply int.eq_of_mul_eq_mul_right _ h, rwa mem_non_zero_divisors_iff_ne_zero at hc, end } namespace is_fraction_ring open is_localization variables {R K} section comm_ring variables [comm_ring K] [algebra R K] [is_fraction_ring R K] [algebra A K] [is_fraction_ring A K] lemma to_map_eq_zero_iff {x : R} : algebra_map R K x = 0 ↔ x = 0 := to_map_eq_zero_iff _ (le_of_eq rfl) variables (R K) protected theorem injective : function.injective (algebra_map R K) := is_localization.injective _ (le_of_eq rfl) variables {R K} @[priority 100] instance [no_zero_divisors K] : no_zero_smul_divisors R K := no_zero_smul_divisors.of_algebra_map_injective $ is_fraction_ring.injective R K variables {R K} protected lemma to_map_ne_zero_of_mem_non_zero_divisors [nontrivial R] {x : R} (hx : x ∈ non_zero_divisors R) : algebra_map R K x ≠ 0 := is_localization.to_map_ne_zero_of_mem_non_zero_divisors _ le_rfl hx variables (A) /-- A `comm_ring` `K` which is the localization of an integral domain `R` at `R - {0}` is an integral domain. -/ protected theorem is_domain : is_domain K := is_domain_of_le_non_zero_divisors _ (le_refl (non_zero_divisors A)) local attribute [instance] classical.dec_eq /-- The inverse of an element in the field of fractions of an integral domain. -/ @[irreducible] protected noncomputable def inv (z : K) : K := if h : z = 0 then 0 else mk' K ↑(sec (non_zero_divisors A) z).2 ⟨(sec _ z).1, mem_non_zero_divisors_iff_ne_zero.2 $ λ h0, h $ eq_zero_of_fst_eq_zero (sec_spec (non_zero_divisors A) z) h0⟩ local attribute [semireducible] is_fraction_ring.inv protected lemma mul_inv_cancel (x : K) (hx : x ≠ 0) : x * is_fraction_ring.inv A x = 1 := show x * dite _ _ _ = 1, by rw [dif_neg hx, ←is_unit.mul_left_inj (map_units K ⟨(sec _ x).1, mem_non_zero_divisors_iff_ne_zero.2 $ λ h0, hx $ eq_zero_of_fst_eq_zero (sec_spec (non_zero_divisors A) x) h0⟩), one_mul, mul_assoc, mk'_spec, ←eq_mk'_iff_mul_eq]; exact (mk'_sec _ x).symm /-- A `comm_ring` `K` which is the localization of an integral domain `R` at `R - {0}` is a field. See note [reducible non-instances]. -/ @[reducible] noncomputable def to_field : field K := { inv := is_fraction_ring.inv A, mul_inv_cancel := is_fraction_ring.mul_inv_cancel A, inv_zero := dif_pos rfl, .. is_fraction_ring.is_domain A, .. show comm_ring K, by apply_instance } end comm_ring variables {B : Type*} [comm_ring B] [is_domain B] [field K] {L : Type*} [field L] [algebra A K] [is_fraction_ring A K] {g : A →+* L} lemma mk'_mk_eq_div {r s} (hs : s ∈ non_zero_divisors A) : mk' K r ⟨s, hs⟩ = algebra_map A K r / algebra_map A K s := mk'_eq_iff_eq_mul.2 $ (div_mul_cancel (algebra_map A K r) (is_fraction_ring.to_map_ne_zero_of_mem_non_zero_divisors hs)).symm @[simp] lemma mk'_eq_div {r} (s : non_zero_divisors A) : mk' K r s = algebra_map A K r / algebra_map A K s := mk'_mk_eq_div s.2 lemma div_surjective (z : K) : ∃ (x y : A) (hy : y ∈ non_zero_divisors A), algebra_map _ _ x / algebra_map _ _ y = z := let ⟨x, ⟨y, hy⟩, h⟩ := mk'_surjective (non_zero_divisors A) z in ⟨x, y, hy, by rwa mk'_eq_div at h⟩ lemma is_unit_map_of_injective (hg : function.injective g) (y : non_zero_divisors A) : is_unit (g y) := is_unit.mk0 (g y) $ show g.to_monoid_with_zero_hom y ≠ 0, from map_ne_zero_of_mem_non_zero_divisors g hg y.2 @[simp] lemma mk'_eq_zero_iff_eq_zero [algebra R K] [is_fraction_ring R K] {x : R} {y : non_zero_divisors R} : mk' K x y = 0 ↔ x = 0 := begin refine ⟨λ hxy, _, λ h, by rw [h, mk'_zero]⟩, { simp_rw [mk'_eq_zero_iff, mul_right_coe_non_zero_divisors_eq_zero_iff] at hxy, exact (exists_const _).mp hxy }, end lemma mk'_eq_one_iff_eq {x : A} {y : non_zero_divisors A} : mk' K x y = 1 ↔ x = y := begin refine ⟨_, λ hxy, by rw [hxy, mk'_self']⟩, { intro hxy, have hy : (algebra_map A K) ↑y ≠ (0 : K) := is_fraction_ring.to_map_ne_zero_of_mem_non_zero_divisors y.property, rw [is_fraction_ring.mk'_eq_div, div_eq_one_iff_eq hy] at hxy, exact is_fraction_ring.injective A K hxy } end open function /-- Given an integral domain `A` with field of fractions `K`, and an injective ring hom `g : A →+* L` where `L` is a field, we get a field hom sending `z : K` to `g x * (g y)⁻¹`, where `(x, y) : A × (non_zero_divisors A)` are such that `z = f x * (f y)⁻¹`. -/ noncomputable def lift (hg : injective g) : K →+* L := lift $ λ (y : non_zero_divisors A), is_unit_map_of_injective hg y /-- Given an integral domain `A` with field of fractions `K`, and an injective ring hom `g : A →+* L` where `L` is a field, the field hom induced from `K` to `L` maps `x` to `g x` for all `x : A`. -/ @[simp] lemma lift_algebra_map (hg : injective g) (x) : lift hg (algebra_map A K x) = g x := lift_eq _ _ /-- Given an integral domain `A` with field of fractions `K`, and an injective ring hom `g : A →+* L` where `L` is a field, field hom induced from `K` to `L` maps `f x / f y` to `g x / g y` for all `x : A, y ∈ non_zero_divisors A`. -/ lemma lift_mk' (hg : injective g) (x) (y : non_zero_divisors A) : lift hg (mk' K x y) = g x / g y := by simp only [mk'_eq_div, ring_hom.map_div, lift_algebra_map] /-- Given integral domains `A, B` with fields of fractions `K`, `L` and an injective ring hom `j : A →+* B`, we get a field hom sending `z : K` to `g (j x) * (g (j y))⁻¹`, where `(x, y) : A × (non_zero_divisors A)` are such that `z = f x * (f y)⁻¹`. -/ noncomputable def map {A B K L : Type*} [comm_ring A] [comm_ring B] [is_domain B] [comm_ring K] [algebra A K] [is_fraction_ring A K] [comm_ring L] [algebra B L] [is_fraction_ring B L] {j : A →+* B} (hj : injective j) : K →+* L := map L j (show non_zero_divisors A ≤ (non_zero_divisors B).comap j, from non_zero_divisors_le_comap_non_zero_divisors_of_injective j hj) /-- Given integral domains `A, B` and localization maps to their fields of fractions `f : A →+* K, g : B →+* L`, an isomorphism `j : A ≃+* B` induces an isomorphism of fields of fractions `K ≃+* L`. -/ noncomputable def field_equiv_of_ring_equiv [algebra B L] [is_fraction_ring B L] (h : A ≃+* B) : K ≃+* L := ring_equiv_of_ring_equiv K L h begin ext b, show b ∈ h.to_equiv '' _ ↔ _, erw [h.to_equiv.image_eq_preimage, set.preimage, set.mem_set_of_eq, mem_non_zero_divisors_iff_ne_zero, mem_non_zero_divisors_iff_ne_zero], exact h.symm.map_ne_zero_iff end variables (S) lemma is_fraction_ring_iff_of_base_ring_equiv (h : R ≃+* P) : is_fraction_ring R S ↔ @@is_fraction_ring P _ S _ ((algebra_map R S).comp h.symm.to_ring_hom).to_algebra := begin delta is_fraction_ring, convert is_localization_iff_of_base_ring_equiv _ _ h, ext x, erw submonoid.map_equiv_eq_comap_symm, simp only [mul_equiv.coe_to_monoid_hom, ring_equiv.to_mul_equiv_eq_coe, submonoid.mem_comap], split, { rintros hx z (hz : z * h.symm x = 0), rw ← h.map_eq_zero_iff, apply hx, simpa only [h.map_zero, h.apply_symm_apply, h.map_mul] using congr_arg h hz }, { rintros (hx : h.symm x ∈ _) z hz, rw ← h.symm.map_eq_zero_iff, apply hx, rw [← h.symm.map_mul, hz, h.symm.map_zero] } end protected lemma nontrivial (R S : Type*) [comm_ring R] [nontrivial R] [comm_ring S] [algebra R S] [is_fraction_ring R S] : nontrivial S := begin apply nontrivial_of_ne, intro h, apply @zero_ne_one R, exact is_localization.injective S (le_of_eq rfl) (((algebra_map R S).map_zero.trans h).trans (algebra_map R S).map_one.symm), end end is_fraction_ring variables (R A) /-- The fraction ring of a commutative ring `R` as a quotient type. We instantiate this definition as generally as possible, and assume that the commutative ring `R` is an integral domain only when this is needed for proving. -/ @[reducible] def fraction_ring := localization (non_zero_divisors R) namespace fraction_ring instance unique [subsingleton R] : unique (fraction_ring R) := localization.unique instance [nontrivial R] : nontrivial (fraction_ring R) := ⟨⟨(algebra_map R _) 0, (algebra_map _ _) 1, λ H, zero_ne_one (is_localization.injective _ le_rfl H)⟩⟩ variables {A} noncomputable instance : field (fraction_ring A) := { add := (+), mul := (*), neg := has_neg.neg, sub := has_sub.sub, one := 1, zero := 0, nsmul := add_monoid.nsmul, zsmul := sub_neg_monoid.zsmul, npow := localization.npow _, .. localization.comm_ring, .. is_fraction_ring.to_field A } @[simp] lemma mk_eq_div {r s} : (localization.mk r s : fraction_ring A) = (algebra_map _ _ r / algebra_map A _ s : fraction_ring A) := by rw [localization.mk_eq_mk', is_fraction_ring.mk'_eq_div] noncomputable instance [is_domain R] [field K] [algebra R K] [no_zero_smul_divisors R K] : algebra (fraction_ring R) K := ring_hom.to_algebra (is_fraction_ring.lift (no_zero_smul_divisors.algebra_map_injective R _)) instance [is_domain R] [field K] [algebra R K] [no_zero_smul_divisors R K] : is_scalar_tower R (fraction_ring R) K := is_scalar_tower.of_algebra_map_eq (λ x, (is_fraction_ring.lift_algebra_map _ x).symm) variables (A) /-- Given an integral domain `A` and a localization map to a field of fractions `f : A →+* K`, we get an `A`-isomorphism between the field of fractions of `A` as a quotient type and `K`. -/ noncomputable def alg_equiv (K : Type*) [field K] [algebra A K] [is_fraction_ring A K] : fraction_ring A ≃ₐ[A] K := localization.alg_equiv (non_zero_divisors A) K instance [algebra R A] [no_zero_smul_divisors R A] : no_zero_smul_divisors R (fraction_ring A) := no_zero_smul_divisors.of_algebra_map_injective begin rw [is_scalar_tower.algebra_map_eq R A], exact function.injective.comp (no_zero_smul_divisors.algebra_map_injective _ _) (no_zero_smul_divisors.algebra_map_injective _ _) end end fraction_ring
03fa364be3f0c8824ad2aa13a2aab8f3bffa8be8
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/data/list/min_max.lean
503ccc232ec8a0ede2f20be197fd6040d155870a
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
5,680
lean
/- Copyright (c) 2019 Minchao Wu. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Minchao Wu -/ import data.list algebra.order_functions namespace list universes u variables {α : Type u} [inhabited α] [decidable_linear_order α] @[simp] def maximum (l : list α) : α := l.foldl max l.head @[simp] def minimum (l : list α) : α := l.foldl min l.head def maximum_aux (l : list α) : α := l.foldr max l.head def minimum_aux (l : list α) : α := l.foldr min l.head @[simp] def maximum_singleton {a : α} : maximum [a] = a := by simp @[simp] def minimum_singleton {a : α} : minimum [a] = a := by simp theorem le_of_foldr_max : Π {a b : α} {l}, a ∈ l → a ≤ foldr max b l | a b [] h := absurd h $ not_mem_nil _ | a b (hd::tl) h := begin cases h, { simp [h, le_refl] }, { simp [le_max_right_of_le, le_of_foldr_max h] } end theorem le_of_foldr_min : Π {a b : α} {l}, a ∈ l → foldr min b l ≤ a | a b [] h := absurd h $ not_mem_nil _ | a b (hd::tl) h := begin cases h, { simp [h, le_refl] }, { simp [min_le_left_of_le, le_of_foldr_min h] } end theorem le_of_foldl_max {a b : α} {l} (h : a ∈ l) : a ≤ foldl max b l := by { rw foldl_eq_foldr max_comm max_assoc, apply le_of_foldr_max h } theorem le_of_foldl_min {a b : α} {l} (h : a ∈ l) : foldl min b l ≤ a := by { rw foldl_eq_foldr min_comm min_assoc, apply le_of_foldr_min h } theorem mem_foldr_max : Π {a : α} {l}, foldr max a l ∈ a :: l | a [] := by simp | a (hd::tl) := begin simp only [foldr_cons], cases (@max_choice _ _ hd (foldr max a tl)), { simp [h] }, { rw h, have hmem := @mem_foldr_max a tl, cases hmem, { simp [hmem] }, { right, right, exact hmem } } end theorem mem_foldr_min : Π {a : α} {l}, foldr min a l ∈ a :: l | a [] := by simp | a (hd::tl) := begin simp only [foldr_cons], cases (@min_choice _ _ hd (foldr min a tl)), { simp [h] }, { rw h, have hmem := @mem_foldr_min a tl, cases hmem, { simp [hmem] }, { right, right, exact hmem } } end theorem mem_foldl_max {a : α} {l} : foldl max a l ∈ a :: l := by { rw foldl_eq_foldr max_comm max_assoc, apply mem_foldr_max } theorem mem_foldl_min {a : α} {l} : foldl min a l ∈ a :: l := by { rw foldl_eq_foldr min_comm min_assoc, apply mem_foldr_min } theorem mem_maximum_aux : Π {l : list α}, l ≠ [] → maximum_aux l ∈ l | [] h := by contradiction | (hd::tl) h := begin dsimp [maximum_aux], have hc := @max_choice _ _ hd (foldr max hd tl), cases hc, { simp [hc] }, { simp [hc, mem_foldr_max] } end theorem mem_minimum_aux : Π {l : list α}, l ≠ [] → minimum_aux l ∈ l | [] h := by contradiction | (hd::tl) h := begin dsimp [minimum_aux], have hc := @min_choice _ _ hd (foldr min hd tl), cases hc, { simp [hc] }, { simp [hc, mem_foldr_min] } end theorem mem_maximum {l : list α} (h : l ≠ []) : maximum l ∈ l := by { dsimp, rw foldl_eq_foldr max_comm max_assoc, apply mem_maximum_aux h } theorem mem_minimum {l : list α} (h : l ≠ []) : minimum l ∈ l := by { dsimp, rw foldl_eq_foldr min_comm min_assoc, apply mem_minimum_aux h } theorem le_maximum_aux_of_mem : Π {a : α} {l}, a ∈ l → a ≤ maximum_aux l | a [] h := absurd h $ not_mem_nil _ | a (hd::tl) h := begin cases h, { rw h, apply le_of_foldr_max, simp }, { dsimp [maximum_aux], apply le_max_right_of_le, apply le_of_foldr_max h } end theorem le_minimum_aux_of_mem : Π {a : α} {l}, a ∈ l → minimum_aux l ≤ a | a [] h := absurd h $ not_mem_nil _ | a (hd::tl) h := begin cases h, { rw h, apply le_of_foldr_min, simp }, { dsimp [minimum_aux], apply min_le_right_of_le, apply le_of_foldr_min h } end theorem le_maximum_of_mem {a : α} {l} (h : a ∈ l) : a ≤ maximum l := by { dsimp, rw foldl_eq_foldr max_comm max_assoc, apply le_maximum_aux_of_mem h } theorem le_minimum_of_mem {a : α} {l} (h : a ∈ l) : minimum l ≤ a := by { dsimp, rw foldl_eq_foldr min_comm min_assoc, apply le_minimum_aux_of_mem h } def maximum_aux_cons : Π {a : α} {l}, l ≠ [] → maximum_aux (a :: l) = max a (maximum_aux l) | a [] h := by contradiction | a (hd::tl) h := begin apply le_antisymm, { have : a :: hd :: tl ≠ [], { simp [h] }, have hle := mem_maximum_aux this, cases hle, { simp [hle, le_max_left] }, { apply le_max_right_of_le, apply le_maximum_aux_of_mem, exact hle } }, { have hc := @max_choice _ _ a (maximum_aux $ hd :: tl), cases hc, { simp [hc, le_maximum_aux_of_mem] }, { simp [hc, le_maximum_aux_of_mem, mem_maximum_aux h] } } end def minimum_aux_cons : Π {a : α} {l}, l ≠ [] → minimum_aux (a :: l) = min a (minimum_aux l) | a [] h := by contradiction | a (hd::tl) h := begin apply le_antisymm, { have hc := @min_choice _ _ a (minimum_aux $ hd :: tl), cases hc, { simp [hc, le_minimum_aux_of_mem] }, { simp [hc, le_minimum_aux_of_mem, mem_minimum_aux h] } }, { have : a :: hd :: tl ≠ [], { simp [h] }, have hle := mem_minimum_aux this, cases hle, { simp [hle, min_le_left] }, { apply min_le_right_of_le, apply le_minimum_aux_of_mem, exact hle } } end def maximum_cons {a : α} {l} (h : l ≠ []) : maximum (a :: l) = max a (maximum l) := begin dsimp only [maximum], repeat { rw foldl_eq_foldr max_comm max_assoc }, have := maximum_aux_cons h, dsimp only [maximum_aux] at this, exact this end def minimum_cons {a : α} {l} (h : l ≠ []) : minimum (a :: l) = min a (minimum l) := begin dsimp only [minimum], repeat { rw foldl_eq_foldr min_comm min_assoc }, have := minimum_aux_cons h, dsimp only [minimum_aux] at this, exact this end end list
bce7e1778bf6165256c40f1ce24441fc718074b7
d642a6b1261b2cbe691e53561ac777b924751b63
/src/topology/separation.lean
9ece0dcc69cff6f0a5cad756a08f4acf38693486
[ "Apache-2.0" ]
permissive
cipher1024/mathlib
fee56b9954e969721715e45fea8bcb95f9dc03fe
d077887141000fefa5a264e30fa57520e9f03522
refs/heads/master
1,651,806,490,504
1,573,508,694,000
1,573,508,694,000
107,216,176
0
0
Apache-2.0
1,647,363,136,000
1,508,213,014,000
Lean
UTF-8
Lean
false
false
16,270
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 Separation properties of topological spaces. -/ import topology.subset_properties open set filter lattice local attribute [instance] classical.prop_decidable -- TODO: use "open_locale classical" universes u v variables {α : Type u} {β : Type v} [topological_space α] section separation /-- A T₀ space, also known as a Kolmogorov space, is a topological space where for every pair `x ≠ y`, there is an open set containing one but not the other. -/ class t0_space (α : Type u) [topological_space α] : Prop := (t0 : ∀ x y, x ≠ y → ∃ U:set α, is_open U ∧ (xor (x ∈ U) (y ∈ U))) theorem exists_open_singleton_of_fintype [t0_space α] [f : fintype α] [decidable_eq α] [ha : nonempty α] : ∃ x:α, is_open ({x}:set α) := have H : ∀ (T : finset α), T ≠ ∅ → ∃ x ∈ T, ∃ u, is_open u ∧ {x} = {y | y ∈ T} ∩ u := begin intro T, apply finset.case_strong_induction_on T, { intro h, exact (h rfl).elim }, { intros x S hxS ih h, by_cases hs : S = ∅, { existsi [x, finset.mem_insert_self x S, univ, is_open_univ], rw [hs, inter_univ], refl }, { rcases ih S (finset.subset.refl S) hs with ⟨y, hy, V, hv1, hv2⟩, by_cases hxV : x ∈ V, { cases t0_space.t0 x y (λ hxy, hxS $ by rwa hxy) with U hu, rcases hu with ⟨hu1, ⟨hu2, hu3⟩ | ⟨hu2, hu3⟩⟩, { existsi [x, finset.mem_insert_self x S, U ∩ V, is_open_inter hu1 hv1], apply set.ext, intro z, split, { intro hzx, rw set.mem_singleton_iff at hzx, rw hzx, exact ⟨finset.mem_insert_self x S, ⟨hu2, hxV⟩⟩ }, { intro hz, rw set.mem_singleton_iff, rcases hz with ⟨hz1, hz2, hz3⟩, cases finset.mem_insert.1 hz1 with hz4 hz4, { exact hz4 }, { have h1 : z ∈ {y : α | y ∈ S} ∩ V, { exact ⟨hz4, hz3⟩ }, rw ← hv2 at h1, rw set.mem_singleton_iff at h1, rw h1 at hz2, exact (hu3 hz2).elim } } }, { existsi [y, finset.mem_insert_of_mem hy, U ∩ V, is_open_inter hu1 hv1], apply set.ext, intro z, split, { intro hz, rw set.mem_singleton_iff at hz, rw hz, refine ⟨finset.mem_insert_of_mem hy, hu2, _⟩, have h1 : y ∈ {y} := set.mem_singleton y, rw hv2 at h1, exact h1.2 }, { intro hz, rw set.mem_singleton_iff, cases hz with hz1 hz2, cases finset.mem_insert.1 hz1 with hz3 hz3, { rw hz3 at hz2, exact (hu3 hz2.1).elim }, { have h1 : z ∈ {y : α | y ∈ S} ∩ V := ⟨hz3, hz2.2⟩, rw ← hv2 at h1, rw set.mem_singleton_iff at h1, exact h1 } } } }, { existsi [y, finset.mem_insert_of_mem hy, V, hv1], apply set.ext, intro z, split, { intro hz, rw set.mem_singleton_iff at hz, rw hz, split, { exact finset.mem_insert_of_mem hy }, { have h1 : y ∈ {y} := set.mem_singleton y, rw hv2 at h1, exact h1.2 } }, { intro hz, rw hv2, cases hz with hz1 hz2, cases finset.mem_insert.1 hz1 with hz3 hz3, { rw hz3 at hz2, exact (hxV hz2).elim }, { exact ⟨hz3, hz2⟩ } } } } } end, begin apply nonempty.elim ha, intro x, specialize H finset.univ (finset.ne_empty_of_mem $ finset.mem_univ x), rcases H with ⟨y, hyf, U, hu1, hu2⟩, existsi y, have h1 : {y : α | y ∈ finset.univ} = (univ : set α), { exact set.eq_univ_of_forall (λ x : α, by rw mem_set_of_eq; exact finset.mem_univ x) }, rw h1 at hu2, rw set.univ_inter at hu2, rw hu2, exact hu1 end /-- A T₁ space, also known as a Fréchet space, is a topological space where every singleton set is closed. Equivalently, for every pair `x ≠ y`, there is an open set containing `x` and not `y`. -/ class t1_space (α : Type u) [topological_space α] : Prop := (t1 : ∀x, is_closed ({x} : set α)) lemma is_closed_singleton [t1_space α] {x : α} : is_closed ({x} : set α) := t1_space.t1 x instance t1_space.t0_space [t1_space α] : t0_space α := ⟨λ x y h, ⟨-{x}, is_open_compl_iff.2 is_closed_singleton, or.inr ⟨λ hyx, or.cases_on hyx h.symm id, λ hx, hx $ or.inl rfl⟩⟩⟩ lemma compl_singleton_mem_nhds [t1_space α] {x y : α} (h : y ≠ x) : - {x} ∈ nhds y := mem_nhds_sets is_closed_singleton $ by rwa [mem_compl_eq, mem_singleton_iff] @[simp] lemma closure_singleton [t1_space α] {a : α} : closure ({a} : set α) = {a} := closure_eq_of_is_closed is_closed_singleton /-- A T₂ space, also known as a Hausdorff space, is one in which for every `x ≠ y` there exists disjoint open sets around `x` and `y`. This is the most widely used of the separation axioms. -/ class t2_space (α : Type u) [topological_space α] : Prop := (t2 : ∀x y, x ≠ y → ∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅) lemma t2_separation [t2_space α] {x y : α} (h : x ≠ y) : ∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅ := t2_space.t2 x y h instance t2_space.t1_space [t2_space α] : t1_space α := ⟨λ x, is_open_iff_forall_mem_open.2 $ λ y hxy, let ⟨u, v, hu, hv, hyu, hxv, huv⟩ := t2_separation (mt mem_singleton_of_eq hxy) in ⟨u, λ z hz1 hz2, ((ext_iff _ _).1 huv x).1 ⟨mem_singleton_iff.1 hz2 ▸ hz1, hxv⟩, hu, hyu⟩⟩ lemma eq_of_nhds_neq_bot [ht : t2_space α] {x y : α} (h : nhds x ⊓ nhds y ≠ ⊥) : x = y := classical.by_contradiction $ assume : x ≠ y, let ⟨u, v, hu, hv, hx, hy, huv⟩ := t2_space.t2 x y this in have u ∩ v ∈ nhds x ⊓ nhds y, from inter_mem_inf_sets (mem_nhds_sets hu hx) (mem_nhds_sets hv hy), h $ empty_in_sets_eq_bot.mp $ huv ▸ this lemma t2_iff_nhds : t2_space α ↔ ∀ {x y : α}, nhds x ⊓ nhds y ≠ ⊥ → x = y := ⟨assume h, by exactI λ x y, eq_of_nhds_neq_bot, assume h, ⟨assume x y xy, have nhds x ⊓ nhds y = ⊥ := classical.by_contradiction (mt h xy), let ⟨u', hu', v', hv', u'v'⟩ := empty_in_sets_eq_bot.mpr this, ⟨u, uu', uo, hu⟩ := mem_nhds_sets_iff.mp hu', ⟨v, vv', vo, hv⟩ := mem_nhds_sets_iff.mp hv' in ⟨u, v, uo, vo, hu, hv, disjoint.eq_bot $ disjoint_mono uu' vv' u'v'⟩⟩⟩ lemma t2_iff_ultrafilter : t2_space α ↔ ∀ f {x y : α}, is_ultrafilter f → f ≤ nhds x → f ≤ nhds y → x = y := t2_iff_nhds.trans ⟨assume h f x y u fx fy, h $ neq_bot_of_le_neq_bot u.1 (le_inf fx fy), assume h x y xy, let ⟨f, hf, uf⟩ := exists_ultrafilter xy in h f uf (le_trans hf lattice.inf_le_left) (le_trans hf lattice.inf_le_right)⟩ @[simp] lemma nhds_eq_nhds_iff {a b : α} [t2_space α] : nhds a = nhds b ↔ a = b := ⟨assume h, eq_of_nhds_neq_bot $ by rw [h, inf_idem]; exact nhds_neq_bot, assume h, h ▸ rfl⟩ @[simp] lemma nhds_le_nhds_iff {a b : α} [t2_space α] : nhds a ≤ nhds b ↔ a = b := ⟨assume h, eq_of_nhds_neq_bot $ by rw [inf_of_le_left h]; exact nhds_neq_bot, assume h, h ▸ le_refl _⟩ lemma tendsto_nhds_unique [t2_space α] {f : β → α} {l : filter β} {a b : α} (hl : l ≠ ⊥) (ha : tendsto f l (nhds a)) (hb : tendsto f l (nhds b)) : a = b := eq_of_nhds_neq_bot $ neq_bot_of_le_neq_bot (map_ne_bot hl) $ le_inf ha hb section lim variables [inhabited α] [t2_space α] {f : filter α} lemma lim_eq {a : α} (hf : f ≠ ⊥) (h : f ≤ nhds a) : lim f = a := eq_of_nhds_neq_bot $ neq_bot_of_le_neq_bot hf $ le_inf (lim_spec ⟨_, h⟩) h @[simp] lemma lim_nhds_eq {a : α} : lim (nhds a) = a := lim_eq nhds_neq_bot (le_refl _) @[simp] lemma lim_nhds_eq_of_closure {a : α} {s : set α} (h : a ∈ closure s) : lim (nhds a ⊓ principal s) = a := lim_eq begin rw [closure_eq_nhds] at h, exact h end inf_le_left end lim instance t2_space_discrete {α : Type*} [topological_space α] [discrete_topology α] : t2_space α := { t2 := assume x y hxy, ⟨{x}, {y}, is_open_discrete _, is_open_discrete _, mem_insert _ _, mem_insert _ _, eq_empty_iff_forall_not_mem.2 $ by intros z hz; cases eq_of_mem_singleton hz.1; cases eq_of_mem_singleton hz.2; cc⟩ } private lemma separated_by_f {α : Type*} {β : Type*} [tα : topological_space α] [tβ : topological_space β] [t2_space β] (f : α → β) (hf : tα ≤ tβ.induced f) {x y : α} (h : f x ≠ f y) : ∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅ := let ⟨u, v, uo, vo, xu, yv, uv⟩ := t2_separation h in ⟨f ⁻¹' u, f ⁻¹' v, hf _ ⟨u, uo, rfl⟩, hf _ ⟨v, vo, rfl⟩, xu, yv, by rw [←preimage_inter, uv, preimage_empty]⟩ instance {α : Type*} {p : α → Prop} [t : topological_space α] [t2_space α] : t2_space (subtype p) := ⟨assume x y h, separated_by_f subtype.val (le_refl _) (mt subtype.eq h)⟩ instance {α : Type*} {β : Type*} [t₁ : topological_space α] [t2_space α] [t₂ : topological_space β] [t2_space β] : t2_space (α × β) := ⟨assume ⟨x₁,x₂⟩ ⟨y₁,y₂⟩ h, or.elim (not_and_distrib.mp (mt prod.ext_iff.mpr h)) (λ h₁, separated_by_f prod.fst inf_le_left h₁) (λ h₂, separated_by_f prod.snd inf_le_right h₂)⟩ instance Pi.t2_space {α : Type*} {β : α → Type v} [t₂ : Πa, topological_space (β a)] [Πa, t2_space (β a)] : t2_space (Πa, β a) := ⟨assume x y h, let ⟨i, hi⟩ := not_forall.mp (mt funext h) in separated_by_f (λz, z i) (infi_le _ i) hi⟩ lemma is_closed_diagonal [t2_space α] : is_closed {p:α×α | p.1 = p.2} := is_closed_iff_nhds.mpr $ assume ⟨a₁, a₂⟩ h, eq_of_nhds_neq_bot $ assume : nhds a₁ ⊓ nhds a₂ = ⊥, h $ let ⟨t₁, ht₁, t₂, ht₂, (h' : t₁ ∩ t₂ ⊆ ∅)⟩ := by rw [←empty_in_sets_eq_bot, mem_inf_sets] at this; exact this in begin change t₁ ∈ nhds a₁ at ht₁, change t₂ ∈ nhds a₂ at ht₂, rw [nhds_prod_eq, ←empty_in_sets_eq_bot], apply filter.sets_of_superset, apply inter_mem_inf_sets (prod_mem_prod ht₁ ht₂) (mem_principal_sets.mpr (subset.refl _)), exact assume ⟨x₁, x₂⟩ ⟨⟨hx₁, hx₂⟩, (heq : x₁ = x₂)⟩, show false, from @h' x₁ ⟨hx₁, heq.symm ▸ hx₂⟩ end variables [topological_space β] lemma is_closed_eq [t2_space α] {f g : β → α} (hf : continuous f) (hg : continuous g) : is_closed {x:β | f x = g x} := continuous_iff_is_closed.mp (hf.prod_mk hg) _ is_closed_diagonal lemma diagonal_eq_range_diagonal_map {α : Type*} : {p:α×α | p.1 = p.2} = range (λx, (x,x)) := ext $ assume p, iff.intro (assume h, ⟨p.1, prod.ext_iff.2 ⟨rfl, h⟩⟩) (assume ⟨x, hx⟩, show p.1 = p.2, by rw ←hx) lemma prod_subset_compl_diagonal_iff_disjoint {α : Type*} {s t : set α} : set.prod s t ⊆ - {p:α×α | p.1 = p.2} ↔ s ∩ t = ∅ := by rw [eq_empty_iff_forall_not_mem, subset_compl_comm, diagonal_eq_range_diagonal_map, range_subset_iff]; simp lemma compact_compact_separated [t2_space α] {s t : set α} (hs : compact s) (ht : compact t) (hst : s ∩ t = ∅) : ∃u v : set α, is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ u ∩ v = ∅ := by simp only [prod_subset_compl_diagonal_iff_disjoint.symm] at ⊢ hst; exact generalized_tube_lemma hs ht is_closed_diagonal hst lemma closed_of_compact [t2_space α] (s : set α) (hs : compact s) : is_closed s := is_open_compl_iff.mpr $ is_open_iff_forall_mem_open.mpr $ assume x hx, let ⟨u, v, uo, vo, su, xv, uv⟩ := compact_compact_separated hs (compact_singleton : compact {x}) (by rwa [inter_comm, ←subset_compl_iff_disjoint, singleton_subset_iff]) in have v ⊆ -s, from subset_compl_comm.mp (subset.trans su (subset_compl_iff_disjoint.mpr uv)), ⟨v, this, vo, by simpa using xv⟩ lemma locally_compact_of_compact_nhds [t2_space α] (h : ∀ x : α, ∃ s, s ∈ nhds x ∧ compact s) : locally_compact_space α := ⟨assume x n hn, let ⟨u, un, uo, xu⟩ := mem_nhds_sets_iff.mp hn in let ⟨k, kx, kc⟩ := h x in -- K is compact but not necessarily contained in N. -- K \ U is again compact and doesn't contain x, so -- we may find open sets V, W separating x from K \ U. -- Then K \ W is a compact neighborhood of x contained in U. let ⟨v, w, vo, wo, xv, kuw, vw⟩ := compact_compact_separated compact_singleton (compact_diff kc uo) (by rw [singleton_inter_eq_empty]; exact λ h, h.2 xu) in have wn : -w ∈ nhds x, from mem_nhds_sets_iff.mpr ⟨v, subset_compl_iff_disjoint.mpr vw, vo, singleton_subset_iff.mp xv⟩, ⟨k - w, filter.inter_mem_sets kx wn, subset.trans (diff_subset_comm.mp kuw) un, compact_diff kc wo⟩⟩ instance locally_compact_of_compact [t2_space α] [compact_space α] : locally_compact_space α := locally_compact_of_compact_nhds (assume x, ⟨univ, mem_nhds_sets is_open_univ trivial, compact_univ⟩) end separation section regularity /-- A T₃ space, also known as a regular space (although this condition sometimes omits T₂), is one in which for every closed `C` and `x ∉ C`, there exist disjoint open sets containing `x` and `C` respectively. -/ class regular_space (α : Type u) [topological_space α] extends t1_space α : Prop := (regular : ∀{s:set α} {a}, is_closed s → a ∉ s → ∃t, is_open t ∧ s ⊆ t ∧ nhds a ⊓ principal t = ⊥) lemma nhds_is_closed [regular_space α] {a : α} {s : set α} (h : s ∈ nhds a) : ∃t∈(nhds a), t ⊆ s ∧ is_closed t := let ⟨s', h₁, h₂, h₃⟩ := mem_nhds_sets_iff.mp h in have ∃t, is_open t ∧ -s' ⊆ t ∧ nhds a ⊓ principal t = ⊥, from regular_space.regular (is_closed_compl_iff.mpr h₂) (not_not_intro h₃), let ⟨t, ht₁, ht₂, ht₃⟩ := this in ⟨-t, mem_sets_of_neq_bot $ by rwa [lattice.neg_neg], subset.trans (compl_subset_comm.1 ht₂) h₁, is_closed_compl_iff.mpr ht₁⟩ variable (α) instance regular_space.t2_space [regular_space α] : t2_space α := ⟨λ x y hxy, let ⟨s, hs, hys, hxs⟩ := regular_space.regular is_closed_singleton (mt mem_singleton_iff.1 hxy), ⟨t, hxt, u, hsu, htu⟩ := empty_in_sets_eq_bot.2 hxs, ⟨v, hvt, hv, hxv⟩ := mem_nhds_sets_iff.1 hxt in ⟨v, s, hv, hs, hxv, singleton_subset_iff.1 hys, eq_empty_of_subset_empty $ λ z ⟨hzv, hzs⟩, htu ⟨hvt hzv, hsu hzs⟩⟩⟩ end regularity section normality /-- A T₄ space, also known as a normal space (although this condition sometimes omits T₂), is one in which for every pair of disjoint closed sets `C` and `D`, there exist disjoint open sets containing `C` and `D` respectively. -/ class normal_space (α : Type u) [topological_space α] extends t1_space α : Prop := (normal : ∀ s t : set α, is_closed s → is_closed t → disjoint s t → ∃ u v, is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ disjoint u v) theorem normal_separation [normal_space α] (s t : set α) (H1 : is_closed s) (H2 : is_closed t) (H3 : disjoint s t) : ∃ u v, is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ disjoint u v := normal_space.normal s t H1 H2 H3 instance normal_space.regular_space [normal_space α] : regular_space α := { regular := λ s x hs hxs, let ⟨u, v, hu, hv, hsu, hxv, huv⟩ := normal_separation s {x} hs is_closed_singleton (λ _ ⟨hx, hy⟩, hxs $ set.mem_of_eq_of_mem (set.eq_of_mem_singleton hy).symm hx) in ⟨u, hu, hsu, filter.empty_in_sets_eq_bot.1 $ filter.mem_inf_sets.2 ⟨v, mem_nhds_sets hv (set.singleton_subset_iff.1 hxv), u, filter.mem_principal_self u, set.inter_comm u v ▸ huv⟩⟩ } -- We can't make this an instance because it could cause an instance loop. lemma normal_of_compact_t2 [compact_space α] [t2_space α] : normal_space α := begin refine ⟨assume s t hs ht st, _⟩, simp only [disjoint_iff], exact compact_compact_separated (compact_of_closed hs) (compact_of_closed ht) st.eq_bot end end normality
5afc3ecb1638f8fdb86788cce299244d4dc1e4c0
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Elab/PreDefinition/Structural/SmartUnfolding.lean
ed15a4d5a8c40e4565d9106375b3f9295571ab44
[ "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
3,200
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.PreDefinition.Basic import Lean.Elab.PreDefinition.Structural.Basic namespace Lean.Elab.Structural open Meta partial def addSmartUnfoldingDefAux (preDef : PreDefinition) (recArgPos : Nat) : MetaM PreDefinition := do return { preDef with declName := mkSmartUnfoldingNameFor preDef.declName value := (← visit preDef.value) modifiers := {} } where /-- Auxiliary method for annotating `match`-alternatives with `markSmartUnfoldingMatch` and `markSmartUnfoldigMatchAlt`. It uses the following approach: - Whenever it finds a `match` application `e` s.t. `recArgHasLooseBVarsAt preDef.declName recArgPos e`, it marks the `match` with `markSmartUnfoldingMatch`, and each alternative that does not contain a nested marked `match` is marked with `markSmartUnfoldigMatchAlt`. Recall that the condition `recArgHasLooseBVarsAt preDef.declName recArgPos e` is the one used at `mkBRecOn`. -/ visit (e : Expr) : MetaM Expr := do match e with | Expr.lam .. => lambdaTelescope e fun xs b => do mkLambdaFVars xs (← visit b) | Expr.forallE .. => forallTelescope e fun xs b => do mkForallFVars xs (← visit b) | Expr.letE n type val body _ => withLetDecl n type (← visit val) fun x => do mkLetFVars #[x] (← visit (body.instantiate1 x)) | Expr.mdata d b _ => return mkMData d (← visit b) | Expr.proj n i s _ => return mkProj n i (← visit s) | Expr.app .. => let processApp (e : Expr) : MetaM Expr := e.withApp fun f args => return mkAppN (← visit f) (← args.mapM visit) match (← matchMatcherApp? e) with | some matcherApp => if !recArgHasLooseBVarsAt preDef.declName recArgPos e then processApp e else let mut altsNew := #[] for alt in matcherApp.alts, numParams in matcherApp.altNumParams do let altNew ← lambdaTelescope alt fun xs altBody => do unless xs.size >= numParams do throwError "unexpected matcher application alternative{indentExpr alt}\nat application{indentExpr e}" let altBody ← visit altBody let containsSUnfoldMatch := Option.isSome <| altBody.find? fun e => smartUnfoldingMatch? e |>.isSome if !containsSUnfoldMatch then let altBody ← mkLambdaFVars xs[numParams:xs.size] altBody let altBody ← markSmartUnfoldigMatchAlt altBody mkLambdaFVars xs[0:numParams] altBody else mkLambdaFVars xs altBody altsNew := altsNew.push altNew return markSmartUnfoldingMatch { matcherApp with alts := altsNew }.toExpr | _ => processApp e | _ => return e partial def addSmartUnfoldingDef (preDef : PreDefinition) (recArgPos : Nat) : TermElabM Unit := do if (← isProp preDef.type) then return () else let preDefSUnfold ← addSmartUnfoldingDefAux preDef recArgPos addNonRec preDefSUnfold end Lean.Elab.Structural
f969f52529a0b6bb8dde465ca07b4963f6dc22c2
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/normed_space/conformal_linear_map.lean
a711a152372cbf43b105f643e30e795ffd74fd74
[ "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,688
lean
/- Copyright (c) 2021 Yourong Zang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yourong Zang -/ import analysis.normed_space.basic import analysis.normed_space.linear_isometry /-! # Conformal Linear Maps > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. A continuous linear map between `R`-normed spaces `X` and `Y` `is_conformal_map` if it is a nonzero multiple of a linear isometry. ## Main definitions * `is_conformal_map`: the main definition of conformal linear maps ## Main results * The conformality of the composition of two conformal linear maps, the identity map and multiplications by nonzero constants as continuous linear maps * `is_conformal_map_of_subsingleton`: all continuous linear maps on singleton spaces are conformal * `is_conformal_map.preserves_angle`: if a continuous linear map is conformal, then it preserves all angles in the normed space See `analysis.normed_space.conformal_linear_map.inner_product` for * `is_conformal_map_iff`: a map between inner product spaces is conformal iff it preserves inner products up to a fixed scalar factor. ## Tags conformal ## Warning The definition of conformality in this file does NOT require the maps to be orientation-preserving. -/ noncomputable theory open function linear_isometry continuous_linear_map /-- A continuous linear map `f'` is said to be conformal if it's a nonzero multiple of a linear isometry. -/ def is_conformal_map {R : Type*} {X Y : Type*} [normed_field R] [seminormed_add_comm_group X] [seminormed_add_comm_group Y] [normed_space R X] [normed_space R Y] (f' : X →L[R] Y) := ∃ (c : R) (hc : c ≠ 0) (li : X →ₗᵢ[R] Y), f' = c • li.to_continuous_linear_map variables {R M N G M' : Type*} [normed_field R] [seminormed_add_comm_group M] [seminormed_add_comm_group N] [seminormed_add_comm_group G] [normed_space R M] [normed_space R N] [normed_space R G] [normed_add_comm_group M'] [normed_space R M'] {f : M →L[R] N} {g : N →L[R] G} {c : R} lemma is_conformal_map_id : is_conformal_map (id R M) := ⟨1, one_ne_zero, id, by simp⟩ lemma is_conformal_map.smul (hf : is_conformal_map f) {c : R} (hc : c ≠ 0) : is_conformal_map (c • f) := begin rcases hf with ⟨c', hc', li, rfl⟩, exact ⟨c * c', mul_ne_zero hc hc', li, smul_smul _ _ _⟩ end lemma is_conformal_map_const_smul (hc : c ≠ 0) : is_conformal_map (c • id R M) := is_conformal_map_id.smul hc protected lemma linear_isometry.is_conformal_map (f' : M →ₗᵢ[R] N) : is_conformal_map f'.to_continuous_linear_map := ⟨1, one_ne_zero, f', (one_smul _ _).symm⟩ @[nontriviality] lemma is_conformal_map_of_subsingleton [subsingleton M] (f' : M →L[R] N) : is_conformal_map f' := ⟨1, one_ne_zero, ⟨0, λ x, by simp [subsingleton.elim x 0]⟩, subsingleton.elim _ _⟩ namespace is_conformal_map lemma comp (hg : is_conformal_map g) (hf : is_conformal_map f) : is_conformal_map (g.comp f) := begin rcases hf with ⟨cf, hcf, lif, rfl⟩, rcases hg with ⟨cg, hcg, lig, rfl⟩, refine ⟨cg * cf, mul_ne_zero hcg hcf, lig.comp lif, _⟩, rw [smul_comp, comp_smul, mul_smul], refl end protected lemma injective {f : M' →L[R] N} (h : is_conformal_map f) : function.injective f := by { rcases h with ⟨c, hc, li, rfl⟩, exact (smul_right_injective _ hc).comp li.injective } lemma ne_zero [nontrivial M'] {f' : M' →L[R] N} (hf' : is_conformal_map f') : f' ≠ 0 := begin rintro rfl, rcases exists_ne (0 : M') with ⟨a, ha⟩, exact ha (hf'.injective rfl) end end is_conformal_map
85c747ac6e4be121a7d54da9ea873eb404ac244e
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/order/ideal.lean
88be666126f21ce0209ea51b23998ac36a7194ec
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
7,738
lean
/- Copyright (c) 2020 David Wärn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Wärn -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.order.basic import Mathlib.data.equiv.encodable.basic import Mathlib.PostPort universes u_2 l u_1 namespace Mathlib /-! # Order ideals, cofinal sets, and the Rasiowa–Sikorski lemma ## Main definitions Throughout this file, `P` is at least a preorder, but some sections require more structure, such as a bottom element, a top element, or a join-semilattice structure. - `ideal P`: the type of upward directed, downward closed subsets of `P`. Dual to the notion of a filter on a preorder. - `cofinal P`: the type of subsets of `P` containing arbitrarily large elements. Dual to the notion of 'dense set' used in forcing. - `ideal_of_cofinals p 𝒟`, where `p : P`, and `𝒟` is a countable family of cofinal subsets of P: an ideal in `P` which contains `p` and intersects every set in `𝒟`. ## References - https://en.wikipedia.org/wiki/Ideal_(order_theory) - https://en.wikipedia.org/wiki/Cofinal_(mathematics) - https://en.wikipedia.org/wiki/Rasiowa–Sikorski_lemma Note that for the Rasiowa–Sikorski lemma, Wikipedia uses the opposite ordering on `P`, in line with most presentations of forcing. ## Tags ideal, cofinal, dense, countable, generic -/ namespace order /-- An ideal on a preorder `P` is a subset of `P` that is - nonempty - upward directed - downward closed. -/ structure ideal (P : Type u_2) [preorder P] where carrier : set P nonempty : set.nonempty carrier directed : directed_on LessEq carrier mem_of_le : ∀ {x y : P}, x ≤ y → y ∈ carrier → x ∈ carrier namespace ideal /-- The smallest ideal containing a given element. -/ def principal {P : Type u_1} [preorder P] (p : P) : ideal P := mk (set_of fun (x : P) => x ≤ p) sorry sorry sorry protected instance inhabited {P : Type u_1} [preorder P] [Inhabited P] : Inhabited (ideal P) := { default := principal Inhabited.default } /-- An ideal of `P` can be viewed as a subset of `P`. -/ protected instance set.has_coe {P : Type u_1} [preorder P] : has_coe (ideal P) (set P) := has_coe.mk carrier /-- For the notation `x ∈ I`. -/ protected instance has_mem {P : Type u_1} [preorder P] : has_mem P (ideal P) := has_mem.mk fun (x : P) (I : ideal P) => x ∈ ↑I /-- Two ideals are equal when their underlying sets are equal. -/ theorem ext {P : Type u_1} [preorder P] (I : ideal P) (J : ideal P) : ↑I = ↑J → I = J := sorry /-- The partial ordering by subset inclusion, inherited from `set P`. -/ protected instance partial_order {P : Type u_1} [preorder P] : partial_order (ideal P) := partial_order.lift coe ext theorem mem_of_mem_of_le {P : Type u_1} [preorder P] {x : P} {I : ideal P} {J : ideal P} : x ∈ I → I ≤ J → x ∈ J := set.mem_of_mem_of_subset @[simp] theorem principal_le_iff {P : Type u_1} [preorder P] {x : P} {I : ideal P} : principal x ≤ I ↔ x ∈ I := { mp := fun (h : ∀ {y : P}, y ≤ x → y ∈ I) => h (le_refl x), mpr := fun (h_mem : x ∈ I) (y : P) (h_le : y ≤ x) => mem_of_le I h_le h_mem } /-- A specific witness of `I.nonempty` when `P` has a bottom element. -/ @[simp] theorem bot_mem {P : Type u_1} [order_bot P] {I : ideal P} : ⊥ ∈ I := mem_of_le I bot_le (set.nonempty.some_mem (nonempty I)) /-- There is a bottom ideal when `P` has a bottom element. -/ protected instance order_bot {P : Type u_1} [order_bot P] : order_bot (ideal P) := order_bot.mk (principal ⊥) partial_order.le partial_order.lt sorry sorry sorry sorry /-- There is a top ideal when `P` has a top element. -/ protected instance order_top {P : Type u_1} [order_top P] : order_top (ideal P) := order_top.mk (principal ⊤) partial_order.le partial_order.lt sorry sorry sorry sorry /-- A specific witness of `I.directed` when `P` has joins. -/ theorem sup_mem {P : Type u_1} [semilattice_sup P] {I : ideal P} (x : P) (y : P) (H : x ∈ I) : y ∈ I → x ⊔ y ∈ I := sorry @[simp] theorem sup_mem_iff {P : Type u_1} [semilattice_sup P] {x : P} {y : P} {I : ideal P} : x ⊔ y ∈ I ↔ x ∈ I ∧ y ∈ I := { mp := fun (h : x ⊔ y ∈ I) => { left := mem_of_le I le_sup_left h, right := mem_of_le I le_sup_right h }, mpr := fun (h : x ∈ I ∧ y ∈ I) => sup_mem x y (and.left h) (and.right h) } end ideal /-- For a preorder `P`, `cofinal P` is the type of subsets of `P` containing arbitrarily large elements. They are the dense sets in the topology whose open sets are terminal segments. -/ structure cofinal (P : Type u_2) [preorder P] where carrier : set P mem_gt : ∀ (x : P), ∃ (y : P), ∃ (H : y ∈ carrier), x ≤ y namespace cofinal protected instance inhabited {P : Type u_1} [preorder P] : Inhabited (cofinal P) := { default := mk set.univ sorry } protected instance has_mem {P : Type u_1} [preorder P] : has_mem P (cofinal P) := has_mem.mk fun (x : P) (D : cofinal P) => x ∈ carrier D /-- A (noncomputable) element of a cofinal set lying above a given element. -/ def above {P : Type u_1} [preorder P] (D : cofinal P) (x : P) : P := classical.some (mem_gt D x) theorem above_mem {P : Type u_1} [preorder P] (D : cofinal P) (x : P) : above D x ∈ D := exists.elim (classical.some_spec (mem_gt D x)) fun (a : classical.some (mem_gt D x) ∈ carrier D) (_x : x ≤ classical.some (mem_gt D x)) => a theorem le_above {P : Type u_1} [preorder P] (D : cofinal P) (x : P) : x ≤ above D x := exists.elim (classical.some_spec (mem_gt D x)) fun (_x : classical.some (mem_gt D x) ∈ carrier D) (b : x ≤ classical.some (mem_gt D x)) => b end cofinal /-- Given a starting point, and a countable family of cofinal sets, this is an increasing sequence that intersects each cofinal set. -/ def sequence_of_cofinals {P : Type u_1} [preorder P] (p : P) {ι : Type u_2} [encodable ι] (𝒟 : ι → cofinal P) : ℕ → P := sorry theorem sequence_of_cofinals.monotone {P : Type u_1} [preorder P] (p : P) {ι : Type u_2} [encodable ι] (𝒟 : ι → cofinal P) : monotone (sequence_of_cofinals p 𝒟) := sorry theorem sequence_of_cofinals.encode_mem {P : Type u_1} [preorder P] (p : P) {ι : Type u_2} [encodable ι] (𝒟 : ι → cofinal P) (i : ι) : sequence_of_cofinals p 𝒟 (encodable.encode i + 1) ∈ 𝒟 i := sorry /-- Given an element `p : P` and a family `𝒟` of cofinal subsets of a preorder `P`, indexed by a countable type, `ideal_of_cofinals p 𝒟` is an ideal in `P` which - contains `p`, according to `mem_ideal_of_cofinals p 𝒟`, and - intersects every set in `𝒟`, according to `cofinal_meets_ideal_of_cofinals p 𝒟`. This proves the Rasiowa–Sikorski lemma. -/ def ideal_of_cofinals {P : Type u_1} [preorder P] (p : P) {ι : Type u_2} [encodable ι] (𝒟 : ι → cofinal P) : ideal P := ideal.mk (set_of fun (x : P) => ∃ (n : ℕ), x ≤ sequence_of_cofinals p 𝒟 n) sorry sorry sorry theorem mem_ideal_of_cofinals {P : Type u_1} [preorder P] (p : P) {ι : Type u_2} [encodable ι] (𝒟 : ι → cofinal P) : p ∈ ideal_of_cofinals p 𝒟 := Exists.intro 0 (le_refl p) /-- `ideal_of_cofinals p 𝒟` is `𝒟`-generic. -/ theorem cofinal_meets_ideal_of_cofinals {P : Type u_1} [preorder P] (p : P) {ι : Type u_2} [encodable ι] (𝒟 : ι → cofinal P) (i : ι) : ∃ (x : P), x ∈ 𝒟 i ∧ x ∈ ideal_of_cofinals p 𝒟 := Exists.intro (sequence_of_cofinals p 𝒟 (encodable.encode i + 1)) { left := sequence_of_cofinals.encode_mem p 𝒟 i, right := Exists.intro (encodable.encode i + 1) (le_refl (sequence_of_cofinals p 𝒟 (encodable.encode i + 1))) }
b471a5d976eb755532405522e3c06543227e3a25
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/category_theory/limits/cones.lean
891c6f306ecf1dd10a9c328a3940b91dd529615f
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
11,068
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.whiskering import category_theory.const import category_theory.opposites import category_theory.yoneda universes v u u' -- declare the `v`'s first; see `category_theory.category` for an explanation open category_theory -- There is an awkward difficulty with universes here. -- If we allowed `J` to be a small category in `Prop`, we'd run into trouble -- because `yoneda.obj (F : (J ⥤ C)ᵒᵖ)` will be a functor into `Sort (max v 1)`, -- not into `Sort v`. -- So we don't allow this case; it's not particularly useful anyway. variables {J : Type v} [small_category J] variables {C : Sort u} [𝒞 : category.{v+1} C] include 𝒞 open category_theory open category_theory.category open category_theory.functor namespace category_theory namespace functor variables {J C} (F : J ⥤ C) /-- `F.cones` is the functor assigning to an object `X` the type of natural transformations from the constant functor with value `X` to `F`. An object representing this functor is a limit of `F`. -/ def cones : Cᵒᵖ ⥤ Type v := (const J).op ⋙ (yoneda.obj F) lemma cones_obj (X : Cᵒᵖ) : F.cones.obj X = ((const J).obj (unop X) ⟶ F) := rfl @[simp] lemma cones_map_app {X₁ X₂ : Cᵒᵖ} (f : X₁ ⟶ X₂) (t : F.cones.obj X₁) (j : J) : (F.cones.map f t).app j = f.unop ≫ t.app j := rfl /-- `F.cocones` is the functor assigning to an object `X` the type of natural transformations from `F` to the constant functor with value `X`. An object corepresenting this functor is a colimit of `F`. -/ def cocones : C ⥤ Type v := const J ⋙ coyoneda.obj (op F) lemma cocones_obj (X : C) : F.cocones.obj X = (F ⟶ (const J).obj X) := rfl @[simp] lemma cocones_map_app {X₁ X₂ : C} (f : X₁ ⟶ X₂) (t : F.cocones.obj X₁) (j : J) : (F.cocones.map f t).app j = t.app j ≫ f := rfl end functor section variables (J C) def cones : (J ⥤ C) ⥤ (Cᵒᵖ ⥤ Type v) := { obj := functor.cones, map := λ F G f, whisker_left (const J).op (yoneda.map f) } def cocones : (J ⥤ C)ᵒᵖ ⥤ (C ⥤ Type v) := { obj := λ F, functor.cocones (unop F), map := λ F G f, whisker_left (const J) (coyoneda.map f) } variables {J C} @[simp] lemma cones_obj (F : J ⥤ C) : (cones J C).obj F = F.cones := rfl @[simp] lemma cones_map {F G : J ⥤ C} {f : F ⟶ G} : (cones J C).map f = (whisker_left (const J).op (yoneda.map f)) := rfl @[simp] lemma cocones_obj (F : (J ⥤ C)ᵒᵖ) : (cocones J C).obj F = (unop F).cocones := rfl @[simp] lemma cocones_map {F G : (J ⥤ C)ᵒᵖ} {f : F ⟶ G} : (cocones J C).map f = (whisker_left (const J) (coyoneda.map f)) := rfl end namespace limits /-- A `c : cone F` is: * an object `c.X` and * a natural transformation `c.π : c.X ⟶ F` from the constant `c.X` functor to `F`. `cone F` is equivalent, in the obvious way, to `Σ X, F.cones.obj X`. -/ structure cone (F : J ⥤ C) := (X : C) (π : (const J).obj X ⟶ F) @[simp] lemma cone.w {F : J ⥤ C} (c : cone F) {j j' : J} (f : j ⟶ j') : c.π.app j ≫ F.map f = c.π.app j' := by convert ←(c.π.naturality f).symm; apply id_comp /-- A `c : cocone F` is * an object `c.X` and * a natural transformation `c.ι : F ⟶ c.X` from `F` to the constant `c.X` functor. `cocone F` is equivalent, in the obvious way, to `Σ X, F.cocones.obj X`. -/ structure cocone (F : J ⥤ C) := (X : C) (ι : F ⟶ (const J).obj X) @[simp] lemma cocone.w {F : J ⥤ C} (c : cocone F) {j j' : J} (f : j ⟶ j') : F.map f ≫ c.ι.app j' = c.ι.app j := by convert ←(c.ι.naturality f); apply comp_id variables {F : J ⥤ C} namespace cone @[simp] def extensions (c : cone F) : yoneda.obj c.X ⟶ F.cones := { app := λ X f, ((const J).map f) ≫ c.π } /-- A map to the vertex of a cone induces a cone by composition. -/ @[simp] def extend (c : cone F) {X : C} (f : X ⟶ c.X) : cone F := { X := X, π := c.extensions.app (op X) f } @[simp] lemma extend_π (c : cone F) {X : Cᵒᵖ} (f : unop X ⟶ c.X) : (extend c f).π = c.extensions.app X f := rfl def whisker {K : Type v} [small_category K] (E : K ⥤ J) (c : cone F) : cone (E ⋙ F) := { X := c.X, π := whisker_left E c.π } @[simp] lemma whisker_π_app (c : cone F) {K : Type v} [small_category K] (E : K ⥤ J) (k : K) : (c.whisker E).π.app k = (c.π).app (E.obj k) := rfl end cone namespace cocone @[simp] def extensions (c : cocone F) : coyoneda.obj (op c.X) ⟶ F.cocones := { app := λ X f, c.ι ≫ ((const J).map f) } /-- A map from the vertex of a cocone induces a cocone by composition. -/ @[simp] def extend (c : cocone F) {X : C} (f : c.X ⟶ X) : cocone F := { X := X, ι := c.extensions.app X f } @[simp] lemma extend_ι (c : cocone F) {X : C} (f : c.X ⟶ X) : (extend c f).ι = c.extensions.app X f := rfl def whisker {K : Type v} [small_category K] (E : K ⥤ J) (c : cocone F) : cocone (E ⋙ F) := { X := c.X, ι := whisker_left E c.ι } @[simp] lemma whisker_ι_app (c : cocone F) {K : Type v} [small_category K] (E : K ⥤ J) (k : K) : (c.whisker E).ι.app k = (c.ι).app (E.obj k) := rfl end cocone structure cone_morphism (A B : cone F) := (hom : A.X ⟶ B.X) (w' : ∀ j : J, hom ≫ B.π.app j = A.π.app j . obviously) restate_axiom cone_morphism.w' attribute [simp] cone_morphism.w @[extensionality] lemma cone_morphism.ext {A B : cone F} {f g : cone_morphism A B} (w : f.hom = g.hom) : f = g := by cases f; cases g; simpa using w instance cone.category : category.{v+1} (cone F) := { hom := λ A B, cone_morphism A B, comp := λ X Y Z f g, { hom := f.hom ≫ g.hom, w' := by intro j; rw [assoc, g.w, f.w] }, id := λ B, { hom := 𝟙 B.X } } namespace cones @[simp] lemma id.hom (c : cone F) : (𝟙 c : cone_morphism c c).hom = 𝟙 (c.X) := rfl @[simp] lemma comp.hom {c d e : cone F} (f : c ⟶ d) (g : d ⟶ e) : (f ≫ g).hom = f.hom ≫ g.hom := rfl /-- To give an isomorphism between cones, it suffices to give an isomorphism between their vertices which commutes with the cone maps. -/ @[extensionality] def ext {c c' : cone F} (φ : c.X ≅ c'.X) (w : ∀ j, c.π.app j = φ.hom ≫ c'.π.app j) : c ≅ c' := { hom := { hom := φ.hom }, inv := { hom := φ.inv, w' := λ j, φ.inv_comp_eq.mpr (w j) } } def postcompose {G : J ⥤ C} (α : F ⟶ G) : cone F ⥤ cone G := { obj := λ c, { X := c.X, π := c.π ≫ α }, map := λ c₁ c₂ f, { hom := f.hom, w' := by intro; erw ← category.assoc; simp [-category.assoc] } } @[simp] lemma postcompose_obj_X {G : J ⥤ C} (α : F ⟶ G) (c : cone F) : ((postcompose α).obj c).X = c.X := rfl @[simp] lemma postcompose_obj_π {G : J ⥤ C} (α : F ⟶ G) (c : cone F) : ((postcompose α).obj c).π = c.π ≫ α := rfl @[simp] lemma postcompose_map_hom {G : J ⥤ C} (α : F ⟶ G) {c₁ c₂ : cone F} (f : c₁ ⟶ c₂): ((postcompose α).map f).hom = f.hom := rfl def forget : cone F ⥤ C := { obj := λ t, t.X, map := λ s t f, f.hom } @[simp] lemma forget_obj {t : cone F} : forget.obj t = t.X := rfl @[simp] lemma forget_map {s t : cone F} {f : s ⟶ t} : forget.map f = f.hom := rfl section variables {D : Sort u'} [𝒟 : category.{v+1} D] include 𝒟 @[simp] def functoriality (G : C ⥤ D) : cone F ⥤ cone (F ⋙ G) := { obj := λ A, { X := G.obj A.X, π := { app := λ j, G.map (A.π.app j), naturality' := by intros; erw ←G.map_comp; tidy } }, map := λ X Y f, { hom := G.map f.hom, w' := by intros; rw [←functor.map_comp, f.w] } } end end cones structure cocone_morphism (A B : cocone F) := (hom : A.X ⟶ B.X) (w' : ∀ j : J, A.ι.app j ≫ hom = B.ι.app j . obviously) restate_axiom cocone_morphism.w' attribute [simp] cocone_morphism.w @[extensionality] lemma cocone_morphism.ext {A B : cocone F} {f g : cocone_morphism A B} (w : f.hom = g.hom) : f = g := by cases f; cases g; simpa using w instance cocone.category : category.{v+1} (cocone F) := { hom := λ A B, cocone_morphism A B, comp := λ _ _ _ f g, { hom := f.hom ≫ g.hom, w' := by intro j; rw [←assoc, f.w, g.w] }, id := λ B, { hom := 𝟙 B.X } } namespace cocones @[simp] lemma id.hom (c : cocone F) : (𝟙 c : cocone_morphism c c).hom = 𝟙 (c.X) := rfl @[simp] lemma comp.hom {c d e : cocone F} (f : c ⟶ d) (g : d ⟶ e) : (f ≫ g).hom = f.hom ≫ g.hom := rfl /-- To give an isomorphism between cocones, it suffices to give an isomorphism between their vertices which commutes with the cocone maps. -/ @[extensionality] def ext {c c' : cocone F} (φ : c.X ≅ c'.X) (w : ∀ j, c.ι.app j ≫ φ.hom = c'.ι.app j) : c ≅ c' := { hom := { hom := φ.hom }, inv := { hom := φ.inv, w' := λ j, φ.comp_inv_eq.mpr (w j).symm } } def precompose {G : J ⥤ C} (α : G ⟶ F) : cocone F ⥤ cocone G := { obj := λ c, { X := c.X, ι := α ≫ c.ι }, map := λ c₁ c₂ f, { hom := f.hom } } @[simp] lemma precompose_obj_X {G : J ⥤ C} (α : G ⟶ F) (c : cocone F) : ((precompose α).obj c).X = c.X := rfl @[simp] lemma precompose_obj_ι {G : J ⥤ C} (α : G ⟶ F) (c : cocone F) : ((precompose α).obj c).ι = α ≫ c.ι := rfl @[simp] lemma precompose_map_hom {G : J ⥤ C} (α : G ⟶ F) {c₁ c₂ : cocone F} (f : c₁ ⟶ c₂) : ((precompose α).map f).hom = f.hom := rfl def forget : cocone F ⥤ C := { obj := λ t, t.X, map := λ s t f, f.hom } @[simp] lemma forget_obj {t : cocone F} : forget.obj t = t.X := rfl @[simp] lemma forget_map {s t : cocone F} {f : s ⟶ t} : forget.map f = f.hom := rfl section variables {D : Sort u'} [𝒟 : category.{v+1} D] include 𝒟 @[simp] def functoriality (G : C ⥤ D) : cocone F ⥤ cocone (F ⋙ G) := { obj := λ A, { X := G.obj A.X, ι := { app := λ j, G.map (A.ι.app j), naturality' := by intros; erw ←G.map_comp; tidy } }, map := λ _ _ f, { hom := G.map f.hom, w' := by intros; rw [←functor.map_comp, cocone_morphism.w] } } end end cocones end limits namespace functor variables {D : Sort u'} [category.{v+1} D] variables {F : J ⥤ C} {G : J ⥤ C} (H : C ⥤ D) open category_theory.limits /-- The image of a cone in C under a functor G : C ⥤ D is a cone in D. -/ def map_cone (c : cone F) : cone (F ⋙ H) := (cones.functoriality H).obj c /-- The image of a cocone in C under a functor G : C ⥤ D is a cocone in D. -/ def map_cocone (c : cocone F) : cocone (F ⋙ H) := (cocones.functoriality H).obj c def map_cone_morphism {c c' : cone F} (f : cone_morphism c c') : cone_morphism (H.map_cone c) (H.map_cone c') := (cones.functoriality H).map f def map_cocone_morphism {c c' : cocone F} (f : cocone_morphism c c') : cocone_morphism (H.map_cocone c) (H.map_cocone c') := (cocones.functoriality H).map f @[simp] lemma map_cone_π (c : cone F) (j : J) : (map_cone H c).π.app j = H.map (c.π.app j) := rfl @[simp] lemma map_cocone_ι (c : cocone F) (j : J) : (map_cocone H c).ι.app j = H.map (c.ι.app j) := rfl end functor end category_theory
95423e1ce179a5349a97ad8913ce740339b129a0
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/playground/rand.lean
3322b24c25d1fe6caaa3a98b8ebfcb5c1910aef4
[ "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
196
lean
def main (xs : List String) : IO Unit := do [seed, n] ← pure (xs.map String.toNat) | throw "invalid number of arguments", IO.setRandSeed seed, n.mfor $ λ _, IO.rand 0 1000 >>= IO.println
899bb13754845b2ea19871bb32d766a4f73511ca
46125763b4dbf50619e8846a1371029346f4c3db
/src/topology/separation.lean
84767741e6824f3eadbbe97b7967fb2f01f1a35e
[ "Apache-2.0" ]
permissive
thjread/mathlib
a9d97612cedc2c3101060737233df15abcdb9eb1
7cffe2520a5518bba19227a107078d83fa725ddc
refs/heads/master
1,615,637,696,376
1,583,953,063,000
1,583,953,063,000
246,680,271
0
0
Apache-2.0
1,583,960,875,000
1,583,960,875,000
null
UTF-8
Lean
false
false
16,752
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 Separation properties of topological spaces. -/ import topology.subset_properties open set filter lattice open_locale topological_space local attribute [instance] classical.prop_decidable -- TODO: use "open_locale classical" universes u v variables {α : Type u} {β : Type v} [topological_space α] section separation /-- A T₀ space, also known as a Kolmogorov space, is a topological space where for every pair `x ≠ y`, there is an open set containing one but not the other. -/ class t0_space (α : Type u) [topological_space α] : Prop := (t0 : ∀ x y, x ≠ y → ∃ U:set α, is_open U ∧ (xor (x ∈ U) (y ∈ U))) theorem exists_open_singleton_of_fintype [t0_space α] [f : fintype α] [decidable_eq α] [ha : nonempty α] : ∃ x:α, is_open ({x}:set α) := have H : ∀ (T : finset α), T ≠ ∅ → ∃ x ∈ T, ∃ u, is_open u ∧ {x} = {y | y ∈ T} ∩ u := begin intro T, apply finset.case_strong_induction_on T, { intro h, exact (h rfl).elim }, { intros x S hxS ih h, by_cases hs : S = ∅, { existsi [x, finset.mem_insert_self x S, univ, is_open_univ], rw [hs, inter_univ], refl }, { rcases ih S (finset.subset.refl S) hs with ⟨y, hy, V, hv1, hv2⟩, by_cases hxV : x ∈ V, { cases t0_space.t0 x y (λ hxy, hxS $ by rwa hxy) with U hu, rcases hu with ⟨hu1, ⟨hu2, hu3⟩ | ⟨hu2, hu3⟩⟩, { existsi [x, finset.mem_insert_self x S, U ∩ V, is_open_inter hu1 hv1], apply set.ext, intro z, split, { intro hzx, rw set.mem_singleton_iff at hzx, rw hzx, exact ⟨finset.mem_insert_self x S, ⟨hu2, hxV⟩⟩ }, { intro hz, rw set.mem_singleton_iff, rcases hz with ⟨hz1, hz2, hz3⟩, cases finset.mem_insert.1 hz1 with hz4 hz4, { exact hz4 }, { have h1 : z ∈ {y : α | y ∈ S} ∩ V, { exact ⟨hz4, hz3⟩ }, rw ← hv2 at h1, rw set.mem_singleton_iff at h1, rw h1 at hz2, exact (hu3 hz2).elim } } }, { existsi [y, finset.mem_insert_of_mem hy, U ∩ V, is_open_inter hu1 hv1], apply set.ext, intro z, split, { intro hz, rw set.mem_singleton_iff at hz, rw hz, refine ⟨finset.mem_insert_of_mem hy, hu2, _⟩, have h1 : y ∈ {y} := set.mem_singleton y, rw hv2 at h1, exact h1.2 }, { intro hz, rw set.mem_singleton_iff, cases hz with hz1 hz2, cases finset.mem_insert.1 hz1 with hz3 hz3, { rw hz3 at hz2, exact (hu3 hz2.1).elim }, { have h1 : z ∈ {y : α | y ∈ S} ∩ V := ⟨hz3, hz2.2⟩, rw ← hv2 at h1, rw set.mem_singleton_iff at h1, exact h1 } } } }, { existsi [y, finset.mem_insert_of_mem hy, V, hv1], apply set.ext, intro z, split, { intro hz, rw set.mem_singleton_iff at hz, rw hz, split, { exact finset.mem_insert_of_mem hy }, { have h1 : y ∈ {y} := set.mem_singleton y, rw hv2 at h1, exact h1.2 } }, { intro hz, rw hv2, cases hz with hz1 hz2, cases finset.mem_insert.1 hz1 with hz3 hz3, { rw hz3 at hz2, exact (hxV hz2).elim }, { exact ⟨hz3, hz2⟩ } } } } } end, begin apply nonempty.elim ha, intro x, specialize H finset.univ (finset.ne_empty_of_mem $ finset.mem_univ x), rcases H with ⟨y, hyf, U, hu1, hu2⟩, existsi y, have h1 : {y : α | y ∈ finset.univ} = (univ : set α), { exact set.eq_univ_of_forall (λ x : α, by rw mem_set_of_eq; exact finset.mem_univ x) }, rw h1 at hu2, rw set.univ_inter at hu2, rw hu2, exact hu1 end /-- A T₁ space, also known as a Fréchet space, is a topological space where every singleton set is closed. Equivalently, for every pair `x ≠ y`, there is an open set containing `x` and not `y`. -/ class t1_space (α : Type u) [topological_space α] : Prop := (t1 : ∀x, is_closed ({x} : set α)) lemma is_closed_singleton [t1_space α] {x : α} : is_closed ({x} : set α) := t1_space.t1 x @[priority 100] -- see Note [lower instance priority] instance t1_space.t0_space [t1_space α] : t0_space α := ⟨λ x y h, ⟨-{x}, is_open_compl_iff.2 is_closed_singleton, or.inr ⟨λ hyx, or.cases_on hyx h.symm id, λ hx, hx $ or.inl rfl⟩⟩⟩ lemma compl_singleton_mem_nhds [t1_space α] {x y : α} (h : y ≠ x) : - {x} ∈ 𝓝 y := mem_nhds_sets is_closed_singleton $ by rwa [mem_compl_eq, mem_singleton_iff] @[simp] lemma closure_singleton [t1_space α] {a : α} : closure ({a} : set α) = {a} := closure_eq_of_is_closed is_closed_singleton /-- A T₂ space, also known as a Hausdorff space, is one in which for every `x ≠ y` there exists disjoint open sets around `x` and `y`. This is the most widely used of the separation axioms. -/ class t2_space (α : Type u) [topological_space α] : Prop := (t2 : ∀x y, x ≠ y → ∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅) lemma t2_separation [t2_space α] {x y : α} (h : x ≠ y) : ∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅ := t2_space.t2 x y h @[priority 100] -- see Note [lower instance priority] instance t2_space.t1_space [t2_space α] : t1_space α := ⟨λ x, is_open_iff_forall_mem_open.2 $ λ y hxy, let ⟨u, v, hu, hv, hyu, hxv, huv⟩ := t2_separation (mt mem_singleton_of_eq hxy) in ⟨u, λ z hz1 hz2, ((ext_iff _ _).1 huv x).1 ⟨mem_singleton_iff.1 hz2 ▸ hz1, hxv⟩, hu, hyu⟩⟩ lemma eq_of_nhds_ne_bot [ht : t2_space α] {x y : α} (h : 𝓝 x ⊓ 𝓝 y ≠ ⊥) : x = y := classical.by_contradiction $ assume : x ≠ y, let ⟨u, v, hu, hv, hx, hy, huv⟩ := t2_space.t2 x y this in have u ∩ v ∈ 𝓝 x ⊓ 𝓝 y, from inter_mem_inf_sets (mem_nhds_sets hu hx) (mem_nhds_sets hv hy), h $ empty_in_sets_eq_bot.mp $ huv ▸ this lemma t2_iff_nhds : t2_space α ↔ ∀ {x y : α}, 𝓝 x ⊓ 𝓝 y ≠ ⊥ → x = y := ⟨assume h, by exactI λ x y, eq_of_nhds_ne_bot, assume h, ⟨assume x y xy, have 𝓝 x ⊓ 𝓝 y = ⊥ := classical.by_contradiction (mt h xy), let ⟨u', hu', v', hv', u'v'⟩ := empty_in_sets_eq_bot.mpr this, ⟨u, uu', uo, hu⟩ := mem_nhds_sets_iff.mp hu', ⟨v, vv', vo, hv⟩ := mem_nhds_sets_iff.mp hv' in ⟨u, v, uo, vo, hu, hv, disjoint.eq_bot $ disjoint_mono uu' vv' u'v'⟩⟩⟩ lemma t2_iff_ultrafilter : t2_space α ↔ ∀ f {x y : α}, is_ultrafilter f → f ≤ 𝓝 x → f ≤ 𝓝 y → x = y := t2_iff_nhds.trans ⟨assume h f x y u fx fy, h $ ne_bot_of_le_ne_bot u.1 (le_inf fx fy), assume h x y xy, let ⟨f, hf, uf⟩ := exists_ultrafilter xy in h f uf (le_trans hf lattice.inf_le_left) (le_trans hf lattice.inf_le_right)⟩ @[simp] lemma nhds_eq_nhds_iff {a b : α} [t2_space α] : 𝓝 a = 𝓝 b ↔ a = b := ⟨assume h, eq_of_nhds_ne_bot $ by rw [h, inf_idem]; exact nhds_ne_bot, assume h, h ▸ rfl⟩ @[simp] lemma nhds_le_nhds_iff {a b : α} [t2_space α] : 𝓝 a ≤ 𝓝 b ↔ a = b := ⟨assume h, eq_of_nhds_ne_bot $ by rw [inf_of_le_left h]; exact nhds_ne_bot, assume h, h ▸ le_refl _⟩ lemma tendsto_nhds_unique [t2_space α] {f : β → α} {l : filter β} {a b : α} (hl : l ≠ ⊥) (ha : tendsto f l (𝓝 a)) (hb : tendsto f l (𝓝 b)) : a = b := eq_of_nhds_ne_bot $ ne_bot_of_le_ne_bot (map_ne_bot hl) $ le_inf ha hb section lim variables [nonempty α] [t2_space α] {f : filter α} lemma lim_eq {a : α} (hf : f ≠ ⊥) (h : f ≤ 𝓝 a) : lim f = a := eq_of_nhds_ne_bot $ ne_bot_of_le_ne_bot hf $ le_inf (lim_spec ⟨_, h⟩) h @[simp] lemma lim_nhds_eq {a : α} : lim (𝓝 a) = a := lim_eq nhds_ne_bot (le_refl _) @[simp] lemma lim_nhds_eq_of_closure {a : α} {s : set α} (h : a ∈ closure s) : lim (𝓝 a ⊓ principal s) = a := lim_eq begin rw [closure_eq_nhds] at h, exact h end inf_le_left end lim @[priority 100] -- see Note [lower instance priority] instance t2_space_discrete {α : Type*} [topological_space α] [discrete_topology α] : t2_space α := { t2 := assume x y hxy, ⟨{x}, {y}, is_open_discrete _, is_open_discrete _, mem_insert _ _, mem_insert _ _, eq_empty_iff_forall_not_mem.2 $ by intros z hz; cases eq_of_mem_singleton hz.1; cases eq_of_mem_singleton hz.2; cc⟩ } private lemma separated_by_f {α : Type*} {β : Type*} [tα : topological_space α] [tβ : topological_space β] [t2_space β] (f : α → β) (hf : tα ≤ tβ.induced f) {x y : α} (h : f x ≠ f y) : ∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅ := let ⟨u, v, uo, vo, xu, yv, uv⟩ := t2_separation h in ⟨f ⁻¹' u, f ⁻¹' v, hf _ ⟨u, uo, rfl⟩, hf _ ⟨v, vo, rfl⟩, xu, yv, by rw [←preimage_inter, uv, preimage_empty]⟩ instance {α : Type*} {p : α → Prop} [t : topological_space α] [t2_space α] : t2_space (subtype p) := ⟨assume x y h, separated_by_f subtype.val (le_refl _) (mt subtype.eq h)⟩ instance {α : Type*} {β : Type*} [t₁ : topological_space α] [t2_space α] [t₂ : topological_space β] [t2_space β] : t2_space (α × β) := ⟨assume ⟨x₁,x₂⟩ ⟨y₁,y₂⟩ h, or.elim (not_and_distrib.mp (mt prod.ext_iff.mpr h)) (λ h₁, separated_by_f prod.fst inf_le_left h₁) (λ h₂, separated_by_f prod.snd inf_le_right h₂)⟩ instance Pi.t2_space {α : Type*} {β : α → Type v} [t₂ : Πa, topological_space (β a)] [Πa, t2_space (β a)] : t2_space (Πa, β a) := ⟨assume x y h, let ⟨i, hi⟩ := not_forall.mp (mt funext h) in separated_by_f (λz, z i) (infi_le _ i) hi⟩ lemma is_closed_diagonal [t2_space α] : is_closed {p:α×α | p.1 = p.2} := is_closed_iff_nhds.mpr $ assume ⟨a₁, a₂⟩ h, eq_of_nhds_ne_bot $ assume : 𝓝 a₁ ⊓ 𝓝 a₂ = ⊥, h $ let ⟨t₁, ht₁, t₂, ht₂, (h' : t₁ ∩ t₂ ⊆ ∅)⟩ := by rw [←empty_in_sets_eq_bot, mem_inf_sets] at this; exact this in begin change t₁ ∈ 𝓝 a₁ at ht₁, change t₂ ∈ 𝓝 a₂ at ht₂, rw [nhds_prod_eq, ←empty_in_sets_eq_bot], apply filter.sets_of_superset, apply inter_mem_inf_sets (prod_mem_prod ht₁ ht₂) (mem_principal_sets.mpr (subset.refl _)), exact assume ⟨x₁, x₂⟩ ⟨⟨hx₁, hx₂⟩, (heq : x₁ = x₂)⟩, show false, from @h' x₁ ⟨hx₁, heq.symm ▸ hx₂⟩ end variables [topological_space β] lemma is_closed_eq [t2_space α] {f g : β → α} (hf : continuous f) (hg : continuous g) : is_closed {x:β | f x = g x} := continuous_iff_is_closed.mp (hf.prod_mk hg) _ is_closed_diagonal lemma diagonal_eq_range_diagonal_map {α : Type*} : {p:α×α | p.1 = p.2} = range (λx, (x,x)) := ext $ assume p, iff.intro (assume h, ⟨p.1, prod.ext_iff.2 ⟨rfl, h⟩⟩) (assume ⟨x, hx⟩, show p.1 = p.2, by rw ←hx) lemma prod_subset_compl_diagonal_iff_disjoint {α : Type*} {s t : set α} : set.prod s t ⊆ - {p:α×α | p.1 = p.2} ↔ s ∩ t = ∅ := by rw [eq_empty_iff_forall_not_mem, subset_compl_comm, diagonal_eq_range_diagonal_map, range_subset_iff]; simp lemma compact_compact_separated [t2_space α] {s t : set α} (hs : compact s) (ht : compact t) (hst : s ∩ t = ∅) : ∃u v : set α, is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ u ∩ v = ∅ := by simp only [prod_subset_compl_diagonal_iff_disjoint.symm] at ⊢ hst; exact generalized_tube_lemma hs ht is_closed_diagonal hst lemma closed_of_compact [t2_space α] (s : set α) (hs : compact s) : is_closed s := is_open_compl_iff.mpr $ is_open_iff_forall_mem_open.mpr $ assume x hx, let ⟨u, v, uo, vo, su, xv, uv⟩ := compact_compact_separated hs (compact_singleton : compact {x}) (by rwa [inter_comm, ←subset_compl_iff_disjoint, singleton_subset_iff]) in have v ⊆ -s, from subset_compl_comm.mp (subset.trans su (subset_compl_iff_disjoint.mpr uv)), ⟨v, this, vo, by simpa using xv⟩ lemma locally_compact_of_compact_nhds [t2_space α] (h : ∀ x : α, ∃ s, s ∈ 𝓝 x ∧ compact s) : locally_compact_space α := ⟨assume x n hn, let ⟨u, un, uo, xu⟩ := mem_nhds_sets_iff.mp hn in let ⟨k, kx, kc⟩ := h x in -- K is compact but not necessarily contained in N. -- K \ U is again compact and doesn't contain x, so -- we may find open sets V, W separating x from K \ U. -- Then K \ W is a compact neighborhood of x contained in U. let ⟨v, w, vo, wo, xv, kuw, vw⟩ := compact_compact_separated compact_singleton (compact_diff kc uo) (by rw [singleton_inter_eq_empty]; exact λ h, h.2 xu) in have wn : -w ∈ 𝓝 x, from mem_nhds_sets_iff.mpr ⟨v, subset_compl_iff_disjoint.mpr vw, vo, singleton_subset_iff.mp xv⟩, ⟨k - w, filter.inter_mem_sets kx wn, subset.trans (diff_subset_comm.mp kuw) un, compact_diff kc wo⟩⟩ @[priority 100] -- see Note [lower instance priority] instance locally_compact_of_compact [t2_space α] [compact_space α] : locally_compact_space α := locally_compact_of_compact_nhds (assume x, ⟨univ, mem_nhds_sets is_open_univ trivial, compact_univ⟩) end separation section regularity section prio set_option default_priority 100 -- see Note [default priority] /-- A T₃ space, also known as a regular space (although this condition sometimes omits T₂), is one in which for every closed `C` and `x ∉ C`, there exist disjoint open sets containing `x` and `C` respectively. -/ class regular_space (α : Type u) [topological_space α] extends t1_space α : Prop := (regular : ∀{s:set α} {a}, is_closed s → a ∉ s → ∃t, is_open t ∧ s ⊆ t ∧ 𝓝 a ⊓ principal t = ⊥) end prio lemma nhds_is_closed [regular_space α] {a : α} {s : set α} (h : s ∈ 𝓝 a) : ∃t∈(𝓝 a), t ⊆ s ∧ is_closed t := let ⟨s', h₁, h₂, h₃⟩ := mem_nhds_sets_iff.mp h in have ∃t, is_open t ∧ -s' ⊆ t ∧ 𝓝 a ⊓ principal t = ⊥, from regular_space.regular (is_closed_compl_iff.mpr h₂) (not_not_intro h₃), let ⟨t, ht₁, ht₂, ht₃⟩ := this in ⟨-t, mem_sets_of_eq_bot $ by rwa [lattice.neg_neg], subset.trans (compl_subset_comm.1 ht₂) h₁, is_closed_compl_iff.mpr ht₁⟩ variable (α) @[priority 100] -- see Note [lower instance priority] instance regular_space.t2_space [regular_space α] : t2_space α := ⟨λ x y hxy, let ⟨s, hs, hys, hxs⟩ := regular_space.regular is_closed_singleton (mt mem_singleton_iff.1 hxy), ⟨t, hxt, u, hsu, htu⟩ := empty_in_sets_eq_bot.2 hxs, ⟨v, hvt, hv, hxv⟩ := mem_nhds_sets_iff.1 hxt in ⟨v, s, hv, hs, hxv, singleton_subset_iff.1 hys, eq_empty_of_subset_empty $ λ z ⟨hzv, hzs⟩, htu ⟨hvt hzv, hsu hzs⟩⟩⟩ end regularity section normality section prio set_option default_priority 100 -- see Note [default priority] /-- A T₄ space, also known as a normal space (although this condition sometimes omits T₂), is one in which for every pair of disjoint closed sets `C` and `D`, there exist disjoint open sets containing `C` and `D` respectively. -/ class normal_space (α : Type u) [topological_space α] extends t1_space α : Prop := (normal : ∀ s t : set α, is_closed s → is_closed t → disjoint s t → ∃ u v, is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ disjoint u v) end prio theorem normal_separation [normal_space α] (s t : set α) (H1 : is_closed s) (H2 : is_closed t) (H3 : disjoint s t) : ∃ u v, is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ disjoint u v := normal_space.normal s t H1 H2 H3 @[priority 100] -- see Note [lower instance priority] instance normal_space.regular_space [normal_space α] : regular_space α := { regular := λ s x hs hxs, let ⟨u, v, hu, hv, hsu, hxv, huv⟩ := normal_separation s {x} hs is_closed_singleton (λ _ ⟨hx, hy⟩, hxs $ set.mem_of_eq_of_mem (set.eq_of_mem_singleton hy).symm hx) in ⟨u, hu, hsu, filter.empty_in_sets_eq_bot.1 $ filter.mem_inf_sets.2 ⟨v, mem_nhds_sets hv (set.singleton_subset_iff.1 hxv), u, filter.mem_principal_self u, set.inter_comm u v ▸ huv⟩⟩ } -- We can't make this an instance because it could cause an instance loop. lemma normal_of_compact_t2 [compact_space α] [t2_space α] : normal_space α := begin refine ⟨assume s t hs ht st, _⟩, simp only [disjoint_iff], exact compact_compact_separated hs.compact ht.compact st.eq_bot end end normality
5ef6f161f09e42cbce8c31283ae50542d439826e
41ebf3cb010344adfa84907b3304db00e02db0a6
/uexp/src/uexp/meta/UDP.lean
759c992494819d123e1b58ec583ae0266c63f51b
[ "BSD-2-Clause" ]
permissive
ReinierKoops/Cosette
e061b2ba58b26f4eddf4cd052dcf7abd16dfe8fb
eb8dadd06ee05fe7b6b99de431dd7c4faef5cb29
refs/heads/master
1,686,483,953,198
1,624,293,498,000
1,624,293,498,000
378,997,885
0
0
BSD-2-Clause
1,624,293,485,000
1,624,293,484,000
null
UTF-8
Lean
false
false
2,332
lean
import ..u_semiring import .cosette_tactics .ucongr .TDP section UDP open tactic meta structure usr_add_repr := (summands : list expr) -- Given a + (b + c), produce [a, b, c] meta def add_expr_to_add_repr : expr → usr_add_repr | `(%%a + %%b) := match add_expr_to_add_repr b with | ⟨es⟩ := ⟨a :: es⟩ end | e := ⟨[e]⟩ meta def add_repr_to_add_expr : usr_add_repr → tactic expr | ⟨xs⟩ := match xs.reverse with | (a::as) := list.mfoldr (λ (x sum : expr), to_expr ``(%%x + %%sum)) a as.reverse | [] := fail "Tried to turn an empty list into a sum" end meta def get_lhs_add_repr : tactic usr_add_repr := target >>= λ e, match e with | `(%%a = %%b) := return $ add_expr_to_add_repr a | _ := fail "Not an equality" end meta def swap_ith_summand_forward (i : nat) : usr_add_repr → tactic unit | ⟨es⟩ := do swapped_repr ← usr_add_repr.mk <$> list.swap_ith_forward i es, normal_expr ← add_repr_to_add_expr ⟨es⟩, swapped_expr ← add_repr_to_add_expr swapped_repr, equality_lemma ← to_expr ``(%%normal_expr = %%swapped_expr), eq_lemma_name ← mk_fresh_name, tactic.assert eq_lemma_name equality_lemma, ac_refl, eq_lemma ← resolve_name eq_lemma_name >>= to_expr, rewrite_target eq_lemma, clear eq_lemma meta def move_add_to_front (i : nat) : tactic unit := let loop : ℕ → tactic unit → tactic unit := λ iter_num next_iter, do repr ← get_lhs_add_repr, swap_ith_summand_forward iter_num repr, next_iter in nat.repeat loop i $ return () meta def UDP : tactic unit := let loop (iter_num : ℕ) (next_iter : tactic unit) : tactic unit := next_iter <|> do move_add_to_front iter_num, applyc `congr_arg₂, TDP, UDP in do num_summands ← list.length <$> usr_add_repr.summands <$> get_lhs_add_repr, nat.repeat loop num_summands TDP end UDP example {p q r s} {f g : Tuple p → Tuple q → Tuple r → Tuple s → usr} : (∑ (a : Tuple p) (b : Tuple q) (c : Tuple r) (d : Tuple s), f a b c d) + ((∑ (a : Tuple p) (b : Tuple q) (c : Tuple r) (d : Tuple s), g a b c d) + 1) = 1 + ((∑ (c : Tuple r) (a : Tuple p) (d : Tuple s) (b : Tuple q), g a b c d) + (∑ (c : Tuple r) (a : Tuple p) (d : Tuple s) (b : Tuple q), f a b c d)) := begin UDP, end
132237b31293be2cd753296f4bdd9064bb0528e5
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/vector_bundle/basic.lean
5a703818a86607e248016aa4254d3c74cda743c5
[ "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
42,032
lean
/- Copyright © 2020 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nicolò Cavalleri, Sebastien Gouezel, Heather Macbeth, Patrick Massot, Floris van Doorn -/ import analysis.normed_space.bounded_linear_maps import topology.fiber_bundle.basic /-! # Vector bundles > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we define (topological) vector bundles. Let `B` be the base space, let `F` be a normed space over a normed field `R`, and let `E : B → Type*` be a `fiber_bundle` with fiber `F`, in which, for each `x`, the fiber `E x` is a topological vector space over `R`. To have a vector bundle structure on `bundle.total_space F E`, one should additionally have the following properties: * The bundle trivializations in the trivialization atlas should be continuous linear equivs in the fibers; * For any two trivializations `e`, `e'` in the atlas the transition function considered as a map from `B` into `F →L[R] F` is continuous on `e.base_set ∩ e'.base_set` with respect to the operator norm topology on `F →L[R] F`. If these conditions are satisfied, we register the typeclass `vector_bundle R F E`. We define constructions on vector bundles like pullbacks and direct sums in other files. ## Main Definitions * `trivialization.is_linear`: a class stating that a trivialization is fiberwise linear on its base set. * `trivialization.linear_equiv_at` and `trivialization.continuous_linear_map_at` are the (continuous) linear fiberwise equivalences a trivialization induces. * They have forward maps `trivialization.linear_map_at` / `trivialization.continuous_linear_map_at` and inverses `trivialization.symmₗ` / `trivialization.symmL`. Note that these are all defined everywhere, since they are extended using the zero function. * `trivialization.coord_changeL` is the coordinate change induced by two trivializations. It only makes sense on the intersection of their base sets, but is extended outside it using the identity. * Given a continuous (semi)linear map between `E x` and `E' y` where `E` and `E'` are bundles over possibly different base sets, `continuous_linear_map.in_coordinates` turns this into a continuous (semi)linear map between the chosen fibers of those bundles. ## Implementation notes The implementation choices in the vector bundle definition are discussed in the "Implementation notes" section of `topology.fiber_bundle.basic`. ## Tags Vector bundle -/ noncomputable theory open bundle set open_locale classical bundle variables (R : Type*) {B : Type*} (F : Type*) (E : B → Type*) section topological_vector_space variables {B F E} [semiring R] [topological_space F] [topological_space B] /-- A mixin class for `pretrivialization`, stating that a pretrivialization is fiberwise linear with respect to given module structures on its fibers and the model fiber. -/ protected class pretrivialization.is_linear [add_comm_monoid F] [module R F] [∀ x, add_comm_monoid (E x)] [∀ x, module R (E x)] (e : pretrivialization F (π F E)) : Prop := (linear : ∀ b ∈ e.base_set, is_linear_map R (λ x : E b, (e ⟨b, x⟩).2)) namespace pretrivialization variables {F E} (e : pretrivialization F (π F E)) {x : total_space F E} {b : B} {y : E b} lemma linear [add_comm_monoid F] [module R F] [∀ x, add_comm_monoid (E x)] [∀ x, module R (E x)] [e.is_linear R] {b : B} (hb : b ∈ e.base_set) : is_linear_map R (λ x : E b, (e ⟨b, x⟩).2) := pretrivialization.is_linear.linear b hb variables [add_comm_monoid F] [module R F] [∀ x, add_comm_monoid (E x)] [∀ x, module R (E x)] /-- A fiberwise linear inverse to `e`. -/ @[simps] protected def symmₗ (e : pretrivialization F (π F E)) [e.is_linear R] (b : B) : F →ₗ[R] E b := begin refine is_linear_map.mk' (e.symm b) _, by_cases hb : b ∈ e.base_set, { exact (((e.linear R hb).mk' _).inverse (e.symm b) (e.symm_apply_apply_mk hb) (λ v, congr_arg prod.snd $ e.apply_mk_symm hb v)).is_linear }, { rw [e.coe_symm_of_not_mem hb], exact (0 : F →ₗ[R] E b).is_linear } end /-- A pretrivialization for a vector bundle defines linear equivalences between the fibers and the model space. -/ @[simps {fully_applied := ff}] def linear_equiv_at (e : pretrivialization F (π F E)) [e.is_linear R] (b : B) (hb : b ∈ e.base_set) : E b ≃ₗ[R] F := { to_fun := λ y, (e ⟨b, y⟩).2, inv_fun := e.symm b, left_inv := e.symm_apply_apply_mk hb, right_inv := λ v, by simp_rw [e.apply_mk_symm hb v], map_add' := λ v w, (e.linear R hb).map_add v w, map_smul' := λ c v, (e.linear R hb).map_smul c v } /-- A fiberwise linear map equal to `e` on `e.base_set`. -/ protected def linear_map_at (e : pretrivialization F (π F E)) [e.is_linear R] (b : B) : E b →ₗ[R] F := if hb : b ∈ e.base_set then e.linear_equiv_at R b hb else 0 variables {R} lemma coe_linear_map_at (e : pretrivialization F (π F E)) [e.is_linear R] (b : B) : ⇑(e.linear_map_at R b) = λ y, if b ∈ e.base_set then (e ⟨b, y⟩).2 else 0 := by { rw [pretrivialization.linear_map_at], split_ifs; refl } lemma coe_linear_map_at_of_mem (e : pretrivialization F (π F E)) [e.is_linear R] {b : B} (hb : b ∈ e.base_set) : ⇑(e.linear_map_at R b) = λ y, (e ⟨b, y⟩).2 := by simp_rw [coe_linear_map_at, if_pos hb] lemma linear_map_at_apply (e : pretrivialization F (π F E)) [e.is_linear R] {b : B} (y : E b) : e.linear_map_at R b y = if b ∈ e.base_set then (e ⟨b, y⟩).2 else 0 := by rw [coe_linear_map_at] lemma linear_map_at_def_of_mem (e : pretrivialization F (π F E)) [e.is_linear R] {b : B} (hb : b ∈ e.base_set) : e.linear_map_at R b = e.linear_equiv_at R b hb := dif_pos hb lemma linear_map_at_def_of_not_mem (e : pretrivialization F (π F E)) [e.is_linear R] {b : B} (hb : b ∉ e.base_set) : e.linear_map_at R b = 0 := dif_neg hb lemma linear_map_at_eq_zero (e : pretrivialization F (π F E)) [e.is_linear R] {b : B} (hb : b ∉ e.base_set) : e.linear_map_at R b = 0 := dif_neg hb lemma symmₗ_linear_map_at (e : pretrivialization F (π F E)) [e.is_linear R] {b : B} (hb : b ∈ e.base_set) (y : E b) : e.symmₗ R b (e.linear_map_at R b y) = y := by { rw [e.linear_map_at_def_of_mem hb], exact (e.linear_equiv_at R b hb).left_inv y } lemma linear_map_at_symmₗ (e : pretrivialization F (π F E)) [e.is_linear R] {b : B} (hb : b ∈ e.base_set) (y : F) : e.linear_map_at R b (e.symmₗ R b y) = y := by { rw [e.linear_map_at_def_of_mem hb], exact (e.linear_equiv_at R b hb).right_inv y } end pretrivialization variables (R) [topological_space (total_space F E)] /-- A mixin class for `trivialization`, stating that a trivialization is fiberwise linear with respect to given module structures on its fibers and the model fiber. -/ protected class trivialization.is_linear [add_comm_monoid F] [module R F] [∀ x, add_comm_monoid (E x)] [∀ x, module R (E x)] (e : trivialization F (π F E)) : Prop := (linear : ∀ b ∈ e.base_set, is_linear_map R (λ x : E b, (e ⟨b, x⟩).2)) namespace trivialization variables (e : trivialization F (π F E)) {x : total_space F E} {b : B} {y : E b} protected lemma linear [add_comm_monoid F] [module R F] [∀ x, add_comm_monoid (E x)] [∀ x, module R (E x)] [e.is_linear R] {b : B} (hb : b ∈ e.base_set) : is_linear_map R (λ y : E b, (e ⟨b, y⟩).2) := trivialization.is_linear.linear b hb instance to_pretrivialization.is_linear [add_comm_monoid F] [module R F] [∀ x, add_comm_monoid (E x)] [∀ x, module R (E x)] [e.is_linear R] : e.to_pretrivialization.is_linear R := { ..(‹_› : e.is_linear R) } variables [add_comm_monoid F] [module R F] [∀ x, add_comm_monoid (E x)] [∀ x, module R (E x)] /-- A trivialization for a vector bundle defines linear equivalences between the fibers and the model space. -/ def linear_equiv_at (e : trivialization F (π F E)) [e.is_linear R] (b : B) (hb : b ∈ e.base_set) : E b ≃ₗ[R] F := e.to_pretrivialization.linear_equiv_at R b hb variables {R} @[simp] lemma linear_equiv_at_apply (e : trivialization F (π F E)) [e.is_linear R] (b : B) (hb : b ∈ e.base_set) (v : E b) : e.linear_equiv_at R b hb v = (e ⟨b, v⟩).2 := rfl @[simp] lemma linear_equiv_at_symm_apply (e : trivialization F (π F E)) [e.is_linear R] (b : B) (hb : b ∈ e.base_set) (v : F) : (e.linear_equiv_at R b hb).symm v = e.symm b v := rfl variables (R) /-- A fiberwise linear inverse to `e`. -/ protected def symmₗ (e : trivialization F (π F E)) [e.is_linear R] (b : B) : F →ₗ[R] E b := e.to_pretrivialization.symmₗ R b variables {R} lemma coe_symmₗ (e : trivialization F (π F E)) [e.is_linear R] (b : B) : ⇑(e.symmₗ R b) = e.symm b := rfl variables (R) /-- A fiberwise linear map equal to `e` on `e.base_set`. -/ protected def linear_map_at (e : trivialization F (π F E)) [e.is_linear R] (b : B) : E b →ₗ[R] F := e.to_pretrivialization.linear_map_at R b variables {R} lemma coe_linear_map_at (e : trivialization F (π F E)) [e.is_linear R] (b : B) : ⇑(e.linear_map_at R b) = λ y, if b ∈ e.base_set then (e ⟨b, y⟩).2 else 0 := e.to_pretrivialization.coe_linear_map_at b lemma coe_linear_map_at_of_mem (e : trivialization F (π F E)) [e.is_linear R] {b : B} (hb : b ∈ e.base_set) : ⇑(e.linear_map_at R b) = λ y, (e ⟨b, y⟩).2 := by simp_rw [coe_linear_map_at, if_pos hb] lemma linear_map_at_apply (e : trivialization F (π F E)) [e.is_linear R] {b : B} (y : E b) : e.linear_map_at R b y = if b ∈ e.base_set then (e ⟨b, y⟩).2 else 0 := by rw [coe_linear_map_at] lemma linear_map_at_def_of_mem (e : trivialization F (π F E)) [e.is_linear R] {b : B} (hb : b ∈ e.base_set) : e.linear_map_at R b = e.linear_equiv_at R b hb := dif_pos hb lemma linear_map_at_def_of_not_mem (e : trivialization F (π F E)) [e.is_linear R] {b : B} (hb : b ∉ e.base_set) : e.linear_map_at R b = 0 := dif_neg hb lemma symmₗ_linear_map_at (e : trivialization F (π F E)) [e.is_linear R] {b : B} (hb : b ∈ e.base_set) (y : E b) : e.symmₗ R b (e.linear_map_at R b y) = y := e.to_pretrivialization.symmₗ_linear_map_at hb y lemma linear_map_at_symmₗ (e : trivialization F (π F E)) [e.is_linear R] {b : B} (hb : b ∈ e.base_set) (y : F) : e.linear_map_at R b (e.symmₗ R b y) = y := e.to_pretrivialization.linear_map_at_symmₗ hb y variables (R) /-- A coordinate change function between two trivializations, as a continuous linear equivalence. Defined to be the identity when `b` does not lie in the base set of both trivializations. -/ def coord_changeL (e e' : trivialization F (π F E)) [e.is_linear R] [e'.is_linear R] (b : B) : F ≃L[R] F := { continuous_to_fun := begin by_cases hb : b ∈ e.base_set ∩ e'.base_set, { simp_rw [dif_pos hb], refine (e'.continuous_on.comp_continuous _ _).snd, exact e.continuous_on_symm.comp_continuous (continuous.prod.mk b) (λ y, mk_mem_prod hb.1 (mem_univ y)), exact (λ y, e'.mem_source.mpr hb.2) }, { rw [dif_neg hb], exact continuous_id } end, continuous_inv_fun := begin by_cases hb : b ∈ e.base_set ∩ e'.base_set, { simp_rw [dif_pos hb], refine (e.continuous_on.comp_continuous _ _).snd, exact e'.continuous_on_symm.comp_continuous (continuous.prod.mk b) (λ y, mk_mem_prod hb.2 (mem_univ y)), exact (λ y, e.mem_source.mpr hb.1) }, { rw [dif_neg hb], exact continuous_id } end, .. if hb : b ∈ e.base_set ∩ e'.base_set then (e.linear_equiv_at R b (hb.1 : _)).symm.trans (e'.linear_equiv_at R b hb.2) else linear_equiv.refl R F } variables {R} lemma coe_coord_changeL (e e' : trivialization F (π F E)) [e.is_linear R] [e'.is_linear R] {b : B} (hb : b ∈ e.base_set ∩ e'.base_set) : ⇑(coord_changeL R e e' b) = (e.linear_equiv_at R b hb.1).symm.trans (e'.linear_equiv_at R b hb.2) := congr_arg linear_equiv.to_fun (dif_pos hb) lemma coe_coord_changeL' (e e' : trivialization F (π F E)) [e.is_linear R] [e'.is_linear R] {b : B} (hb : b ∈ e.base_set ∩ e'.base_set) : (coord_changeL R e e' b).to_linear_equiv = (e.linear_equiv_at R b hb.1).symm.trans (e'.linear_equiv_at R b hb.2) := linear_equiv.coe_injective (coe_coord_changeL _ _ _) lemma symm_coord_changeL (e e' : trivialization F (π F E)) [e.is_linear R] [e'.is_linear R] {b : B} (hb : b ∈ e'.base_set ∩ e.base_set) : (e.coord_changeL R e' b).symm = e'.coord_changeL R e b := begin apply continuous_linear_equiv.to_linear_equiv_injective, rw [coe_coord_changeL' e' e hb, (coord_changeL R e e' b).symm_to_linear_equiv, coe_coord_changeL' e e' hb.symm, linear_equiv.trans_symm, linear_equiv.symm_symm], end lemma coord_changeL_apply (e e' : trivialization F (π F E)) [e.is_linear R] [e'.is_linear R] {b : B} (hb : b ∈ e.base_set ∩ e'.base_set) (y : F) : coord_changeL R e e' b y = (e' ⟨b, e.symm b y⟩).2 := congr_arg (λ f, linear_equiv.to_fun f y) (dif_pos hb) lemma mk_coord_changeL (e e' : trivialization F (π F E)) [e.is_linear R] [e'.is_linear R] {b : B} (hb : b ∈ e.base_set ∩ e'.base_set) (y : F) : (b, coord_changeL R e e' b y) = e' ⟨b, e.symm b y⟩ := begin ext, { rw [e.mk_symm hb.1 y, e'.coe_fst', e.proj_symm_apply' hb.1], rw [e.proj_symm_apply' hb.1], exact hb.2 }, { exact e.coord_changeL_apply e' hb y } end lemma apply_symm_apply_eq_coord_changeL (e e' : trivialization F (π F E)) [e.is_linear R] [e'.is_linear R] {b : B} (hb : b ∈ e.base_set ∩ e'.base_set) (v : F) : e' (e.to_local_homeomorph.symm (b, v)) = (b, e.coord_changeL R e' b v) := by rw [e.mk_coord_changeL e' hb, e.mk_symm hb.1] /-- A version of `coord_change_apply` that fully unfolds `coord_change`. The right-hand side is ugly, but has good definitional properties for specifically defined trivializations. -/ lemma coord_changeL_apply' (e e' : trivialization F (π F E)) [e.is_linear R] [e'.is_linear R] {b : B} (hb : b ∈ e.base_set ∩ e'.base_set) (y : F) : coord_changeL R e e' b y = (e' (e.to_local_homeomorph.symm (b, y))).2 := by rw [e.coord_changeL_apply e' hb, e.mk_symm hb.1] lemma coord_changeL_symm_apply (e e' : trivialization F (π F E)) [e.is_linear R] [e'.is_linear R] {b : B} (hb : b ∈ e.base_set ∩ e'.base_set) : ⇑(coord_changeL R e e' b).symm = (e'.linear_equiv_at R b hb.2).symm.trans (e.linear_equiv_at R b hb.1) := congr_arg linear_equiv.inv_fun (dif_pos hb) end trivialization end topological_vector_space section namespace bundle /-- The zero section of a vector bundle -/ def zero_section [∀ x, has_zero (E x)] : B → total_space F E := λ x, ⟨x, 0⟩ @[simp, mfld_simps] lemma zero_section_proj [∀ x, has_zero (E x)] (x : B) : (zero_section F E x).proj = x := rfl @[simp, mfld_simps] lemma zero_section_snd [∀ x, has_zero (E x)] (x : B) : (zero_section F E x).2 = 0 := rfl end bundle open bundle variables [nontrivially_normed_field R] [∀ x, add_comm_monoid (E x)] [∀ x, module R (E x)] [normed_add_comm_group F] [normed_space R F] [topological_space B] [topological_space (total_space F E)] [∀ x, topological_space (E x)] [fiber_bundle F E] /-- The space `total_space F E` (for `E : B → Type*` such that each `E x` is a topological vector space) has a topological vector space structure with fiber `F` (denoted with `vector_bundle R F E`) if around every point there is a fiber bundle trivialization which is linear in the fibers. -/ class vector_bundle : Prop := (trivialization_linear' : ∀ (e : trivialization F (π F E)) [mem_trivialization_atlas e], e.is_linear R) (continuous_on_coord_change' [] : ∀ (e e' : trivialization F (π F E)) [mem_trivialization_atlas e] [mem_trivialization_atlas e'], continuous_on (λ b, by exactI trivialization.coord_changeL R e e' b : B → F →L[R] F) (e.base_set ∩ e'.base_set)) variables {F E} @[priority 100] instance trivialization_linear [vector_bundle R F E] (e : trivialization F (π F E)) [mem_trivialization_atlas e] : e.is_linear R := vector_bundle.trivialization_linear' e lemma continuous_on_coord_change [vector_bundle R F E] (e e' : trivialization F (π F E)) [he : mem_trivialization_atlas e] [he' : mem_trivialization_atlas e'] : continuous_on (λ b, trivialization.coord_changeL R e e' b : B → F →L[R] F) (e.base_set ∩ e'.base_set) := vector_bundle.continuous_on_coord_change' R e e' namespace trivialization /-- Forward map of `continuous_linear_equiv_at` (only propositionally equal), defined everywhere (`0` outside domain). -/ @[simps apply {fully_applied := ff}] def continuous_linear_map_at (e : trivialization F (π F E)) [e.is_linear R] (b : B) : E b →L[R] F := { to_fun := e.linear_map_at R b, -- given explicitly to help `simps` cont := begin dsimp, rw [e.coe_linear_map_at b], refine continuous_if_const _ (λ hb, _) (λ _, continuous_zero), exact continuous_snd.comp (e.continuous_on.comp_continuous (fiber_bundle.total_space_mk_inducing F E b).continuous (λ x, e.mem_source.mpr hb)) end, .. e.linear_map_at R b } /-- Backwards map of `continuous_linear_equiv_at`, defined everywhere. -/ @[simps apply {fully_applied := ff}] def symmL (e : trivialization F (π F E)) [e.is_linear R] (b : B) : F →L[R] E b := { to_fun := e.symm b, -- given explicitly to help `simps` cont := begin by_cases hb : b ∈ e.base_set, { rw (fiber_bundle.total_space_mk_inducing F E b).continuous_iff, exact e.continuous_on_symm.comp_continuous (continuous_const.prod_mk continuous_id) (λ x, mk_mem_prod hb (mem_univ x)) }, { refine continuous_zero.congr (λ x, (e.symm_apply_of_not_mem hb x).symm) }, end, .. e.symmₗ R b } variables {R} lemma symmL_continuous_linear_map_at (e : trivialization F (π F E)) [e.is_linear R] {b : B} (hb : b ∈ e.base_set) (y : E b) : e.symmL R b (e.continuous_linear_map_at R b y) = y := e.symmₗ_linear_map_at hb y lemma continuous_linear_map_at_symmL (e : trivialization F (π F E)) [e.is_linear R] {b : B} (hb : b ∈ e.base_set) (y : F) : e.continuous_linear_map_at R b (e.symmL R b y) = y := e.linear_map_at_symmₗ hb y variables (R) /-- In a vector bundle, a trivialization in the fiber (which is a priori only linear) is in fact a continuous linear equiv between the fibers and the model fiber. -/ @[simps apply symm_apply {fully_applied := ff}] def continuous_linear_equiv_at (e : trivialization F (π F E)) [e.is_linear R] (b : B) (hb : b ∈ e.base_set) : E b ≃L[R] F := { to_fun := λ y, (e ⟨b, y⟩).2, -- given explicitly to help `simps` inv_fun := e.symm b, -- given explicitly to help `simps` continuous_to_fun := continuous_snd.comp (e.continuous_on.comp_continuous (fiber_bundle.total_space_mk_inducing F E b).continuous (λ x, e.mem_source.mpr hb)), continuous_inv_fun := (e.symmL R b).continuous, .. e.to_pretrivialization.linear_equiv_at R b hb } variables {R} lemma coe_continuous_linear_equiv_at_eq (e : trivialization F (π F E)) [e.is_linear R] {b : B} (hb : b ∈ e.base_set) : (e.continuous_linear_equiv_at R b hb : E b → F) = e.continuous_linear_map_at R b := (e.coe_linear_map_at_of_mem hb).symm lemma symm_continuous_linear_equiv_at_eq (e : trivialization F (π F E)) [e.is_linear R] {b : B} (hb : b ∈ e.base_set) : ((e.continuous_linear_equiv_at R b hb).symm : F → E b) = e.symmL R b := rfl @[simp] lemma continuous_linear_equiv_at_apply' (e : trivialization F (π F E)) [e.is_linear R] (x : total_space F E) (hx : x ∈ e.source) : e.continuous_linear_equiv_at R x.proj (e.mem_source.1 hx) x.2 = (e x).2 := by { cases x, refl } variables (R) lemma apply_eq_prod_continuous_linear_equiv_at (e : trivialization F (π F E)) [e.is_linear R] (b : B) (hb : b ∈ e.base_set) (z : E b) : e ⟨b, z⟩ = (b, e.continuous_linear_equiv_at R b hb z) := begin ext, { refine e.coe_fst _, rw e.source_eq, exact hb }, { simp only [coe_coe, continuous_linear_equiv_at_apply] } end protected lemma zero_section (e : trivialization F (π F E)) [e.is_linear R] {x : B} (hx : x ∈ e.base_set) : e (zero_section F E x) = (x, 0) := by simp_rw [zero_section, e.apply_eq_prod_continuous_linear_equiv_at R x hx 0, map_zero] variables {R} lemma symm_apply_eq_mk_continuous_linear_equiv_at_symm (e : trivialization F (π F E)) [e.is_linear R] (b : B) (hb : b ∈ e.base_set) (z : F) : e.to_local_homeomorph.symm ⟨b, z⟩ = ⟨b, (e.continuous_linear_equiv_at R b hb).symm z⟩ := begin have h : (b, z) ∈ e.target, { rw e.target_eq, exact ⟨hb, mem_univ _⟩ }, apply e.inj_on (e.map_target h), { simp only [e.source_eq, hb, mem_preimage] }, simp_rw [e.right_inv h, coe_coe, e.apply_eq_prod_continuous_linear_equiv_at R b hb, continuous_linear_equiv.apply_symm_apply], end lemma comp_continuous_linear_equiv_at_eq_coord_change (e e' : trivialization F (π F E)) [e.is_linear R] [e'.is_linear R] {b : B} (hb : b ∈ e.base_set ∩ e'.base_set) : (e.continuous_linear_equiv_at R b hb.1).symm.trans (e'.continuous_linear_equiv_at R b hb.2) = coord_changeL R e e' b := by { ext v, rw [coord_changeL_apply e e' hb], refl } end trivialization include R F /-! ### Constructing vector bundles -/ variables (R B F) /-- Analogous construction of `fiber_bundle_core` for vector bundles. This construction gives a way to construct vector bundles from a structure registering how trivialization changes act on fibers. -/ structure vector_bundle_core (ι : Type*) := (base_set : ι → set B) (is_open_base_set : ∀ i, is_open (base_set i)) (index_at : B → ι) (mem_base_set_at : ∀ x, x ∈ base_set (index_at x)) (coord_change : ι → ι → B → (F →L[R] F)) (coord_change_self : ∀ i, ∀ x ∈ base_set i, ∀ v, coord_change i i x v = v) (continuous_on_coord_change : ∀ i j, continuous_on (coord_change i j) (base_set i ∩ base_set j)) (coord_change_comp : ∀ i j k, ∀ x ∈ (base_set i) ∩ (base_set j) ∩ (base_set k), ∀ v, (coord_change j k x) (coord_change i j x v) = coord_change i k x v) /-- The trivial vector bundle core, in which all the changes of coordinates are the identity. -/ def trivial_vector_bundle_core (ι : Type*) [inhabited ι] : vector_bundle_core R B F ι := { base_set := λ ι, univ, is_open_base_set := λ i, is_open_univ, index_at := default, mem_base_set_at := λ x, mem_univ x, coord_change := λ i j x, continuous_linear_map.id R F, coord_change_self := λ i x hx v, rfl, coord_change_comp := λ i j k x hx v, rfl, continuous_on_coord_change := λ i j, continuous_on_const } instance (ι : Type*) [inhabited ι] : inhabited (vector_bundle_core R B F ι) := ⟨trivial_vector_bundle_core R B F ι⟩ namespace vector_bundle_core variables {R B F} {ι : Type*} (Z : vector_bundle_core R B F ι) /-- Natural identification to a `fiber_bundle_core`. -/ @[simps (mfld_cfg)] def to_fiber_bundle_core : fiber_bundle_core ι B F := { coord_change := λ i j b, Z.coord_change i j b, continuous_on_coord_change := λ i j, is_bounded_bilinear_map_apply.continuous.comp_continuous_on ((Z.continuous_on_coord_change i j).prod_map continuous_on_id), ..Z } instance to_fiber_bundle_core_coe : has_coe (vector_bundle_core R B F ι) (fiber_bundle_core ι B F) := ⟨to_fiber_bundle_core⟩ include Z lemma coord_change_linear_comp (i j k : ι): ∀ x ∈ (Z.base_set i) ∩ (Z.base_set j) ∩ (Z.base_set k), (Z.coord_change j k x).comp (Z.coord_change i j x) = Z.coord_change i k x := λ x hx, by { ext v, exact Z.coord_change_comp i j k x hx v } /-- The index set of a vector bundle core, as a convenience function for dot notation -/ @[nolint unused_arguments has_nonempty_instance] def index := ι /-- The base space of a vector bundle core, as a convenience function for dot notation-/ @[nolint unused_arguments, reducible] def base := B /-- The fiber of a vector bundle core, as a convenience function for dot notation and typeclass inference -/ @[nolint unused_arguments has_nonempty_instance] def fiber : B → Type* := Z.to_fiber_bundle_core.fiber instance topological_space_fiber (x : B) : topological_space (Z.fiber x) := by delta_instance vector_bundle_core.fiber instance add_comm_monoid_fiber : ∀ (x : B), add_comm_monoid (Z.fiber x) := by dsimp [vector_bundle_core.fiber]; delta_instance fiber_bundle_core.fiber instance module_fiber : ∀ (x : B), module R (Z.fiber x) := by dsimp [vector_bundle_core.fiber]; delta_instance fiber_bundle_core.fiber instance add_comm_group_fiber [add_comm_group F] : ∀ (x : B), add_comm_group (Z.fiber x) := by dsimp [vector_bundle_core.fiber]; delta_instance fiber_bundle_core.fiber /-- The projection from the total space of a fiber bundle core, on its base. -/ @[reducible, simp, mfld_simps] protected def proj : total_space F Z.fiber → B := total_space.proj /-- The total space of the vector bundle, as a convenience function for dot notation. It is by definition equal to `bundle.total_space Z.fiber`. -/ @[nolint unused_arguments, reducible] protected def total_space := bundle.total_space F Z.fiber /-- Local homeomorphism version of the trivialization change. -/ def triv_change (i j : ι) : local_homeomorph (B × F) (B × F) := fiber_bundle_core.triv_change ↑Z i j @[simp, mfld_simps] lemma mem_triv_change_source (i j : ι) (p : B × F) : p ∈ (Z.triv_change i j).source ↔ p.1 ∈ Z.base_set i ∩ Z.base_set j := fiber_bundle_core.mem_triv_change_source ↑Z i j p /-- Topological structure on the total space of a vector bundle created from core, designed so that all the local trivialization are continuous. -/ instance to_topological_space : topological_space Z.total_space := Z.to_fiber_bundle_core.to_topological_space variables (b : B) (a : F) @[simp, mfld_simps] lemma coe_coord_change (i j : ι) : Z.to_fiber_bundle_core.coord_change i j b = Z.coord_change i j b := rfl /-- One of the standard local trivializations of a vector bundle constructed from core, taken by considering this in particular as a fiber bundle constructed from core. -/ def local_triv (i : ι) : trivialization F (π F Z.fiber) := by dsimp [vector_bundle_core.total_space, vector_bundle_core.fiber]; exact Z.to_fiber_bundle_core.local_triv i /-- The standard local trivializations of a vector bundle constructed from core are linear. -/ instance local_triv.is_linear (i : ι) : (Z.local_triv i).is_linear R := { linear := λ x hx, by dsimp [vector_bundle_core.local_triv]; exact { map_add := λ v w, by simp only [continuous_linear_map.map_add] with mfld_simps, map_smul := λ r v, by simp only [continuous_linear_map.map_smul] with mfld_simps} } variables (i j : ι) @[simp, mfld_simps] lemma mem_local_triv_source (p : Z.total_space) : p ∈ (Z.local_triv i).source ↔ p.1 ∈ Z.base_set i := by dsimp [vector_bundle_core.fiber]; exact iff.rfl @[simp, mfld_simps] lemma base_set_at : Z.base_set i = (Z.local_triv i).base_set := rfl @[simp, mfld_simps] lemma local_triv_apply (p : Z.total_space) : (Z.local_triv i) p = ⟨p.1, Z.coord_change (Z.index_at p.1) i p.1 p.2⟩ := rfl @[simp, mfld_simps] lemma mem_local_triv_target (p : B × F) : p ∈ (Z.local_triv i).target ↔ p.1 ∈ (Z.local_triv i).base_set := Z.to_fiber_bundle_core.mem_local_triv_target i p @[simp, mfld_simps] lemma local_triv_symm_fst (p : B × F) : (Z.local_triv i).to_local_homeomorph.symm p = ⟨p.1, Z.coord_change i (Z.index_at p.1) p.1 p.2⟩ := rfl @[simp, mfld_simps] lemma local_triv_symm_apply {b : B} (hb : b ∈ Z.base_set i) (v : F) : (Z.local_triv i).symm b v = Z.coord_change i (Z.index_at b) b v := by apply (Z.local_triv i).symm_apply hb v @[simp, mfld_simps] lemma local_triv_coord_change_eq {b : B} (hb : b ∈ Z.base_set i ∩ Z.base_set j) (v : F) : (Z.local_triv i).coord_changeL R (Z.local_triv j) b v = Z.coord_change i j b v := begin rw [trivialization.coord_changeL_apply', local_triv_symm_fst, local_triv_apply, coord_change_comp], exacts [⟨⟨hb.1, Z.mem_base_set_at b⟩, hb.2⟩, hb] end /-- Preferred local trivialization of a vector bundle constructed from core, at a given point, as a bundle trivialization -/ def local_triv_at (b : B) : trivialization F (π F Z.fiber) := Z.local_triv (Z.index_at b) @[simp, mfld_simps] lemma local_triv_at_def : Z.local_triv (Z.index_at b) = Z.local_triv_at b := rfl @[simp, mfld_simps] lemma mem_source_at : (⟨b, a⟩ : Z.total_space) ∈ (Z.local_triv_at b).source := by { rw [local_triv_at, mem_local_triv_source], exact Z.mem_base_set_at b } @[simp, mfld_simps] lemma local_triv_at_apply (p : Z.total_space) : ((Z.local_triv_at p.1) p) = ⟨p.1, p.2⟩ := fiber_bundle_core.local_triv_at_apply Z p @[simp, mfld_simps] lemma local_triv_at_apply_mk (b : B) (a : F) : ((Z.local_triv_at b) ⟨b, a⟩) = ⟨b, a⟩ := Z.local_triv_at_apply _ @[simp, mfld_simps] lemma mem_local_triv_at_base_set : b ∈ (Z.local_triv_at b).base_set := fiber_bundle_core.mem_local_triv_at_base_set Z b instance fiber_bundle : fiber_bundle F Z.fiber := Z.to_fiber_bundle_core.fiber_bundle instance vector_bundle : vector_bundle R F Z.fiber := { trivialization_linear' := begin rintros _ ⟨i, rfl⟩, apply local_triv.is_linear, end, continuous_on_coord_change' := begin rintros _ _ ⟨i, rfl⟩ ⟨i', rfl⟩, refine (Z.continuous_on_coord_change i i').congr (λ b hb, _), ext v, exact Z.local_triv_coord_change_eq i i' hb v, end } /-- The projection on the base of a vector bundle created from core is continuous -/ @[continuity] lemma continuous_proj : continuous Z.proj := fiber_bundle_core.continuous_proj Z /-- The projection on the base of a vector bundle created from core is an open map -/ lemma is_open_map_proj : is_open_map Z.proj := fiber_bundle_core.is_open_map_proj Z variables {i j} @[simp, mfld_simps] lemma local_triv_continuous_linear_map_at {b : B} (hb : b ∈ Z.base_set i) : (Z.local_triv i).continuous_linear_map_at R b = Z.coord_change (Z.index_at b) i b := begin ext1 v, rw [(Z.local_triv i).continuous_linear_map_at_apply R, (Z.local_triv i).coe_linear_map_at_of_mem], exacts [rfl, hb] end @[simp, mfld_simps] lemma trivialization_at_continuous_linear_map_at {b₀ b : B} (hb : b ∈ (trivialization_at F Z.fiber b₀).base_set) : (trivialization_at F Z.fiber b₀).continuous_linear_map_at R b = Z.coord_change (Z.index_at b) (Z.index_at b₀) b := Z.local_triv_continuous_linear_map_at hb @[simp, mfld_simps] lemma local_triv_symmL {b : B} (hb : b ∈ Z.base_set i) : (Z.local_triv i).symmL R b = Z.coord_change i (Z.index_at b) b := by { ext1 v, rw [(Z.local_triv i).symmL_apply R, (Z.local_triv i).symm_apply], exacts [rfl, hb] } @[simp, mfld_simps] lemma trivialization_at_symmL {b₀ b : B} (hb : b ∈ (trivialization_at F Z.fiber b₀).base_set) : (trivialization_at F Z.fiber b₀).symmL R b = Z.coord_change (Z.index_at b₀) (Z.index_at b) b := Z.local_triv_symmL hb @[simp, mfld_simps] lemma trivialization_at_coord_change_eq {b₀ b₁ b : B} (hb : b ∈ (trivialization_at F Z.fiber b₀).base_set ∩ (trivialization_at F Z.fiber b₁).base_set) (v : F) : (trivialization_at F Z.fiber b₀).coord_changeL R (trivialization_at F Z.fiber b₁) b v = Z.coord_change (Z.index_at b₀) (Z.index_at b₁) b v := Z.local_triv_coord_change_eq _ _ hb v end vector_bundle_core end /-! ### Vector prebundle -/ section variables [nontrivially_normed_field R] [∀ x, add_comm_monoid (E x)] [∀ x, module R (E x)] [normed_add_comm_group F] [normed_space R F] [topological_space B] [∀ x, topological_space (E x)] open topological_space open vector_bundle /-- This structure permits to define a vector bundle when trivializations are given as local equivalences but there is not yet a topology on the total space or the fibers. The total space is hence given a topology in such a way that there is a fiber bundle structure for which the local equivalences are also local homeomorphisms and hence vector bundle trivializations. The topology on the fibers is induced from the one on the total space. The field `exists_coord_change` is stated as an existential statement (instead of 3 separate fields), since it depends on propositional information (namely `e e' ∈ pretrivialization_atlas`). This makes it inconvenient to explicitly define a `coord_change` function when constructing a `vector_prebundle`. -/ @[nolint has_nonempty_instance] structure vector_prebundle := (pretrivialization_atlas : set (pretrivialization F (π F E))) (pretrivialization_linear' : ∀ (e : pretrivialization F (π F E)) (he : e ∈ pretrivialization_atlas), e.is_linear R) (pretrivialization_at : B → pretrivialization F (π F E)) (mem_base_pretrivialization_at : ∀ x : B, x ∈ (pretrivialization_at x).base_set) (pretrivialization_mem_atlas : ∀ x : B, pretrivialization_at x ∈ pretrivialization_atlas) (exists_coord_change : ∀ (e e' ∈ pretrivialization_atlas), ∃ f : B → F →L[R] F, continuous_on f (e.base_set ∩ e'.base_set) ∧ ∀ (b : B) (hb : b ∈ e.base_set ∩ e'.base_set) (v : F), f b v = (e' ⟨b, e.symm b v⟩).2) (total_space_mk_inducing : ∀ (b : B), inducing ((pretrivialization_at b) ∘ (total_space.mk b))) namespace vector_prebundle variables {R E F} /-- A randomly chosen coordinate change on a `vector_prebundle`, given by the field `exists_coord_change`. -/ def coord_change (a : vector_prebundle R F E) {e e' : pretrivialization F (π F E)} (he : e ∈ a.pretrivialization_atlas) (he' : e' ∈ a.pretrivialization_atlas) (b : B) : F →L[R] F := classical.some (a.exists_coord_change e he e' he') b lemma continuous_on_coord_change (a : vector_prebundle R F E) {e e' : pretrivialization F (π F E)} (he : e ∈ a.pretrivialization_atlas) (he' : e' ∈ a.pretrivialization_atlas) : continuous_on (a.coord_change he he') (e.base_set ∩ e'.base_set) := (classical.some_spec (a.exists_coord_change e he e' he')).1 lemma coord_change_apply (a : vector_prebundle R F E) {e e' : pretrivialization F (π F E)} (he : e ∈ a.pretrivialization_atlas) (he' : e' ∈ a.pretrivialization_atlas) {b : B} (hb : b ∈ e.base_set ∩ e'.base_set) (v : F) : a.coord_change he he' b v = (e' ⟨b, e.symm b v⟩).2 := (classical.some_spec (a.exists_coord_change e he e' he')).2 b hb v lemma mk_coord_change (a : vector_prebundle R F E) {e e' : pretrivialization F (π F E)} (he : e ∈ a.pretrivialization_atlas) (he' : e' ∈ a.pretrivialization_atlas) {b : B} (hb : b ∈ e.base_set ∩ e'.base_set) (v : F) : (b, a.coord_change he he' b v) = e' ⟨b, e.symm b v⟩ := begin ext, { rw [e.mk_symm hb.1 v, e'.coe_fst', e.proj_symm_apply' hb.1], rw [e.proj_symm_apply' hb.1], exact hb.2 }, { exact a.coord_change_apply he he' hb v } end /-- Natural identification of `vector_prebundle` as a `fiber_prebundle`. -/ def to_fiber_prebundle (a : vector_prebundle R F E) : fiber_prebundle F E := { continuous_triv_change := begin intros e he e' he', have := is_bounded_bilinear_map_apply.continuous.comp_continuous_on ((a.continuous_on_coord_change he' he).prod_map continuous_on_id), have H : e'.to_local_equiv.target ∩ e'.to_local_equiv.symm ⁻¹' e.to_local_equiv.source =(e'.base_set ∩ e.base_set) ×ˢ univ, { rw [e'.target_eq, e.source_eq], ext ⟨b, f⟩, simp only [-total_space.proj, and.congr_right_iff, e'.proj_symm_apply', iff_self, implies_true_iff] with mfld_simps {contextual := tt} }, rw [H], refine (continuous_on_fst.prod this).congr _, rintros ⟨b, f⟩ ⟨hb, -⟩, dsimp only [function.comp, prod.map], rw [a.mk_coord_change _ _ hb, e'.mk_symm hb.1], refl, end, .. a } /-- Topology on the total space that will make the prebundle into a bundle. -/ def total_space_topology (a : vector_prebundle R F E) : topological_space (total_space F E) := a.to_fiber_prebundle.total_space_topology /-- Promotion from a `trivialization` in the `pretrivialization_atlas` of a `vector_prebundle` to a `trivialization`. -/ def trivialization_of_mem_pretrivialization_atlas (a : vector_prebundle R F E) {e : pretrivialization F (π F E)} (he : e ∈ a.pretrivialization_atlas) : @trivialization B F _ _ _ a.total_space_topology (π F E) := a.to_fiber_prebundle.trivialization_of_mem_pretrivialization_atlas he lemma linear_of_mem_pretrivialization_atlas (a : vector_prebundle R F E) {e : pretrivialization F (π F E)} (he : e ∈ a.pretrivialization_atlas) : @trivialization.is_linear R B F _ _ _ _ a.total_space_topology _ _ _ _ (trivialization_of_mem_pretrivialization_atlas a he) := { linear := (a.pretrivialization_linear' e he).linear } variable (a : vector_prebundle R F E) lemma mem_trivialization_at_source (b : B) (x : E b) : total_space.mk b x ∈ (a.pretrivialization_at b).source := a.to_fiber_prebundle.mem_trivialization_at_source b x @[simp] lemma total_space_mk_preimage_source (b : B) : (total_space.mk b) ⁻¹' (a.pretrivialization_at b).source = univ := a.to_fiber_prebundle.total_space_mk_preimage_source b @[continuity] lemma continuous_total_space_mk (b : B) : @continuous _ _ _ a.total_space_topology (total_space.mk b) := a.to_fiber_prebundle.continuous_total_space_mk b /-- Make a `fiber_bundle` from a `vector_prebundle`; auxiliary construction for `vector_prebundle.vector_bundle`. -/ def to_fiber_bundle : @fiber_bundle B F _ _ _ a.total_space_topology _ := a.to_fiber_prebundle.to_fiber_bundle /-- Make a `vector_bundle` from a `vector_prebundle`. Concretely this means that, given a `vector_prebundle` structure for a sigma-type `E` -- which consists of a number of "pretrivializations" identifying parts of `E` with product spaces `U × F` -- one establishes that for the topology constructed on the sigma-type using `vector_prebundle.total_space_topology`, these "pretrivializations" are actually "trivializations" (i.e., homeomorphisms with respect to the constructed topology). -/ lemma to_vector_bundle : @vector_bundle R _ F E _ _ _ _ _ _ a.total_space_topology _ a.to_fiber_bundle := { trivialization_linear' := begin rintros _ ⟨e, he, rfl⟩, apply linear_of_mem_pretrivialization_atlas, end, continuous_on_coord_change' := begin rintros _ _ ⟨e, he, rfl⟩ ⟨e', he', rfl⟩, refine (a.continuous_on_coord_change he he').congr _, intros b hb, ext v, rw [a.coord_change_apply he he' hb v, continuous_linear_equiv.coe_coe, trivialization.coord_changeL_apply], exacts [rfl, hb] end } end vector_prebundle namespace continuous_linear_map variables {𝕜₁ 𝕜₂ : Type*} [nontrivially_normed_field 𝕜₁] [nontrivially_normed_field 𝕜₂] variables {σ : 𝕜₁ →+* 𝕜₂} variables {B' : Type*} [topological_space B'] variables [normed_space 𝕜₁ F] [Π x, module 𝕜₁ (E x)] [topological_space (total_space F E)] variables {F' : Type*} [normed_add_comm_group F'] [normed_space 𝕜₂ F'] {E' : B' → Type*} [Π x, add_comm_monoid (E' x)] [Π x, module 𝕜₂ (E' x)] [topological_space (total_space F' E')] variables [fiber_bundle F E] [vector_bundle 𝕜₁ F E] variables [Π x, topological_space (E' x)] [fiber_bundle F' E'] [vector_bundle 𝕜₂ F' E'] variables (F E F' E') /-- When `ϕ` is a continuous (semi)linear map between the fibers `E x` and `E' y` of two vector bundles `E` and `E'`, `continuous_linear_map.in_coordinates F E F' E' x₀ x y₀ y ϕ` is a coordinate change of this continuous linear map w.r.t. the chart around `x₀` and the chart around `y₀`. It is defined by composing `ϕ` with appropriate coordinate changes given by the vector bundles `E` and `E'`. We use the operations `trivialization.continuous_linear_map_at` and `trivialization.symmL` in the definition, instead of `trivialization.continuous_linear_equiv_at`, so that `continuous_linear_map.in_coordinates` is defined everywhere (but see `continuous_linear_map.in_coordinates_eq`). This is the (second component of the) underlying function of a trivialization of the hom-bundle (see `hom_trivialization_at_apply`). However, note that `continuous_linear_map.in_coordinates` is defined even when `x` and `y` live in different base sets. Therefore, it is is also convenient when working with the hom-bundle between pulled back bundles. -/ def in_coordinates (x₀ x : B) (y₀ y : B') (ϕ : E x →SL[σ] E' y) : F →SL[σ] F' := ((trivialization_at F' E' y₀).continuous_linear_map_at 𝕜₂ y).comp $ ϕ.comp $ (trivialization_at F E x₀).symmL 𝕜₁ x variables {F F'} /-- rewrite `in_coordinates` using continuous linear equivalences. -/ lemma in_coordinates_eq (x₀ x : B) (y₀ y : B') (ϕ : E x →SL[σ] E' y) (hx : x ∈ (trivialization_at F E x₀).base_set) (hy : y ∈ (trivialization_at F' E' y₀).base_set) : in_coordinates F E F' E' x₀ x y₀ y ϕ = ((trivialization_at F' E' y₀).continuous_linear_equiv_at 𝕜₂ y hy : E' y →L[𝕜₂] F').comp (ϕ.comp $ (((trivialization_at F E x₀).continuous_linear_equiv_at 𝕜₁ x hx).symm : F →L[𝕜₁] E x)) := begin ext, simp_rw [in_coordinates, continuous_linear_map.coe_comp', continuous_linear_equiv.coe_coe, trivialization.coe_continuous_linear_equiv_at_eq, trivialization.symm_continuous_linear_equiv_at_eq] end /-- rewrite `in_coordinates` in a `vector_bundle_core`. -/ protected lemma vector_bundle_core.in_coordinates_eq {ι ι'} (Z : vector_bundle_core 𝕜₁ B F ι) (Z' : vector_bundle_core 𝕜₂ B' F' ι') {x₀ x : B} {y₀ y : B'} (ϕ : F →SL[σ] F') (hx : x ∈ Z.base_set (Z.index_at x₀)) (hy : y ∈ Z'.base_set (Z'.index_at y₀)) : in_coordinates F Z.fiber F' Z'.fiber x₀ x y₀ y ϕ = (Z'.coord_change (Z'.index_at y) (Z'.index_at y₀) y).comp (ϕ.comp $ Z.coord_change (Z.index_at x₀) (Z.index_at x) x) := by simp_rw [in_coordinates, Z'.trivialization_at_continuous_linear_map_at hy, Z.trivialization_at_symmL hx] end continuous_linear_map end
f44098b3b32ab39420bacc0183ff800308f7c217
ad0c7d243dc1bd563419e2767ed42fb323d7beea
/set_theory/lists.lean
b1692c849d3eae5dd8184964cc8e1e4fa4fcf18e
[ "Apache-2.0" ]
permissive
sebzim4500/mathlib
e0b5a63b1655f910dee30badf09bd7e191d3cf30
6997cafbd3a7325af5cb318561768c316ceb7757
refs/heads/master
1,585,549,958,618
1,538,221,723,000
1,538,221,723,000
150,869,076
0
0
Apache-2.0
1,538,229,323,000
1,538,229,323,000
null
UTF-8
Lean
false
false
11,704
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro A computable model of hereditarily finite sets with atoms (ZFA without infinity). This is useful for calculations in naive set theory. -/ import tactic.interactive data.list.basic variables {α : Type*} @[derive decidable_eq] inductive {u} lists' (α : Type u) : bool → Type u | atom : α → lists' ff | nil {} : lists' tt | cons' {b} : lists' b → lists' tt → lists' tt def lists (α : Type*) := Σ b, lists' α b namespace lists' def cons : lists α → lists' α tt → lists' α tt | ⟨b, a⟩ l := cons' a l @[simp] def to_list : ∀ {b}, lists' α b → list (lists α) | _ (atom a) := [] | _ nil := [] | _ (cons' a l) := ⟨_, a⟩ :: l.to_list @[simp] theorem to_list_cons (a : lists α) (l) : to_list (cons a l) = a :: l.to_list := by cases a; simp [cons] @[simp] def of_list : list (lists α) → lists' α tt | [] := nil | (a :: l) := cons a (of_list l) @[simp] theorem to_of_list (l : list (lists α)) : to_list (of_list l) = l := by induction l; simp * @[simp] theorem of_to_list : ∀ (l : lists' α tt), of_list (to_list l) = l := suffices ∀ b (h : tt = b) (l : lists' α b), let l' : lists' α tt := by rw h; exact l in of_list (to_list l') = l', from this _ rfl, λ b h l, begin induction l, {cases h}, {exact rfl}, case lists'.cons' : b a l IH₁ IH₂ { intro, change l' with cons' a l, simpa [cons] using IH₂ rfl } end end lists' mutual inductive lists.equiv, lists'.subset with lists.equiv : lists α → lists α → Prop | refl (l) : lists.equiv l l | antisymm {l₁ l₂ : lists' α tt} : lists'.subset l₁ l₂ → lists'.subset l₂ l₁ → lists.equiv ⟨_, l₁⟩ ⟨_, l₂⟩ with lists'.subset : lists' α tt → lists' α tt → Prop | nil {l} : lists'.subset lists'.nil l | cons {a a' l l'} : lists.equiv a a' → a' ∈ lists'.to_list l' → lists'.subset l l' → lists'.subset (lists'.cons a l) l' local infix ~ := equiv namespace lists' instance : has_subset (lists' α tt) := ⟨lists'.subset⟩ instance {b} : has_mem (lists α) (lists' α b) := ⟨λ a l, ∃ a' ∈ l.to_list, a ~ a'⟩ theorem mem_def {b a} {l : lists' α b} : a ∈ l ↔ ∃ a' ∈ l.to_list, a ~ a' := iff.rfl @[simp] theorem mem_cons {a y l} : a ∈ @cons α y l ↔ a ~ y ∨ a ∈ l := by simp [mem_def, or_and_distrib_right, exists_or_distrib] theorem cons_subset {a} {l₁ l₂ : lists' α tt} : lists'.cons a l₁ ⊆ l₂ ↔ a ∈ l₂ ∧ l₁ ⊆ l₂ := begin refine ⟨λ h, _, λ ⟨⟨a', m, e⟩, s⟩, subset.cons e m s⟩, generalize_hyp h' : lists'.cons a l₁ = l₁' at h, cases h with l a' a'' l l' e m s, {cases a, cases h'}, cases a, cases a', cases h', exact ⟨⟨_, m, e⟩, s⟩ end theorem of_list_subset {l₁ l₂ : list (lists α)} (h : l₁ ⊆ l₂) : lists'.of_list l₁ ⊆ lists'.of_list l₂ := begin induction l₁, {exact subset.nil}, refine subset.cons (equiv.refl _) _ (l₁_ih (list.subset_of_cons_subset h)), simp at h, simp [h] end @[refl] theorem subset.refl {l : lists' α tt} : l ⊆ l := by rw ← lists'.of_to_list l; exact of_list_subset (list.subset.refl _) theorem subset_nil {l : lists' α tt} : l ⊆ lists'.nil → l = lists'.nil := begin rw ← of_to_list l, induction to_list l; intro h, {refl}, rcases cons_subset.1 h with ⟨⟨_, ⟨⟩, _⟩, _⟩ end theorem mem_of_subset' {a} {l₁ l₂ : lists' α tt} (s : l₁ ⊆ l₂) (h : a ∈ l₁.to_list) : a ∈ l₂ := begin induction s with _ a a' l l' e m s IH, {cases h}, simp at h, rcases h with rfl|h, exacts [⟨_, m, e⟩, IH h] end theorem subset_def {l₁ l₂ : lists' α tt} : l₁ ⊆ l₂ ↔ ∀ a ∈ l₁.to_list, a ∈ l₂ := ⟨λ H a, mem_of_subset' H, λ H, begin rw ← of_to_list l₁, revert H, induction to_list l₁; intro, { exact subset.nil }, { simp at H, exact cons_subset.2 ⟨H.1, ih H.2⟩ } end⟩ end lists' namespace lists @[pattern] def atom (a : α) : lists α := ⟨_, lists'.atom a⟩ @[pattern] def of' (l : lists' α tt) : lists α := ⟨_, l⟩ @[simp] def to_list : lists α → list (lists α) | ⟨b, l⟩ := l.to_list def is_list (l : lists α) : Prop := l.1 def of_list (l : list (lists α)) : lists α := of' (lists'.of_list l) theorem is_list_to_list (l : list (lists α)) : is_list (of_list l) := eq.refl _ theorem to_of_list (l : list (lists α)) : to_list (of_list l) = l := by simp [of_list, of'] theorem of_to_list : ∀ {l : lists α}, is_list l → of_list (to_list l) = l | ⟨tt, l⟩ _ := by simp [of_list, of'] instance [decidable_eq α] : decidable_eq (lists α) := by unfold lists; apply_instance instance [has_sizeof α] : has_sizeof (lists α) := by unfold lists; apply_instance def induction_mut (C : lists α → Sort*) (D : lists' α tt → Sort*) (C0 : ∀ a, C (atom a)) (C1 : ∀ l, D l → C (of' l)) (D0 : D lists'.nil) (D1 : ∀ a l, C a → D l → D (lists'.cons a l)) : pprod (∀ l, C l) (∀ l, D l) := begin suffices : ∀ {b} (l : lists' α b), pprod (C ⟨_, l⟩) (match b, l with | tt, l := D l | ff, l := punit end), { exact ⟨λ ⟨b, l⟩, (this _).1, λ l, (this l).2⟩ }, intros, induction l with a b a l IH₁ IH₂, { exact ⟨C0 _, ⟨⟩⟩ }, { exact ⟨C1 _ D0, D0⟩ }, { suffices, {exact ⟨C1 _ this, this⟩}, exact D1 ⟨_, _⟩ _ IH₁.1 IH₂.2 } end def mem (a : lists α) : lists α → Prop | ⟨ff, l⟩ := false | ⟨tt, l⟩ := a ∈ l instance : has_mem (lists α) (lists α) := ⟨mem⟩ theorem is_list_of_mem {a : lists α} : ∀ {l : lists α}, a ∈ l → is_list l | ⟨_, lists'.nil⟩ _ := rfl | ⟨_, lists'.cons' _ _⟩ _ := rfl theorem equiv.antisymm_iff {l₁ l₂ : lists' α tt} : of' l₁ ~ of' l₂ ↔ l₁ ⊆ l₂ ∧ l₂ ⊆ l₁ := begin refine ⟨λ h, _, λ ⟨h₁, h₂⟩, equiv.antisymm h₁ h₂⟩, cases h with _ _ _ h₁ h₂, { simp [lists'.subset.refl] }, { exact ⟨h₁, h₂⟩ } end attribute [refl] equiv.refl theorem equiv_atom {a} {l : lists α} : atom a ~ l ↔ atom a = l := ⟨λ h, by cases h; refl, λ h, h ▸ equiv.refl _⟩ theorem equiv.symm {l₁ l₂ : lists α} (h : l₁ ~ l₂) : l₂ ~ l₁ := by cases h with _ _ _ h₁ h₂; [refl, exact equiv.antisymm h₂ h₁] theorem equiv.trans : ∀ {l₁ l₂ l₃ : lists α}, l₁ ~ l₂ → l₂ ~ l₃ → l₁ ~ l₃ := begin let trans := λ (l₁ : lists α), ∀ ⦃l₂ l₃⦄, l₁ ~ l₂ → l₂ ~ l₃ → l₁ ~ l₃, suffices : pprod (∀ l₁, trans l₁) (∀ (l : lists' α tt) (l' ∈ l.to_list), trans l'), {exact this.1}, apply induction_mut, { intros a l₂ l₃ h₁ h₂, rwa ← equiv_atom.1 h₁ at h₂ }, { intros l₁ IH l₂ l₃ h₁ h₂, cases h₁ with _ _ l₂, {exact h₂}, cases h₂ with _ _ l₃, {exact h₁}, cases equiv.antisymm_iff.1 h₁ with hl₁ hr₁, cases equiv.antisymm_iff.1 h₂ with hl₂ hr₂, apply equiv.antisymm_iff.2; split; apply lists'.subset_def.2, { intros a₁ m₁, rcases lists'.mem_of_subset' hl₁ m₁ with ⟨a₂, m₂, e₁₂⟩, rcases lists'.mem_of_subset' hl₂ m₂ with ⟨a₃, m₃, e₂₃⟩, exact ⟨a₃, m₃, IH _ m₁ e₁₂ e₂₃⟩ }, { intros a₃ m₃, rcases lists'.mem_of_subset' hr₂ m₃ with ⟨a₂, m₂, e₃₂⟩, rcases lists'.mem_of_subset' hr₁ m₂ with ⟨a₁, m₁, e₂₁⟩, exact ⟨a₁, m₁, (IH _ m₁ e₂₁.symm e₃₂.symm).symm⟩ } }, { rintro _ ⟨⟩ }, { intros a l IH₁ IH₂, simpa [IH₁] using IH₂ } end instance : setoid (lists α) := ⟨(~), equiv.refl, @equiv.symm _, @equiv.trans _⟩ section decidable @[simp] def equiv.decidable_meas : (psum (Σ' (l₁ : lists α), lists α) $ psum (Σ' (l₁ : lists' α tt), lists' α tt) Σ' (a : lists α), lists' α tt) → ℕ | (psum.inl ⟨l₁, l₂⟩) := sizeof l₁ + sizeof l₂ | (psum.inr $ psum.inl ⟨l₁, l₂⟩) := sizeof l₁ + sizeof l₂ | (psum.inr $ psum.inr ⟨l₁, l₂⟩) := sizeof l₁ + sizeof l₂ local attribute [-simp] add_comm add_assoc open well_founded_tactics theorem sizeof_pos {b} (l : lists' α b) : 0 < sizeof l := by cases l; {unfold_sizeof, trivial_nat_lt} theorem lt_sizeof_cons' {b} (a : lists' α b) (l) : sizeof (⟨b, a⟩ : lists α) < sizeof (lists'.cons' a l) := by {unfold_sizeof, exact lt_add_of_pos_right _ (sizeof_pos _)} @[instance] mutual def equiv.decidable, subset.decidable, mem.decidable [decidable_eq α] with equiv.decidable : ∀ l₁ l₂ : lists α, decidable (l₁ ~ l₂) | ⟨ff, l₁⟩ ⟨ff, l₂⟩ := decidable_of_iff' (l₁ = l₂) $ by cases l₁; refine equiv_atom.trans (by simp [atom]) | ⟨ff, l₁⟩ ⟨tt, l₂⟩ := is_false $ by rintro ⟨⟩ | ⟨tt, l₁⟩ ⟨ff, l₂⟩ := is_false $ by rintro ⟨⟩ | ⟨tt, l₁⟩ ⟨tt, l₂⟩ := begin haveI := have sizeof l₁ + sizeof l₂ < sizeof (⟨tt, l₁⟩ : lists α) + sizeof (⟨tt, l₂⟩ : lists α), by default_dec_tac, subset.decidable l₁ l₂, haveI := have sizeof l₂ + sizeof l₁ < sizeof (⟨tt, l₁⟩ : lists α) + sizeof (⟨tt, l₂⟩ : lists α), by default_dec_tac, subset.decidable l₂ l₁, exact decidable_of_iff' _ equiv.antisymm_iff, end with subset.decidable : ∀ l₁ l₂ : lists' α tt, decidable (l₁ ⊆ l₂) | lists'.nil l₂ := is_true subset.nil | (@lists'.cons' _ b a l₁) l₂ := begin haveI := have sizeof (⟨b, a⟩ : lists α) + sizeof l₂ < sizeof (lists'.cons' a l₁) + sizeof l₂, from add_lt_add_right (lt_sizeof_cons' _ _) _, mem.decidable ⟨b, a⟩ l₂, haveI := have sizeof l₁ + sizeof l₂ < sizeof (lists'.cons' a l₁) + sizeof l₂, by default_dec_tac, subset.decidable l₁ l₂, exact decidable_of_iff' _ (@lists'.cons_subset _ ⟨_, _⟩ _ _) end with mem.decidable : ∀ (a : lists α) (l : lists' α tt), decidable (a ∈ l) | a lists'.nil := is_false $ by rintro ⟨_, ⟨⟩, _⟩ | a (lists'.cons' b l₂) := begin haveI := have sizeof a + sizeof (⟨_, b⟩ : lists α) < sizeof a + sizeof (lists'.cons' b l₂), from add_lt_add_left (lt_sizeof_cons' _ _) _, equiv.decidable a ⟨_, b⟩, haveI := have sizeof a + sizeof l₂ < sizeof a + sizeof (lists'.cons' b l₂), by default_dec_tac, mem.decidable a l₂, refine decidable_of_iff' (a ~ ⟨_, b⟩ ∨ a ∈ l₂) _, rw ← lists'.mem_cons, refl end using_well_founded { rel_tac := λ _ _, `[exact ⟨_, measure_wf equiv.decidable_meas⟩], dec_tac := `[assumption] } end decidable end lists namespace lists' theorem mem_equiv_left {l : lists' α tt} : ∀ {a a'}, a ~ a' → (a ∈ l ↔ a' ∈ l) := suffices ∀ {a a'}, a ~ a' → a ∈ l → a' ∈ l, from λ a a' e, ⟨this e, this e.symm⟩, λ a₁ a₂ e₁ ⟨a₃, m₃, e₂⟩, ⟨_, m₃, e₁.symm.trans e₂⟩ theorem mem_of_subset {a} {l₁ l₂ : lists' α tt} (s : l₁ ⊆ l₂) : a ∈ l₁ → a ∈ l₂ | ⟨a', m, e⟩ := (mem_equiv_left e).2 (mem_of_subset' s m) theorem subset.trans {l₁ l₂ l₃ : lists' α tt} (h₁ : l₁ ⊆ l₂) (h₂ : l₂ ⊆ l₃) : l₁ ⊆ l₃ := subset_def.2 $ λ a₁ m₁, mem_of_subset h₂ $ mem_of_subset' h₁ m₁ end lists' def finsets (α : Type*) := quotient (@lists.setoid α) namespace finsets instance : has_emptyc (finsets α) := ⟨⟦lists.of' lists'.nil⟧⟩ instance [decidable_eq α] : decidable_eq (finsets α) := by unfold finsets; apply_instance end finsets
75c05dd494127266e6518a978a60290fa11b3073
6b2a480f27775cba4f3ae191b1c1387a29de586e
/group_rep1/test.lean
827263027cb47c11527159191574b902b1f36a99
[]
no_license
Or7ando/group_representation
a681de2e19d1930a1e1be573d6735a2f0b8356cb
9b576984f17764ebf26c8caa2a542d248f1b50d2
refs/heads/master
1,662,413,107,324
1,590,302,389,000
1,590,302,389,000
258,130,829
0
1
null
null
null
null
UTF-8
Lean
false
false
162
lean
import tactic variables (ℓ : Type) (B : Prop) (C : ℓ → Prop) def axiom_5: (∀ x : ℓ , B → C x) → (B → (∀ x : ℓ , C x)) := begin finish, end
da8812910b07486806b58335dd3d531f1c9f259b
e0e64c424bf126977aef10e58324934782979062
/src/wk1/Exercises/exercises.lean
22bd519494d2c9d5cf33671436467653bfb080c4
[]
no_license
jamesa9283/LiaLeanTutor
34e9e133a4f7dd415f02c14c4a62351bb9fd8c21
c7ac1400f26eb2992f5f1ee0aaafb54b74665072
refs/heads/master
1,686,146,337,422
1,625,227,392,000
1,625,227,392,000
373,130,175
0
0
null
null
null
null
UTF-8
Lean
false
false
544
lean
import logic.basic -- Needed for imp_false section question11 variables P Q R : Prop example (h : P ∧ (Q ∧ R)) : (P ∧ Q) ∧ R := begin sorry end end question11 section question6 variables P Q R : Prop example : (P ∧ R) ∨ (Q ∧ R) → (P ∨ Q) ∧ R := begin sorry end end question6 section question9 variables A B C : Prop example (h : C → A ∨ B) : (C ∧ ¬A) → B := begin sorry end -- HINT: for this question, you may find it useful to to use `exfalso, contradiction` somewhere in the proof end question9
2764079482ac286cc9c7833c5868c6da27a624b1
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/library/init/category/alternative.lean
182266bee2872d54352fca60f163f3e19cc57c3c
[ "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
1,082
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.logic init.category.applicative universes u v class alternative (f : Type u → Type v) extends applicative f : Type (max u+1 v) := (failure : Π {a : Type u}, f a) (orelse : Π {a : Type u}, f a → f a → f a) section variables {f : Type u → Type v} [alternative f] {a : Type u} @[inline] def failure : f a := alternative.failure f @[inline] def orelse : f a → f a → f a := alternative.orelse infixr ` <|> `:2 := orelse @[inline] def guard {f : Type → Type v} [alternative f] (p : Prop) [decidable p] : f unit := if p then pure () else failure /- Later we define a coercion from bool to Prop, but this version will still be useful. Given (t : tactic bool), we can write t >>= guardb -/ @[inline] def guardb {f : Type → Type v} [alternative f] : bool → f unit | tt := pure () | ff := failure @[inline] def optional (x : f a) : f (option a) := some <$> x <|> pure none end
518cbc391469492dbf63ecc21a1a4f38d0d907ca
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/linear_algebra/invariant_basis_number.lean
b5e2aa8c9353b82c015b3782c579ddad967f4fd8
[ "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
9,165
lean
/- Copyright (c) 2020 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel, Scott Morrison -/ import ring_theory.principal_ideal_domain import ring_theory.ideal.basic /-! # Invariant basis number property We say that a ring `R` satisfies the invariant basis number property if there is a well-defined notion of the rank of a finitely generated free (left) `R`-module. Since a finitely generated free module with a basis consisting of `n` elements is linearly equivalent to `fin n → R`, it is sufficient that `(fin n → R) ≃ₗ[R] (fin m → R)` implies `n = m`. It is also useful to consider two stronger conditions, namely the rank condition, that a surjective linear map `(fin n → R) →ₗ[R] (fin m → R)` implies `m ≤ n` and the strong rank condition, that an injective linear map `(fin n → R) →ₗ[R] (fin m → R)` implies `n ≤ m`. The strong rank condition implies the rank condition, and the rank condition implies the invariant basis number property. ## Main definitions `strong_rank_condition R` is a type class stating that `R` satisfies the strong rank condition. `rank_condition R` is a type class stating that `R` satisfies the rank condition. `invariant_basis_number R` is a type class stating that `R` has the invariant basis number property. ## Main results We show that every nontrivial left-noetherian ring satisfies the strong rank condition, (and so in particular every division ring or field), and then use this to show every nontrivial commutative ring has the invariant basis number property. ## Future work We can improve these results: in fact every commutative ring satisfies the strong rank condition. So far, there is no API at all for the `invariant_basis_number` class. There are several natural ways to formulate that a module `M` is finitely generated and free, for example `M ≃ₗ[R] (fin n → R)`, `M ≃ₗ[R] (ι → R)`, where `ι` is a fintype, or providing a basis indexed by a finite type. There should be lemmas applying the invariant basis number property to each situation. The finite version of the invariant basis number property implies the infinite analogue, i.e., that `(ι →₀ R) ≃ₗ[R] (ι' →₀ R)` implies that `cardinal.mk ι = cardinal.mk ι'`. This fact (and its variants) should be formalized. ## References * https://en.wikipedia.org/wiki/Invariant_basis_number * https://mathoverflow.net/a/2574/ ## Tags free module, rank, invariant basis number, IBN -/ noncomputable theory open_locale classical big_operators open function universes u v w section variables (R : Type u) [ring R] /-- We say that `R` satisfies the strong rank condition if `(fin n → R) →ₗ[R] (fin m → R)` injective implies `n ≤ m`. -/ class strong_rank_condition : Prop := (le_of_fin_injective : ∀ {n m : ℕ} (f : (fin n → R) →ₗ[R] (fin m → R)), injective f → n ≤ m) lemma le_of_fin_injective [strong_rank_condition R] {n m : ℕ} (f : (fin n → R) →ₗ[R] (fin m → R)) : injective f → n ≤ m := strong_rank_condition.le_of_fin_injective f /-- We say that `R` satisfies the rank condition if `(fin n → R) →ₗ[R] (fin m → R)` surjective implies `m ≤ n`. -/ class rank_condition : Prop := (le_of_fin_surjective : ∀ {n m : ℕ} (f : (fin n → R) →ₗ[R] (fin m → R)), surjective f → m ≤ n) lemma le_of_fin_surjective [rank_condition R] {n m : ℕ} (f : (fin n → R) →ₗ[R] (fin m → R)) : surjective f → m ≤ n := rank_condition.le_of_fin_surjective f /-- By the universal property for free modules, any surjective map `(fin n → R) →ₗ[R] (fin m → R)` has an injective splitting `(fin m → R) →ₗ[R] (fin n → R)` from which the strong rank condition gives the necessary inequality for the rank condition. -/ @[priority 100] instance rank_condition_of_strong_rank_condition [strong_rank_condition R] : rank_condition R := { le_of_fin_surjective := λ n m f s, le_of_fin_injective R _ (f.splitting_of_fun_on_fintype_surjective_injective s), } /-- We say that `R` has the invariant basis number property if `(fin n → R) ≃ₗ[R] (fin m → R)` implies `n = m`. This gives rise to a well-defined notion of rank of a finitely generated free module. -/ class invariant_basis_number : Prop := (eq_of_fin_equiv : ∀ {n m : ℕ}, ((fin n → R) ≃ₗ[R] (fin m → R)) → n = m) @[priority 100] instance invariant_basis_number_of_rank_condition [rank_condition R] : invariant_basis_number R := { eq_of_fin_equiv := λ n m e, le_antisymm (le_of_fin_surjective R e.symm.to_linear_map e.symm.surjective) (le_of_fin_surjective R e.to_linear_map e.surjective) } end section variables (R : Type u) [ring R] [invariant_basis_number R] lemma eq_of_fin_equiv {n m : ℕ} : ((fin n → R) ≃ₗ[R] (fin m → R)) → n = m := invariant_basis_number.eq_of_fin_equiv lemma nontrivial_of_invariant_basis_number : nontrivial R := begin by_contra h, refine zero_ne_one (eq_of_fin_equiv R _), haveI := not_nontrivial_iff_subsingleton.1 h, haveI : subsingleton (fin 1 → R) := ⟨λ a b, funext $ λ x, subsingleton.elim _ _⟩, refine { .. }; { intros, exact 0 } <|> tidy end end section variables (R : Type u) [ring R] [nontrivial R] [is_noetherian_ring R] /-- Any nontrivial noetherian ring satisfies the strong rank condition. An injective map `((fin n ⊕ fin (1 + m)) → R) →ₗ[R] (fin n → R)` for some left-noetherian `R` would force `fin (1 + m) → R ≃ₗ punit` (via `is_noetherian.equiv_punit_of_prod_injective`), which is not the case! -/ -- Note this includes fields, -- and we use this below to show any commutative ring has invariant basis number. @[priority 100] instance noetherian_ring_strong_rank_condition : strong_rank_condition R := begin fsplit, intros m n f i, by_contradiction h, rw [not_le, ←nat.add_one_le_iff, le_iff_exists_add] at h, obtain ⟨m, rfl⟩ := h, let e : fin (n + 1 + m) ≃ fin n ⊕ fin (1 + m) := (fin_congr (add_assoc _ _ _)).trans fin_sum_fin_equiv.symm, let f' := f.comp ((linear_equiv.sum_arrow_lequiv_prod_arrow _ _ R R).symm.trans (linear_map.fun_congr_left R R e)).to_linear_map, have i' : injective f' := i.comp (linear_equiv.injective _), apply @zero_ne_one (fin (1 + m) → R) _ _, apply (is_noetherian.equiv_punit_of_prod_injective f' i').injective, ext, end end /-! We want to show that nontrivial commutative rings have invariant basis number. The idea is to take a maximal ideal `I` of `R` and use an isomorphism `R^n ≃ R^m` of `R` modules to produce an isomorphism `(R/I)^n ≃ (R/I)^m` of `R/I`-modules, which will imply `n = m` since `R/I` is a field and we know that fields have invariant basis number. We construct the isomorphism in two steps: 1. We construct the ring `R^n/I^n`, show that it is an `R/I`-module and show that there is an isomorphism of `R/I`-modules `R^n/I^n ≃ (R/I)^n`. This isomorphism is called `ideal.pi_quot_equiv` and is located in the file `ring_theory/ideals.lean`. 2. We construct an isomorphism of `R/I`-modules `R^n/I^n ≃ R^m/I^m` using the isomorphism `R^n ≃ R^m`. -/ section variables {R : Type u} [comm_ring R] (I : ideal R) {ι : Type v} [fintype ι] {ι' : Type w} /-- An `R`-linear map `R^n → R^m` induces a function `R^n/I^n → R^m/I^m`. -/ private def induced_map (I : ideal R) (e : (ι → R) →ₗ[R] (ι' → R)) : (I.pi ι).quotient → (I.pi ι').quotient := λ x, quotient.lift_on' x (λ y, ideal.quotient.mk _ (e y)) begin refine λ a b hab, ideal.quotient.eq.2 (λ h, _), rw ←linear_map.map_sub, exact ideal.map_pi _ _ hab e h, end /-- An isomorphism of `R`-modules `R^n ≃ R^m` induces an isomorphism of `R/I`-modules `R^n/I^n ≃ R^m/I^m`. -/ private def induced_equiv [fintype ι'] (I : ideal R) (e : (ι → R) ≃ₗ[R] (ι' → R)) : (I.pi ι).quotient ≃ₗ[I.quotient] (I.pi ι').quotient := begin refine { to_fun := induced_map I e, inv_fun := induced_map I e.symm, .. }, all_goals { rintro ⟨a⟩ ⟨b⟩ <|> rintro ⟨a⟩, change ideal.quotient.mk _ _ = ideal.quotient.mk _ _, congr, simp } end end section local attribute [instance] ideal.quotient.field -- TODO: in fact, any nontrivial commutative ring satisfies the strong rank condition. -- To see this, consider `f : (fin m → R) →ₗ[R] (fin n → R)`, -- and consider the subring `A` of `R` generated by the matrix entries. -- That subring is noetherian, and `f` induces a new linear map `f' : (fin m → A) →ₗ[R] (fin n → A)` -- which is injective if `f` is. -- Since we've already established the strong rank condition for noetherian rings, -- this gives the result. /-- Nontrivial commutative rings have the invariant basis number property. -/ @[priority 100] instance invariant_basis_number_of_nontrivial_of_comm_ring {R : Type u} [comm_ring R] [nontrivial R] : invariant_basis_number R := ⟨λ n m e, let ⟨I, hI⟩ := ideal.exists_maximal R in by exactI eq_of_fin_equiv I.quotient ((ideal.pi_quot_equiv _ _).symm.trans ((induced_equiv _ e).trans (ideal.pi_quot_equiv _ _)))⟩ end
012b4b64ae22b48dfafdaf4391eba9cdf8cc36f4
9dc8cecdf3c4634764a18254e94d43da07142918
/src/order/category/omega_complete_partial_order.lean
6f1c756e8de05a211da6ea85b9345dab81df74e9
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
4,201
lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import order.omega_complete_partial_order import order.category.Preorder import category_theory.limits.shapes.products import category_theory.limits.shapes.equalizers import category_theory.limits.constructions.limits_of_products_and_equalizers /-! # Category of types with a omega complete partial order In this file, we bundle the class `omega_complete_partial_order` into a concrete category and prove that continuous functions also form a `omega_complete_partial_order`. ## Main definitions * `ωCPO` * an instance of `category` and `concrete_category` -/ open category_theory universes u v /-- The category of types with a omega complete partial order. -/ def ωCPO : Type (u+1) := bundled omega_complete_partial_order namespace ωCPO open omega_complete_partial_order instance : bundled_hom @continuous_hom := { to_fun := @continuous_hom.simps.apply, id := @continuous_hom.id, comp := @continuous_hom.comp, hom_ext := @continuous_hom.coe_inj } attribute [derive [large_category, concrete_category]] ωCPO instance : has_coe_to_sort ωCPO Type* := bundled.has_coe_to_sort /-- Construct a bundled ωCPO from the underlying type and typeclass. -/ def of (α : Type*) [omega_complete_partial_order α] : ωCPO := bundled.of α @[simp] lemma coe_of (α : Type*) [omega_complete_partial_order α] : ↥(of α) = α := rfl instance : inhabited ωCPO := ⟨of punit⟩ instance (α : ωCPO) : omega_complete_partial_order α := α.str section open category_theory.limits namespace has_products /-- The pi-type gives a cone for a product. -/ def product {J : Type v} (f : J → ωCPO.{v}) : fan f := fan.mk (of (Π j, f j)) (λ j, continuous_hom.of_mono (pi.eval_order_hom j) (λ c, rfl)) /-- The pi-type is a limit cone for the product. -/ def is_product (J : Type v) (f : J → ωCPO) : is_limit (product f) := { lift := λ s, ⟨⟨λ t j, s.π.app ⟨j⟩ t, λ x y h j, (s.π.app ⟨j⟩).monotone h⟩, λ x, funext (λ j, (s.π.app ⟨j⟩).continuous x)⟩, uniq' := λ s m w, begin ext t j, change m t j = s.π.app ⟨j⟩ t, rw ← w ⟨j⟩, refl, end, fac' := λ s j, by { cases j, tidy, } }. instance (J : Type v) (f : J → ωCPO.{v}) : has_product f := has_limit.mk ⟨_, is_product _ f⟩ end has_products instance omega_complete_partial_order_equalizer {α β : Type*} [omega_complete_partial_order α] [omega_complete_partial_order β] (f g : α →𝒄 β) : omega_complete_partial_order {a : α // f a = g a} := omega_complete_partial_order.subtype _ $ λ c hc, begin rw [f.continuous, g.continuous], congr' 1, ext, apply hc _ ⟨_, rfl⟩, end namespace has_equalizers /-- The equalizer inclusion function as a `continuous_hom`. -/ def equalizer_ι {α β : Type*} [omega_complete_partial_order α] [omega_complete_partial_order β] (f g : α →𝒄 β) : {a : α // f a = g a} →𝒄 α := continuous_hom.of_mono (order_hom.subtype.val _) (λ c, rfl) /-- A construction of the equalizer fork. -/ def equalizer {X Y : ωCPO.{v}} (f g : X ⟶ Y) : fork f g := @fork.of_ι _ _ _ _ _ _ (ωCPO.of {a // f a = g a}) (equalizer_ι f g) (continuous_hom.ext _ _ (λ x, x.2)) /-- The equalizer fork is a limit. -/ def is_equalizer {X Y : ωCPO.{v}} (f g : X ⟶ Y) : is_limit (equalizer f g) := fork.is_limit.mk' _ $ λ s, ⟨{ to_fun := λ x, ⟨s.ι x, by apply continuous_hom.congr_fun s.condition⟩, monotone' := λ x y h, s.ι.monotone h, cont := λ x, subtype.ext (s.ι.continuous x) }, by { ext, refl }, λ m hm, begin ext, apply continuous_hom.congr_fun hm, end⟩ end has_equalizers instance : has_products.{v} ωCPO.{v} := λ J, { has_limit := λ F, has_limit_of_iso discrete.nat_iso_functor.symm } instance {X Y : ωCPO.{v}} (f g : X ⟶ Y) : has_limit (parallel_pair f g) := has_limit.mk ⟨_, has_equalizers.is_equalizer f g⟩ instance : has_equalizers ωCPO.{v} := has_equalizers_of_has_limit_parallel_pair _ instance : has_limits ωCPO.{v} := has_limits_of_has_equalizers_and_products end end ωCPO
4502bb3c0a871cffa1685269833ca4c00ce9b571
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/Meta/Tactic/Unfold.lean
5b39d823ee1f466b06776c651d63527ed155b078
[ "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
1,982
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Eqns import Lean.Meta.Tactic.Delta import Lean.Meta.Tactic.Simp.Main namespace Lean.Meta private def getSimpUnfoldContext : MetaM Simp.Context := return { simpTheorems := {} congrTheorems := (← getSimpCongrTheorems) config := Simp.neutralConfig } def unfold (e : Expr) (declName : Name) : MetaM Simp.Result := do if let some unfoldThm ← getUnfoldEqnFor? declName then Simp.main e (← getSimpUnfoldContext) (methods := { pre := pre unfoldThm }) else return { expr := (← deltaExpand e (· == declName)) } where pre (unfoldThm : Name) (e : Expr) : SimpM Simp.Step := do match (← withReducible <| Simp.tryTheorem? e { proof := mkConst unfoldThm, name? := some unfoldThm, rfl := (← isRflTheorem unfoldThm) } (fun _ => return none)) with | none => pure () | some r => match (← reduceMatcher? r.expr) with | .reduced e' => return Simp.Step.done { r with expr := e' } | _ => return Simp.Step.done r return Simp.Step.visit { expr := e } def unfoldTarget (mvarId : MVarId) (declName : Name) : MetaM MVarId := mvarId.withContext do let target ← instantiateMVars (← mvarId.getType) let r ← unfold target declName if r.expr == target then throwError "tactic 'unfold' failed to unfold '{declName}' at{indentExpr target}" applySimpResultToTarget mvarId target r def unfoldLocalDecl (mvarId : MVarId) (fvarId : FVarId) (declName : Name) : MetaM MVarId := mvarId.withContext do let type ← fvarId.getType let r ← unfold (← instantiateMVars type) declName if r.expr == type then throwError "tactic 'unfold' failed to unfold '{declName}' at{indentExpr type}" let some (_, mvarId) ← applySimpResultToLocalDecl mvarId fvarId r (mayCloseGoal := false) | unreachable! return mvarId end Lean.Meta
e0a09c2f532a14da8d3b112073bea17fe13f7a47
a6f55abce20abcd06e718cb3e5fba7bf8a230fa1
/topic/color.lean
8c12f158d84ce6521128a89572ebfca384e8d564
[]
no_license
sonna0909/abc
b8a53e906d4d000d1f2347173a1cd4221757fabf
ff7b4c621cdf6d53937f2d1b6def28de2085a2aa
refs/heads/master
1,599,114,664,248
1,573,634,309,000
1,573,634,309,000
219,406,484
0
0
null
null
null
null
UTF-8
Lean
false
false
5,194
lean
[ { "key": "red", "title": "Red", "spelling": "/red/", "subs": [ { "key": "red1", "title": "My bag is red", "spelling": "" } ] }, { "key": "green", "title": "Green", "spelling": "/griːn/", "subs": [ { "key": "green1", "title": "The leaf is green", "spelling": "" } ] }, { "key": "blue", "title": "Blue", "spelling": "/blo͞o/", "subs": [ { "key": "blue1", "title": "Blue sky", "spelling": "" } ] }, { "key": "white", "title": "White", "spelling": "/waɪt/", "subs": [ { "key": "white1", "title": "My dress is white", "spelling": "" } ] }, { "key": "black", "title": "Black", "spelling": "/blæk/", "subs": [ { "key": "black1", "title": "My phone is black", "spelling": "" } ] }, { "key": "yellow", "title": "Yellow", "spelling": "/ˈjeləʊ/", "subs": [ { "key": "yellow1", "title": "The flower is yellow", "spelling": "" } ] }, { "key": "orange", "title": "Orange", "spelling": "/ˈɒrɪndʒ/", "subs": [ { "key": "orange1", "title": "The box is orange", "spelling": "" } ] }, { "key": "pink", "title": "Pink", "spelling": "/pɪŋk/", "subs": [ { "key": "pink1", "title": "My dress is pink", "spelling": "" } ] }, { "key": "brown", "title": "Brown", "spelling": "/braʊn/", "subs": [ { "key": "brown1", "title": "My hair is brown", "spelling": "" } ] }, { "key": "beige", "title": "Beige", "spelling": "/beɪʒ/", "subs": [ { "key": "beige1", "title": "My shoes is beige", "spelling": "" } ] }, { "key": "gray", "title": "Gray", "spelling": "/greɪ/", "subs": [ { "key": "gray1", "title": "His shoes is gray", "spelling": "" } ] }, { "key": "light_blue", "title": "Light blue", "spelling": "/laɪt bluː/", "subs": [ { "key": "light_blue1", "title": "My shirt is light blue", "spelling": "" } ] }, { "key": "dark_green", "title": "Dark green", "spelling": "/dɑːk griːn/", "subs": [ { "key": "dark_green1", "title": "His shirt is dark green", "spelling": "" } ] }, { "key": "purple", "title": "Purple", "spelling": "/ˈpɜːpļ/", "subs": [ { "key": "purple1", "title": "The pillow is purple", "spelling": "" } ] }, { "key": "magenta", "title": "Magenta", "spelling": "/məˈdʒentə/", "subs": [ { "key": "magenta1", "title": "The shirt is magenta", "spelling": "" } ] }, { "key": "violet", "title": "Violet", "spelling": "/ˈvaɪələt/", "subs": [ { "key": "violet1", "title": "Her dress is violet", "spelling": "" } ] }, { "key": "navy", "title": "Navy", "spelling": "/ˈneɪvi/", "subs": [ { "key": "navy1", "title": "His shirt is navy", "spelling": "" } ] }, { "key": "turquoise", "title": "Turquoise", "spelling": "/ˈtɜːkwɔɪz/", "subs": [ { "key": "turquoise1", "title": "This scarf is turquoise", "spelling": "" } ] }, { "key": "maroon", "title": "Maroon", "spelling": "/məˈruːn/", "subs": [ { "key": "maroon1", "title": "My father's shirt is maroon", "spelling": "" } ] }, { "key": "cream", "title": "Cream", "spelling": "/kriːm/", "subs": [ { "key": "cream1", "title": "My shoes is cream", "spelling": "" } ] }, { "key": "lemon", "title": "Lemon", "spelling": "/ˈlemən/", "subs": [ { "key": "lemon1", "title": "My son's shirt is lemon", "spelling": "" } ] }, { "key": "crimson", "title": "Crimson", "spelling": "/ˈkrɪmzən/", "subs": [ { "key": "crimson1", "title": "My dress is crimson", "spelling": "" } ] }, { "key": "vermilion", "title": "Vermilion", "spelling": "/vəˈmɪl.jən/", "subs": [ { "key": "vermilion1", "title": "My lipstick is magenta", "spelling": "" } ] }, { "key": "plum", "title": "Plum", "spelling": "/plʌm/", "subs": [ { "key": "plum1", "title": "My mother's shirt is plum", "spelling": "" } ] }, { "key": "peach", "title": "Peach", "spelling": "/plʌm/", "subs": [ { "key": "peach1", "title": "My lipstick is peach ", "spelling": "" } ] } ]
e7761fbc2296d2390b0be9d088fa47d2c010fadb
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/stage0/src/Lean/Meta/Match/MatcherInfo.lean
9a7f161a5b584f31e53e9cbaca26debac9c261c2
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
4,000
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.Meta.Basic namespace Lean.Meta namespace Match /-- A "matcher" auxiliary declaration has the following structure: - `numParams` parameters - motive - `numDiscrs` discriminators (aka major premises) - `altNumParams.size` alternatives (aka minor premises) where alternative `i` has `altNumParams[i]` parameters - `uElimPos?` is `some pos` when the matcher can eliminate in different universe levels, and `pos` is the position of the universe level parameter that specifies the elimination universe. It is `none` if the matcher only eliminates into `Prop`. -/ structure MatcherInfo where numParams : Nat numDiscrs : Nat altNumParams : Array Nat uElimPos? : Option Nat def MatcherInfo.numAlts (info : MatcherInfo) : Nat := info.altNumParams.size def MatcherInfo.arity (info : MatcherInfo) : Nat := info.numParams + 1 + info.numDiscrs + info.numAlts def MatcherInfo.getMotivePos (info : MatcherInfo) : Nat := info.numParams namespace Extension structure Entry where name : Name info : MatcherInfo structure State where map : SMap Name MatcherInfo := {} instance : Inhabited State := ⟨{}⟩ def State.addEntry (s : State) (e : Entry) : State := { s with map := s.map.insert e.name e.info } def State.switch (s : State) : State := { s with map := s.map.switch } builtin_initialize extension : SimplePersistentEnvExtension Entry State ← registerSimplePersistentEnvExtension { name := `matcher addEntryFn := State.addEntry addImportedFn := fun es => (mkStateFromImportedEntries State.addEntry {} es).switch } def addMatcherInfo (env : Environment) (matcherName : Name) (info : MatcherInfo) : Environment := extension.addEntry env { name := matcherName, info := info } def getMatcherInfo? (env : Environment) (declName : Name) : Option MatcherInfo := (extension.getState env).map.find? declName end Extension def addMatcherInfo (matcherName : Name) (info : MatcherInfo) : MetaM Unit := modifyEnv fun env => Extension.addMatcherInfo env matcherName info end Match export Match (MatcherInfo) def getMatcherInfo? (declName : Name) : MetaM (Option MatcherInfo) := return Match.Extension.getMatcherInfo? (← getEnv) declName def isMatcher (declName : Name) : MetaM Bool := return (← getMatcherInfo? declName).isSome structure MatcherApp where matcherName : Name matcherLevels : Array Level uElimPos? : Option Nat params : Array Expr motive : Expr discrs : Array Expr altNumParams : Array Nat alts : Array Expr remaining : Array Expr def matchMatcherApp? (e : Expr) : MetaM (Option MatcherApp) := match e.getAppFn with | Expr.const declName declLevels _ => do let some info ← getMatcherInfo? declName | pure none let args := e.getAppArgs if args.size < info.arity then return none else return some { matcherName := declName matcherLevels := declLevels.toArray uElimPos? := info.uElimPos? params := args.extract 0 info.numParams motive := args[info.getMotivePos] discrs := args[info.numParams + 1 : info.numParams + 1 + info.numDiscrs] altNumParams := info.altNumParams alts := args[info.numParams + 1 + info.numDiscrs : info.numParams + 1 + info.numDiscrs + info.numAlts] remaining := args[info.numParams + 1 + info.numDiscrs + info.numAlts : args.size] } | _ => return none def MatcherApp.toExpr (matcherApp : MatcherApp) : Expr := let result := mkAppN (mkConst matcherApp.matcherName matcherApp.matcherLevels.toList) matcherApp.params let result := mkApp result matcherApp.motive let result := mkAppN result matcherApp.discrs let result := mkAppN result matcherApp.alts mkAppN result matcherApp.remaining end Lean.Meta
fc2f1c539675037175fd7ac348c90ebcf2027a10
0003047346476c031128723dfd16fe273c6bc605
/src/data/equiv/algebra.lean
414fba909b0f83069fe590e9f289256b7aaad6a6
[ "Apache-2.0" ]
permissive
ChandanKSingh/mathlib
d2bf4724ccc670bf24915c12c475748281d3fb73
d60d1616958787ccb9842dc943534f90ea0bab64
refs/heads/master
1,588,238,823,679
1,552,867,469,000
1,552,867,469,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,109
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import data.equiv.basic algebra.field universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} namespace equiv section group variables [group α] protected def mul_left (a : α) : α ≃ α := { to_fun := λx, a * x, inv_fun := λx, a⁻¹ * x, left_inv := assume x, show a⁻¹ * (a * x) = x, from inv_mul_cancel_left a x, right_inv := assume x, show a * (a⁻¹ * x) = x, from mul_inv_cancel_left a x } attribute [to_additive equiv.add_left._proof_1] equiv.mul_left._proof_1 attribute [to_additive equiv.add_left._proof_2] equiv.mul_left._proof_2 attribute [to_additive equiv.add_left] equiv.mul_left protected def mul_right (a : α) : α ≃ α := { to_fun := λx, x * a, inv_fun := λx, x * a⁻¹, left_inv := assume x, show (x * a) * a⁻¹ = x, from mul_inv_cancel_right x a, right_inv := assume x, show (x * a⁻¹) * a = x, from inv_mul_cancel_right x a } attribute [to_additive equiv.add_right._proof_1] equiv.mul_right._proof_1 attribute [to_additive equiv.add_right._proof_2] equiv.mul_right._proof_2 attribute [to_additive equiv.add_right] equiv.mul_right protected def inv (α) [group α] : α ≃ α := { to_fun := λa, a⁻¹, inv_fun := λa, a⁻¹, left_inv := assume a, inv_inv a, right_inv := assume a, inv_inv a } attribute [to_additive equiv.neg._proof_1] equiv.inv._proof_1 attribute [to_additive equiv.neg._proof_2] equiv.inv._proof_2 attribute [to_additive equiv.neg] equiv.inv def units_equiv_ne_zero (α : Type*) [field α] : units α ≃ {a : α | a ≠ 0} := ⟨λ a, ⟨a.1, units.ne_zero _⟩, λ a, units.mk0 _ a.2, λ ⟨_, _, _, _⟩, units.ext rfl, λ ⟨_, _⟩, rfl⟩ @[simp] lemma coe_units_equiv_ne_zero [field α] (a : units α) : ((units_equiv_ne_zero α a) : α) = a := rfl end group section instances variables (e : α ≃ β) protected def has_zero [has_zero β] : has_zero α := ⟨e.symm 0⟩ lemma zero_def [has_zero β] : @has_zero.zero _ (equiv.has_zero e) = e.symm 0 := rfl protected def has_one [has_one β] : has_one α := ⟨e.symm 1⟩ lemma one_def [has_one β] : @has_one.one _ (equiv.has_one e) = e.symm 1 := rfl protected def has_mul [has_mul β] : has_mul α := ⟨λ x y, e.symm (e x * e y)⟩ lemma mul_def [has_mul β] (x y : α) : @has_mul.mul _ (equiv.has_mul e) x y = e.symm (e x * e y) := rfl protected def has_add [has_add β] : has_add α := ⟨λ x y, e.symm (e x + e y)⟩ lemma add_def [has_add β] (x y : α) : @has_add.add _ (equiv.has_add e) x y = e.symm (e x + e y) := rfl protected def has_inv [has_inv β] : has_inv α := ⟨λ x, e.symm (e x)⁻¹⟩ lemma inv_def [has_inv β] (x : α) : @has_inv.inv _ (equiv.has_inv e) x = e.symm (e x)⁻¹ := rfl protected def has_neg [has_neg β] : has_neg α := ⟨λ x, e.symm (-e x)⟩ lemma neg_def [has_neg β] (x : α) : @has_neg.neg _ (equiv.has_neg e) x = e.symm (-e x) := rfl protected def semigroup [semigroup β] : semigroup α := { mul_assoc := by simp [mul_def, mul_assoc], ..equiv.has_mul e } protected def comm_semigroup [comm_semigroup β] : comm_semigroup α := { mul_comm := by simp [mul_def, mul_comm], ..equiv.semigroup e } protected def monoid [monoid β] : monoid α := { one_mul := by simp [mul_def, one_def], mul_one := by simp [mul_def, one_def], ..equiv.semigroup e, ..equiv.has_one e } protected def comm_monoid [comm_monoid β] : comm_monoid α := { ..equiv.comm_semigroup e, ..equiv.monoid e } protected def group [group β] : group α := { mul_left_inv := by simp [mul_def, inv_def, one_def], ..equiv.monoid e, ..equiv.has_inv e } protected def comm_group [comm_group β] : comm_group α := { ..equiv.group e, ..equiv.comm_semigroup e } protected def add_semigroup [add_semigroup β] : add_semigroup α := @additive.add_semigroup _ (@equiv.semigroup _ _ e multiplicative.semigroup) protected def add_comm_semigroup [add_comm_semigroup β] : add_comm_semigroup α := @additive.add_comm_semigroup _ (@equiv.comm_semigroup _ _ e multiplicative.comm_semigroup) protected def add_monoid [add_monoid β] : add_monoid α := @additive.add_monoid _ (@equiv.monoid _ _ e multiplicative.monoid) protected def add_comm_monoid [add_comm_monoid β] : add_comm_monoid α := @additive.add_comm_monoid _ (@equiv.comm_monoid _ _ e multiplicative.comm_monoid) protected def add_group [add_group β] : add_group α := @additive.add_group _ (@equiv.group _ _ e multiplicative.group) protected def add_comm_group [add_comm_group β] : add_comm_group α := @additive.add_comm_group _ (@equiv.comm_group _ _ e multiplicative.comm_group) protected def semiring [semiring β] : semiring α := { right_distrib := by simp [mul_def, add_def, add_mul], left_distrib := by simp [mul_def, add_def, mul_add], zero_mul := by simp [mul_def, zero_def], mul_zero := by simp [mul_def, zero_def], ..equiv.has_zero e, ..equiv.has_mul e, ..equiv.has_add e, ..equiv.monoid e, ..equiv.add_comm_monoid e } protected def comm_semiring [comm_semiring β] : comm_semiring α := { ..equiv.semiring e, ..equiv.comm_monoid e } protected def ring [ring β] : ring α := { ..equiv.semiring e, ..equiv.add_comm_group e } protected def comm_ring [comm_ring β] : comm_ring α := { ..equiv.comm_monoid e, ..equiv.ring e } protected def zero_ne_one_class [zero_ne_one_class β] : zero_ne_one_class α := { zero_ne_one := by simp [zero_def, one_def], ..equiv.has_zero e, ..equiv.has_one e } protected def nonzero_comm_ring [nonzero_comm_ring β] : nonzero_comm_ring α := { ..equiv.zero_ne_one_class e, ..equiv.comm_ring e } protected def domain [domain β] : domain α := { eq_zero_or_eq_zero_of_mul_eq_zero := by simp [mul_def, zero_def, equiv.eq_symm_apply], ..equiv.has_zero e, ..equiv.zero_ne_one_class e, ..equiv.has_mul e, ..equiv.ring e } protected def integral_domain [integral_domain β] : integral_domain α := { ..equiv.domain e, ..equiv.nonzero_comm_ring e } protected def division_ring [division_ring β] : division_ring α := { inv_mul_cancel := λ _, by simp [mul_def, inv_def, zero_def, one_def, (equiv.symm_apply_eq _).symm]; exact inv_mul_cancel, mul_inv_cancel := λ _, by simp [mul_def, inv_def, zero_def, one_def, (equiv.symm_apply_eq _).symm]; exact mul_inv_cancel, ..equiv.has_zero e, ..equiv.has_one e, ..equiv.domain e, ..equiv.has_inv e } protected def field [field β] : field α := { ..equiv.integral_domain e, ..equiv.division_ring e } protected def discrete_field [discrete_field β] : discrete_field α := { has_decidable_eq := equiv.decidable_eq e, inv_zero := by simp [mul_def, inv_def, zero_def], ..equiv.has_mul e, ..equiv.has_inv e, ..equiv.has_zero e, ..equiv.field e } end instances end equiv structure ring_equiv (α β : Type*) [ring α] [ring β] extends α ≃ β := (hom : is_ring_hom to_fun) infix ` ≃r `:50 := ring_equiv namespace ring_equiv variables [ring α] [ring β] [ring γ] instance {e : α ≃r β} : is_ring_hom e.to_equiv := hom _ protected def refl (α : Type*) [ring α] : α ≃r α := { hom := is_ring_hom.id, .. equiv.refl α } protected def symm {α β : Type*} [ring α] [ring β] (e : α ≃r β) : β ≃r α := { hom := ⟨(equiv.symm_apply_eq _).2 e.hom.1.symm, λ x y, (equiv.symm_apply_eq _).2 $ show _ = e.to_equiv.to_fun _, by rw [e.2.2, e.1.4, e.1.4], λ x y, (equiv.symm_apply_eq _).2 $ show _ = e.to_equiv.to_fun _, by rw [e.2.3, e.1.4, e.1.4]⟩, .. e.to_equiv.symm } protected def trans {α β γ : Type*} [ring α] [ring β] [ring γ] (e₁ : α ≃r β) (e₂ : β ≃r γ) : α ≃r γ := { hom := is_ring_hom.comp _ _, .. e₁.1.trans e₂.1 } instance symm.is_ring_hom {e : α ≃r β} : is_ring_hom e.to_equiv.symm := hom e.symm @[simp] lemma to_equiv_symm (e : α ≃r β) : e.symm.to_equiv = e.to_equiv.symm := rfl @[simp] lemma to_equiv_symm_apply (e : α ≃r β) (x : β) : e.symm.to_equiv x = e.to_equiv.symm x := rfl end ring_equiv
d6bc4e485bbd36fb2e34fda6c59aa91f420356e0
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/playground/task_test4.lean
1c95e5a60c8ea5217a4b8e9fa4c938cabf800120
[ "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
454
lean
def run1 (i : Nat) (n : Nat) (xs : List Nat) : Nat := n.repeat (fun r => let s := (">> [" ++ toString i ++ "] " ++ toString r); xs.foldl (fun a b => a + b) (r + s.length)) 0 def main (xs : List String) : IO UInt32 := let ys := (List.replicate xs.head.toNat 1); let ts : List (Task Nat) := (List.iota 10).map (fun i => Task.mk $ fun _ => run1 (i+1) xs.head.toNat ys); let ns : List Nat := ts.map Task.get; IO.println (">> " ++ toString ns) *> pure 0
973a004b80ad0d61265f17fd39183d4b5dea8f96
a46270e2f76a375564f3b3e9c1bf7b635edc1f2c
/5.8.1-4.6.2.lean
4ee30126e1a383e6e8ddd58dbb4d8971bbe81049
[ "CC0-1.0" ]
permissive
wudcscheme/lean-exercise
88ea2506714eac343de2a294d1132ee8ee6d3a20
5b23b9be3d361fff5e981d5be3a0a1175504b9f6
refs/heads/master
1,678,958,930,293
1,583,197,205,000
1,583,197,205,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
812
lean
variables (α : Type) (p q : α → Prop) variable r : Prop example : α → ((∀ x : α, r) ↔ r) := begin intro, apply iff.intro, { intro f, exact f a }, { intros, assumption } end example : (∀ x, p x ∨ r) ↔ (∀ x, p x) ∨ r := begin apply iff.intro, { intro h, apply classical.by_cases, { assume hr: r, right, assumption }, { assume hnr: ¬ r, left, intro, apply or.elim (h x), { intro, assumption, }, { intro, contradiction, } } }, { intro h, intro, apply or.elim h, { intro h1, left, exact h1 x }, { intro, right, assumption } } end example : (∀ x, r → p x) ↔ (r → ∀ x, p x) := begin apply iff.intro, { intros h hr x, exact h x hr }, { intros h x hr, exact h hr x } end
d320e57404e269bdd366323d84166054cb8cd13f
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/type0.lean
08e67cde696b761a7b103ed4a731980dd8021443
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
141
lean
check (Type → Type) check (Type → Type) → Type check (Type 1) check ((Type 1) → Type) → Type check ((Type 1) → (Type 2)) → Type
3445445ab6de8a155b39d44113bcd93489b56298
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/omega/int/dnf_auto.lean
087b466f8a915c589a6189ce4a415d736363ddfd
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
2,026
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Seul Baek -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.omega.clause import Mathlib.tactic.omega.int.form import Mathlib.PostPort namespace Mathlib /- DNF transformation. -/ namespace omega namespace int /-- 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 := sorry theorem push_neg_equiv {p : preform} : preform.equiv (push_neg p) (preform.not p) := sorry /-- NNF transformation -/ def nnf : preform → preform := sorry def is_nnf : preform → Prop := sorry theorem is_nnf_push_neg (p : preform) : is_nnf p → is_nnf (push_neg p) := sorry /-- Argument is free of negations -/ def neg_free : preform → Prop := sorry theorem is_nnf_nnf (p : preform) : is_nnf (nnf p) := sorry theorem nnf_equiv {p : preform} : preform.equiv (nnf p) p := sorry /-- Eliminate all negations from preform -/ @[simp] def neg_elim : preform → preform := sorry theorem neg_free_neg_elim (p : preform) : is_nnf p → neg_free (neg_elim p) := sorry theorem le_and_le_iff_eq {α : Type} [partial_order α] {a : α} {b : α} : a ≤ b ∧ b ≤ a ↔ a = b := sorry theorem implies_neg_elim {p : preform} : preform.implies p (neg_elim p) := sorry @[simp] def dnf_core : preform → List clause := sorry /-- DNF transformation -/ def dnf (p : preform) : List clause := dnf_core (neg_elim (nnf p)) theorem exists_clause_holds {v : ℕ → ℤ} {p : preform} : neg_free p → preform.holds v p → ∃ (c : clause), ∃ (H : c ∈ dnf_core p), clause.holds v c := sorry theorem clauses_sat_dnf_core {p : preform} : neg_free p → preform.sat p → clauses.sat (dnf_core p) := sorry theorem unsat_of_clauses_unsat {p : preform} : clauses.unsat (dnf p) → preform.unsat p := sorry end Mathlib
b29bfefa7b7269ab09345a859116415ed618dd19
46125763b4dbf50619e8846a1371029346f4c3db
/scripts/mk_nolint.lean
b7d103d2394d676ba68c1ec327b87224cfcfe1ea
[ "Apache-2.0" ]
permissive
thjread/mathlib
a9d97612cedc2c3101060737233df15abcdb9eb1
7cffe2520a5518bba19227a107078d83fa725ddc
refs/heads/master
1,615,637,696,376
1,583,953,063,000
1,583,953,063,000
246,680,271
0
0
Apache-2.0
1,583,960,875,000
1,583,960,875,000
null
UTF-8
Lean
false
false
1,680
lean
/- Copyright (c) 2019 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Robert Y. Lewis -/ import tactic.lint system.io -- these are required import all -- then import everything, to parse the library for failing linters /-! # mk_nolint Defines a function that writes a file containing the names of all declarations that fail the linting tests in `mathlib_linters`. This is mainly used in the Travis check for mathlib. It assumes that files generated by `mk_all.sh` are present. Usage: `lean --run mk_nolint.lean` writes a file `nolints.txt` in the current directory. -/ open io io.fs open native /-- Runs when called with `lean --run` -/ meta def main : io unit := do decls ← run_tactic lint_mathlib_decls, linters ← run_tactic $ get_linters mathlib_linters, results ← run_tactic $ lint_core decls linters, env ← run_tactic tactic.get_env, mathlib_path_len ← string.length <$> run_tactic tactic.get_mathlib_dir, let failed_decls_by_file := rb_lmap.of_list (do (linter_name, _, decls) ← results, (decl_name, _) ← decls.to_list, let file_name := (env.decl_olean decl_name).get_or_else "", pure (file_name.popn mathlib_path_len, decl_name.to_string, linter_name.last)), handle ← mk_file_handle "nolints.txt" mode.write, put_str_ln handle "import .all", put_str_ln handle "run_cmd tactic.skip", failed_decls_by_file.to_list.reverse.mmap' (λ ⟨file_name, decls⟩, do put_str_ln handle $ "\n-- " ++ file_name, (rb_lmap.of_list decls).to_list.reverse.mmap $ λ ⟨decl, linters⟩, put_str_ln handle $ "apply_nolint " ++ decl ++ " " ++ " ".intercalate linters), close handle
b06667f9453f750681d5e683765e2029304fa857
bb31430994044506fa42fd667e2d556327e18dfe
/src/topology/support.lean
4beaa91af3bba9d450dd2cd3dab81aa657ae1b0b
[ "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,034
lean
/- Copyright (c) 2022 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Patrick Massot -/ import topology.separation /-! # The topological support of a function In this file we define the topological support of a function `f`, `tsupport f`, as the closure of the support of `f`. Furthermore, we say that `f` has compact support if the topological support of `f` is compact. ## Main definitions * `function.mul_tsupport` & `function.tsupport` * `function.has_compact_mul_support` & `function.has_compact_support` ## Implementation Notes * We write all lemmas for multiplicative functions, and use `@[to_additive]` to get the more common additive versions. * We do not put the definitions in the `function` namespace, following many other topological definitions that are in the root namespace (compare `embedding` vs `function.embedding`). -/ open function set filter open_locale topological_space variables {X α α' β γ δ M E R : Type*} section one variables [has_one α] variables [topological_space X] /-- The topological support of a function is the closure of its support, i.e. the closure of the set of all elements where the function is not equal to 1. -/ @[to_additive /-" The topological support of a function is the closure of its support. i.e. the closure of the set of all elements where the function is nonzero. "-/] def mul_tsupport (f : X → α) : set X := closure (mul_support f) @[to_additive] lemma subset_mul_tsupport (f : X → α) : mul_support f ⊆ mul_tsupport f := subset_closure @[to_additive] lemma is_closed_mul_tsupport (f : X → α) : is_closed (mul_tsupport f) := is_closed_closure @[to_additive] lemma mul_tsupport_eq_empty_iff {f : X → α} : mul_tsupport f = ∅ ↔ f = 1 := by rw [mul_tsupport, closure_empty_iff, mul_support_eq_empty_iff] @[to_additive] lemma image_eq_one_of_nmem_mul_tsupport {f : X → α} {x : X} (hx : x ∉ mul_tsupport f) : f x = 1 := mul_support_subset_iff'.mp (subset_mul_tsupport f) x hx @[to_additive] lemma range_subset_insert_image_mul_tsupport (f : X → α) : range f ⊆ insert 1 (f '' mul_tsupport f) := (range_subset_insert_image_mul_support f).trans $ insert_subset_insert $ image_subset _ subset_closure @[to_additive] lemma range_eq_image_mul_tsupport_or (f : X → α) : range f = f '' mul_tsupport f ∨ range f = insert 1 (f '' mul_tsupport f) := (wcovby_insert _ _).eq_or_eq (image_subset_range _ _) (range_subset_insert_image_mul_tsupport f) lemma tsupport_mul_subset_left {α : Type*} [mul_zero_class α] {f g : X → α} : tsupport (λ x, f x * g x) ⊆ tsupport f := closure_mono (support_mul_subset_left _ _) lemma tsupport_mul_subset_right {α : Type*} [mul_zero_class α] {f g : X → α} : tsupport (λ x, f x * g x) ⊆ tsupport g := closure_mono (support_mul_subset_right _ _) end one lemma tsupport_smul_subset_left {M α} [topological_space X] [has_zero M] [has_zero α] [smul_with_zero M α] (f : X → M) (g : X → α) : tsupport (λ x, f x • g x) ⊆ tsupport f := closure_mono $ support_smul_subset_left f g section variables [topological_space α] [topological_space α'] variables [has_one β] [has_one γ] [has_one δ] variables {g : β → γ} {f : α → β} {f₂ : α → γ} {m : β → γ → δ} {x : α} @[to_additive] lemma not_mem_mul_tsupport_iff_eventually_eq : x ∉ mul_tsupport f ↔ f =ᶠ[𝓝 x] 1 := by simp_rw [mul_tsupport, mem_closure_iff_nhds, not_forall, not_nonempty_iff_eq_empty, ← disjoint_iff_inter_eq_empty, disjoint_mul_support_iff, eventually_eq_iff_exists_mem] @[to_additive] lemma continuous_of_mul_tsupport [topological_space β] {f : α → β} (hf : ∀ x ∈ mul_tsupport f, continuous_at f x) : continuous f := continuous_iff_continuous_at.2 $ λ x, (em _).elim (hf x) $ λ hx, (@continuous_at_const _ _ _ _ _ 1).congr (not_mem_mul_tsupport_iff_eventually_eq.mp hx).symm /-- A function `f` *has compact multiplicative support* or is *compactly supported* if the closure of the multiplicative support of `f` is compact. In a T₂ space this is equivalent to `f` being equal to `1` outside a compact set. -/ @[to_additive /-" A function `f` *has compact support* or is *compactly supported* if the closure of the support of `f` is compact. In a T₂ space this is equivalent to `f` being equal to `0` outside a compact set. "-/] def has_compact_mul_support (f : α → β) : Prop := is_compact (mul_tsupport f) @[to_additive] lemma has_compact_mul_support_def : has_compact_mul_support f ↔ is_compact (closure (mul_support f)) := by refl @[to_additive] lemma exists_compact_iff_has_compact_mul_support [t2_space α] : (∃ K : set α, is_compact K ∧ ∀ x ∉ K, f x = 1) ↔ has_compact_mul_support f := by simp_rw [← nmem_mul_support, ← mem_compl_iff, ← subset_def, compl_subset_compl, has_compact_mul_support_def, exists_compact_superset_iff] @[to_additive] lemma has_compact_mul_support.intro [t2_space α] {K : set α} (hK : is_compact K) (hfK : ∀ x ∉ K, f x = 1) : has_compact_mul_support f := exists_compact_iff_has_compact_mul_support.mp ⟨K, hK, hfK⟩ @[to_additive] lemma has_compact_mul_support.is_compact (hf : has_compact_mul_support f) : is_compact (mul_tsupport f) := hf @[to_additive] lemma has_compact_mul_support_iff_eventually_eq : has_compact_mul_support f ↔ f =ᶠ[coclosed_compact α] 1 := ⟨ λ h, mem_coclosed_compact.mpr ⟨mul_tsupport f, is_closed_mul_tsupport _, h, λ x, not_imp_comm.mpr $ λ hx, subset_mul_tsupport f hx⟩, λ h, let ⟨C, hC⟩ := mem_coclosed_compact'.mp h in is_compact_of_is_closed_subset hC.2.1 (is_closed_mul_tsupport _) (closure_minimal hC.2.2 hC.1)⟩ @[to_additive] lemma has_compact_mul_support.is_compact_range [topological_space β] (h : has_compact_mul_support f) (hf : continuous f) : is_compact (range f) := begin cases range_eq_image_mul_tsupport_or f with h2 h2; rw [h2], exacts [h.image hf, (h.image hf).insert 1] end @[to_additive] lemma has_compact_mul_support.mono' {f' : α → γ} (hf : has_compact_mul_support f) (hff' : mul_support f' ⊆ mul_tsupport f) : has_compact_mul_support f' := is_compact_of_is_closed_subset hf is_closed_closure $ closure_minimal hff' is_closed_closure @[to_additive] lemma has_compact_mul_support.mono {f' : α → γ} (hf : has_compact_mul_support f) (hff' : mul_support f' ⊆ mul_support f) : has_compact_mul_support f' := hf.mono' $ hff'.trans subset_closure @[to_additive] lemma has_compact_mul_support.comp_left (hf : has_compact_mul_support f) (hg : g 1 = 1) : has_compact_mul_support (g ∘ f) := hf.mono $ mul_support_comp_subset hg f @[to_additive] lemma has_compact_mul_support_comp_left (hg : ∀ {x}, g x = 1 ↔ x = 1) : has_compact_mul_support (g ∘ f) ↔ has_compact_mul_support f := by simp_rw [has_compact_mul_support_def, mul_support_comp_eq g @hg f] @[to_additive] lemma has_compact_mul_support.comp_closed_embedding (hf : has_compact_mul_support f) {g : α' → α} (hg : closed_embedding g) : has_compact_mul_support (f ∘ g) := begin rw [has_compact_mul_support_def, function.mul_support_comp_eq_preimage], refine is_compact_of_is_closed_subset (hg.is_compact_preimage hf) is_closed_closure _, rw [hg.to_embedding.closure_eq_preimage_closure_image], exact preimage_mono (closure_mono $ image_preimage_subset _ _) end @[to_additive] lemma has_compact_mul_support.comp₂_left (hf : has_compact_mul_support f) (hf₂ : has_compact_mul_support f₂) (hm : m 1 1 = 1) : has_compact_mul_support (λ x, m (f x) (f₂ x)) := begin rw [has_compact_mul_support_iff_eventually_eq] at hf hf₂ ⊢, filter_upwards [hf, hf₂] using λ x hx hx₂, by simp_rw [hx, hx₂, pi.one_apply, hm] end end section monoid variables [topological_space α] [monoid β] variables {f f' : α → β} {x : α} @[to_additive] lemma has_compact_mul_support.mul (hf : has_compact_mul_support f) (hf' : has_compact_mul_support f') : has_compact_mul_support (f * f') := by apply hf.comp₂_left hf' (mul_one 1) -- `by apply` speeds up elaboration end monoid section distrib_mul_action variables [topological_space α] [monoid_with_zero R] [add_monoid M] [distrib_mul_action R M] variables {f : α → R} {f' : α → M} {x : α} lemma has_compact_support.smul_left (hf : has_compact_support f') : has_compact_support (f • f') := begin rw [has_compact_support_iff_eventually_eq] at hf ⊢, refine hf.mono (λ x hx, by simp_rw [pi.smul_apply', hx, pi.zero_apply, smul_zero]) end end distrib_mul_action section smul_with_zero variables [topological_space α] [has_zero R] [has_zero M] [smul_with_zero R M] variables {f : α → R} {f' : α → M} {x : α} lemma has_compact_support.smul_right (hf : has_compact_support f) : has_compact_support (f • f') := begin rw [has_compact_support_iff_eventually_eq] at hf ⊢, refine hf.mono (λ x hx, by simp_rw [pi.smul_apply', hx, pi.zero_apply, zero_smul]) end lemma has_compact_support.smul_left' (hf : has_compact_support f') : has_compact_support (f • f') := begin rw [has_compact_support_iff_eventually_eq] at hf ⊢, refine hf.mono (λ x hx, by simp_rw [pi.smul_apply', hx, pi.zero_apply, smul_zero]) end end smul_with_zero section mul_zero_class variables [topological_space α] [mul_zero_class β] variables {f f' : α → β} {x : α} lemma has_compact_support.mul_right (hf : has_compact_support f) : has_compact_support (f * f') := begin rw [has_compact_support_iff_eventually_eq] at hf ⊢, refine hf.mono (λ x hx, by simp_rw [pi.mul_apply, hx, pi.zero_apply, zero_mul]) end lemma has_compact_support.mul_left (hf : has_compact_support f') : has_compact_support (f * f') := begin rw [has_compact_support_iff_eventually_eq] at hf ⊢, refine hf.mono (λ x hx, by simp_rw [pi.mul_apply, hx, pi.zero_apply, mul_zero]) end end mul_zero_class namespace locally_finite variables {ι : Type*} {U : ι → set X} [topological_space X] [has_one R] /-- If a family of functions `f` has locally-finite multiplicative support, subordinate to a family of open sets, then for any point we can find a neighbourhood on which only finitely-many members of `f` are not equal to 1. -/ @[to_additive /-" If a family of functions `f` has locally-finite support, subordinate to a family of open sets, then for any point we can find a neighbourhood on which only finitely-many members of `f` are non-zero. "-/] lemma exists_finset_nhd_mul_support_subset {f : ι → X → R} (hlf : locally_finite (λ i, mul_support (f i))) (hso : ∀ i, mul_tsupport (f i) ⊆ U i) (ho : ∀ i, is_open (U i)) (x : X) : ∃ (is : finset ι) {n : set X} (hn₁ : n ∈ 𝓝 x) (hn₂ : n ⊆ ⋂ i ∈ is, U i), ∀ (z ∈ n), mul_support (λ i, f i z) ⊆ is := begin obtain ⟨n, hn, hnf⟩ := hlf x, classical, let is := hnf.to_finset.filter (λ i, x ∈ U i), let js := hnf.to_finset.filter (λ j, x ∉ U j), refine ⟨is, n ∩ (⋂ j ∈ js, (mul_tsupport (f j))ᶜ) ∩ (⋂ i ∈ is, U i), inter_mem (inter_mem hn _) _, inter_subset_right _ _, λ z hz, _⟩, { exact (bInter_finset_mem js).mpr (λ j hj, is_closed.compl_mem_nhds (is_closed_mul_tsupport _) (set.not_mem_subset (hso j) (finset.mem_filter.mp hj).2)), }, { exact (bInter_finset_mem is).mpr (λ i hi, (ho i).mem_nhds (finset.mem_filter.mp hi).2) }, { have hzn : z ∈ n, { rw inter_assoc at hz, exact mem_of_mem_inter_left hz, }, replace hz := mem_of_mem_inter_right (mem_of_mem_inter_left hz), simp only [finset.mem_filter, finite.mem_to_finset, mem_set_of_eq, mem_Inter, and_imp] at hz, suffices : mul_support (λ i, f i z) ⊆ hnf.to_finset, { refine hnf.to_finset.subset_coe_filter_of_subset_forall _ this (λ i hi, _), specialize hz i ⟨z, ⟨hi, hzn⟩⟩, contrapose hz, simp [hz, subset_mul_tsupport (f i) hi], }, intros i hi, simp only [finite.coe_to_finset, mem_set_of_eq], exact ⟨z, ⟨hi, hzn⟩⟩, }, end end locally_finite
71fb61339b53caa1fdc26e6c991f92f3db737d6b
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/data/list/rotate.lean
2b66eb45cc505d5966701712857dd4893387cc0a
[ "Apache-2.0" ]
permissive
jumpy4/mathlib
d3829e75173012833e9f15ac16e481e17596de0f
af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13
refs/heads/master
1,693,508,842,818
1,636,203,271,000
1,636,203,271,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
21,689
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Yakov Pechersky -/ import data.list.perm import data.list.range /-! # List rotation This file proves basic results about `list.rotate`, the list rotation. ## Main declarations * `is_rotated l₁ l₂`: States that `l₁` is a rotated version of `l₂`. * `cyclic_permutations l`: The list of all cyclic permutants of `l`, up to the length of `l`. ## Tags rotated, rotation, permutation, cycle -/ universe u variables {α : Type u} open nat namespace list lemma rotate_mod (l : list α) (n : ℕ) : l.rotate (n % l.length) = l.rotate n := by simp [rotate] @[simp] lemma rotate_nil (n : ℕ) : ([] : list α).rotate n = [] := by cases n; simp [rotate] @[simp] lemma rotate_zero (l : list α) : l.rotate 0 = l := by simp [rotate] @[simp] lemma rotate'_nil (n : ℕ) : ([] : list α).rotate' n = [] := by cases n; refl @[simp] lemma rotate'_zero (l : list α) : l.rotate' 0 = l := by cases l; refl lemma rotate'_cons_succ (l : list α) (a : α) (n : ℕ) : (a :: l : list α).rotate' n.succ = (l ++ [a]).rotate' n := by simp [rotate'] @[simp] lemma length_rotate' : ∀ (l : list α) (n : ℕ), (l.rotate' n).length = l.length | [] n := rfl | (a::l) 0 := rfl | (a::l) (n+1) := by rw [list.rotate', length_rotate' (l ++ [a]) n]; simp lemma rotate'_eq_drop_append_take : ∀ {l : list α} {n : ℕ}, n ≤ l.length → l.rotate' n = l.drop n ++ l.take n | [] n h := by simp [drop_append_of_le_length h] | l 0 h := by simp [take_append_of_le_length h] | (a::l) (n+1) h := have hnl : n ≤ l.length, from le_of_succ_le_succ h, have hnl' : n ≤ (l ++ [a]).length, by rw [length_append, length_cons, list.length, zero_add]; exact (le_of_succ_le h), by rw [rotate'_cons_succ, rotate'_eq_drop_append_take hnl', drop, take, drop_append_of_le_length hnl, take_append_of_le_length hnl]; simp lemma rotate'_rotate' : ∀ (l : list α) (n m : ℕ), (l.rotate' n).rotate' m = l.rotate' (n + m) | (a::l) 0 m := by simp | [] n m := by simp | (a::l) (n+1) m := by rw [rotate'_cons_succ, rotate'_rotate', add_right_comm, rotate'_cons_succ] @[simp] lemma rotate'_length (l : list α) : rotate' l l.length = l := by rw rotate'_eq_drop_append_take (le_refl _); simp @[simp] lemma rotate'_length_mul (l : list α) : ∀ n : ℕ, l.rotate' (l.length * n) = l | 0 := by simp | (n+1) := calc l.rotate' (l.length * (n + 1)) = (l.rotate' (l.length * n)).rotate' (l.rotate' (l.length * n)).length : by simp [-rotate'_length, nat.mul_succ, rotate'_rotate'] ... = l : by rw [rotate'_length, rotate'_length_mul] lemma rotate'_mod (l : list α) (n : ℕ) : l.rotate' (n % l.length) = l.rotate' n := calc l.rotate' (n % l.length) = (l.rotate' (n % l.length)).rotate' ((l.rotate' (n % l.length)).length * (n / l.length)) : by rw rotate'_length_mul ... = l.rotate' n : by rw [rotate'_rotate', length_rotate', nat.mod_add_div] lemma rotate_eq_rotate' (l : list α) (n : ℕ) : l.rotate n = l.rotate' n := if h : l.length = 0 then by simp [length_eq_zero, *] at * else by rw [← rotate'_mod, rotate'_eq_drop_append_take (le_of_lt (nat.mod_lt _ (nat.pos_of_ne_zero h)))]; simp [rotate] lemma rotate_cons_succ (l : list α) (a : α) (n : ℕ) : (a :: l : list α).rotate n.succ = (l ++ [a]).rotate n := by rw [rotate_eq_rotate', rotate_eq_rotate', rotate'_cons_succ] @[simp] lemma mem_rotate : ∀ {l : list α} {a : α} {n : ℕ}, a ∈ l.rotate n ↔ a ∈ l | [] _ n := by simp | (a::l) _ 0 := by simp | (a::l) _ (n+1) := by simp [rotate_cons_succ, mem_rotate, or.comm] @[simp] lemma length_rotate (l : list α) (n : ℕ) : (l.rotate n).length = l.length := by rw [rotate_eq_rotate', length_rotate'] lemma rotate_eq_drop_append_take {l : list α} {n : ℕ} : n ≤ l.length → l.rotate n = l.drop n ++ l.take n := by rw rotate_eq_rotate'; exact rotate'_eq_drop_append_take lemma rotate_eq_drop_append_take_mod {l : list α} {n : ℕ} : l.rotate n = l.drop (n % l.length) ++ l.take (n % l.length) := begin cases l.length.zero_le.eq_or_lt with hl hl, { simp [eq_nil_of_length_eq_zero hl.symm ] }, rw [←rotate_eq_drop_append_take (n.mod_lt hl).le, rotate_mod] end @[simp] lemma rotate_append_length_eq (l l' : list α) : (l ++ l').rotate l.length = l' ++ l := begin rw rotate_eq_rotate', induction l generalizing l', { simp, }, { simp [rotate', l_ih] }, end lemma rotate_rotate (l : list α) (n m : ℕ) : (l.rotate n).rotate m = l.rotate (n + m) := by rw [rotate_eq_rotate', rotate_eq_rotate', rotate_eq_rotate', rotate'_rotate'] @[simp] lemma rotate_length (l : list α) : rotate l l.length = l := by rw [rotate_eq_rotate', rotate'_length] @[simp] lemma rotate_length_mul (l : list α) (n : ℕ) : l.rotate (l.length * n) = l := by rw [rotate_eq_rotate', rotate'_length_mul] lemma prod_rotate_eq_one_of_prod_eq_one [group α] : ∀ {l : list α} (hl : l.prod = 1) (n : ℕ), (l.rotate n).prod = 1 | [] _ _ := by simp | (a::l) hl n := have n % list.length (a :: l) ≤ list.length (a :: l), from le_of_lt (nat.mod_lt _ dec_trivial), by rw ← list.take_append_drop (n % list.length (a :: l)) (a :: l) at hl; rw [← rotate_mod, rotate_eq_drop_append_take this, list.prod_append, mul_eq_one_iff_inv_eq, ← one_mul (list.prod _)⁻¹, ← hl, list.prod_append, mul_assoc, mul_inv_self, mul_one] lemma rotate_perm (l : list α) (n : ℕ) : l.rotate n ~ l := begin rw rotate_eq_rotate', induction n with n hn generalizing l, { simp }, { cases l with hd tl, { simp }, { rw rotate'_cons_succ, exact (hn _).trans (perm_append_singleton _ _) } } end @[simp] lemma nodup_rotate {l : list α} {n : ℕ} : nodup (l.rotate n) ↔ nodup l := (rotate_perm l n).nodup_iff @[simp] lemma rotate_eq_nil_iff {l : list α} {n : ℕ} : l.rotate n = [] ↔ l = [] := begin induction n with n hn generalizing l, { simp }, { cases l with hd tl, { simp }, { simp [rotate_cons_succ, hn] } } end @[simp] lemma nil_eq_rotate_iff {l : list α} {n : ℕ} : [] = l.rotate n ↔ [] = l := by rw [eq_comm, rotate_eq_nil_iff, eq_comm] @[simp] lemma rotate_singleton (x : α) (n : ℕ) : [x].rotate n = [x] := begin induction n with n hn, { simp }, { rwa [rotate_cons_succ] } end @[simp] lemma rotate_eq_singleton_iff {l : list α} {n : ℕ} {x : α} : l.rotate n = [x] ↔ l = [x] := begin induction n with n hn generalizing l, { simp }, { cases l with hd tl, { simp }, { simp [rotate_cons_succ, hn, append_eq_cons_iff, and_comm] } } end @[simp] lemma singleton_eq_rotate_iff {l : list α} {n : ℕ} {x : α} : [x] = l.rotate n ↔ [x] = l := by rw [eq_comm, rotate_eq_singleton_iff, eq_comm] lemma zip_with_rotate_distrib {α β γ : Type*} (f : α → β → γ) (l : list α) (l' : list β) (n : ℕ) (h : l.length = l'.length) : (zip_with f l l').rotate n = zip_with f (l.rotate n) (l'.rotate n) := begin rw [rotate_eq_drop_append_take_mod, rotate_eq_drop_append_take_mod, rotate_eq_drop_append_take_mod, h, zip_with_append, ←zip_with_distrib_drop, ←zip_with_distrib_take, list.length_zip_with, h, min_self], rw [length_drop, length_drop, h] end local attribute [simp] rotate_cons_succ @[simp] lemma zip_with_rotate_one {β : Type*} (f : α → α → β) (x y : α) (l : list α) : zip_with f (x :: y :: l) ((x :: y :: l).rotate 1) = f x y :: zip_with f (y :: l) (l ++ [x]) := by simp lemma nth_le_rotate_one (l : list α) (k : ℕ) (hk : k < (l.rotate 1).length) : (l.rotate 1).nth_le k hk = l.nth_le ((k + 1) % l.length) (mod_lt _ (length_rotate l 1 ▸ k.zero_le.trans_lt hk)) := begin cases l with hd tl, { simp }, { have : k ≤ tl.length, { refine nat.le_of_lt_succ _, simpa using hk }, rcases this.eq_or_lt with rfl|hk', { simp [nth_le_append_right (le_refl _)] }, { simpa [nth_le_append _ hk', length_cons, nat.mod_eq_of_lt (nat.succ_lt_succ hk')] } } end lemma nth_le_rotate (l : list α) (n k : ℕ) (hk : k < (l.rotate n).length) : (l.rotate n).nth_le k hk = l.nth_le ((k + n) % l.length) (mod_lt _ (length_rotate l n ▸ k.zero_le.trans_lt hk)) := begin induction n with n hn generalizing l k, { have hk' : k < l.length := by simpa using hk, simp [nat.mod_eq_of_lt hk'] }, { simp [nat.succ_eq_add_one, ←rotate_rotate, nth_le_rotate_one, hn l, add_comm, add_left_comm] } end /-- A variant of `nth_le_rotate` useful for rewrites. -/ lemma nth_le_rotate' (l : list α) (n k : ℕ) (hk : k < l.length) : (l.rotate n).nth_le ((l.length - n % l.length + k) % l.length) ((nat.mod_lt _ (k.zero_le.trans_lt hk)).trans_le (length_rotate _ _).ge) = l.nth_le k hk := begin rw nth_le_rotate, congr, set m := l.length, rw [mod_add_mod, add_assoc, add_left_comm, add_comm, add_mod, add_mod _ n], cases (n % m).zero_le.eq_or_lt with hn hn, { simpa [←hn] using nat.mod_eq_of_lt hk }, { have mpos : 0 < m := k.zero_le.trans_lt hk, have hm : m - n % m < m := tsub_lt_self mpos hn, have hn' : n % m < m := nat.mod_lt _ mpos, simpa [mod_eq_of_lt hm, tsub_add_cancel_of_le hn'.le] using nat.mod_eq_of_lt hk } end lemma rotate_injective (n : ℕ) : function.injective (λ l : list α, l.rotate n) := begin rintros l l' (h : l.rotate n = l'.rotate n), have hle : l.length = l'.length := (l.length_rotate n).symm.trans (h.symm ▸ l'.length_rotate n), rw [rotate_eq_drop_append_take_mod, rotate_eq_drop_append_take_mod] at h, obtain ⟨hd, ht⟩ := append_inj h _, { rw [←take_append_drop _ l, ht, hd, take_append_drop] }, { rw [length_drop, length_drop, hle] } end -- possibly easier to find in doc-gen, otherwise not that useful. lemma rotate_eq_rotate {l l' : list α} {n : ℕ} : l.rotate n = l'.rotate n ↔ l = l' := (rotate_injective n).eq_iff lemma rotate_eq_iff {l l' : list α} {n : ℕ} : l.rotate n = l' ↔ l = l'.rotate (l'.length - n % l'.length) := begin rw [←@rotate_eq_rotate _ l _ n, rotate_rotate, ←rotate_mod l', add_mod], cases l'.length.zero_le.eq_or_lt with hl hl, { rw [eq_nil_of_length_eq_zero hl.symm, rotate_nil, rotate_eq_nil_iff] }, { cases (nat.zero_le (n % l'.length)).eq_or_lt with hn hn, { simp [←hn] }, { rw [mod_eq_of_lt (tsub_lt_self hl hn), tsub_add_cancel_of_le, mod_self, rotate_zero], exact (nat.mod_lt _ hl).le } } end lemma reverse_rotate (l : list α) (n : ℕ) : (l.rotate n).reverse = l.reverse.rotate (l.length - (n % l.length)) := begin rw [←length_reverse l, ←rotate_eq_iff], induction n with n hn generalizing l, { simp }, { cases l with hd tl, { simp }, { rw [rotate_cons_succ, nat.succ_eq_add_one, ←rotate_rotate, hn], simp } } end lemma rotate_reverse (l : list α) (n : ℕ) : l.reverse.rotate n = (l.rotate (l.length - (n % l.length))).reverse := begin rw [←reverse_reverse l], simp_rw [reverse_rotate, reverse_reverse, rotate_eq_iff, rotate_rotate, length_rotate, length_reverse], rw [←length_reverse l], set k := n % l.reverse.length with hk, cases hk' : k with k', { simp [-length_reverse, ←rotate_rotate] }, { cases l with x l, { simp }, { have : k'.succ < (x :: l).length, { simp [←hk', hk, nat.mod_lt] }, rw [nat.mod_eq_of_lt, tsub_add_cancel_of_le, rotate_length], { exact tsub_le_self }, { exact tsub_lt_self (by simp) nat.succ_pos' } } } end lemma map_rotate {β : Type*} (f : α → β) (l : list α) (n : ℕ) : map f (l.rotate n) = (map f l).rotate n := begin induction n with n hn IH generalizing l, { simp }, { cases l with hd tl, { simp }, { simp [hn] } } end theorem nodup.rotate_eq_self_iff {l : list α} (hl : l.nodup) {n : ℕ} : l.rotate n = l ↔ n % l.length = 0 ∨ l = [] := begin split, { intro h, cases l.length.zero_le.eq_or_lt with hl' hl', { simp [←length_eq_zero, ←hl'] }, left, rw nodup_iff_nth_le_inj at hl, refine hl _ _ (mod_lt _ hl') hl' _, rw ←nth_le_rotate' _ n, simp_rw [h, tsub_add_cancel_of_le (mod_lt _ hl').le, mod_self] }, { rintro (h|h), { rw [←rotate_mod, h], exact rotate_zero l }, { simp [h] } } end lemma nodup.rotate_congr {l : list α} (hl : l.nodup) (hn : l ≠ []) (i j : ℕ) (h : l.rotate i = l.rotate j) : i % l.length = j % l.length := begin have hi : i % l.length < l.length := mod_lt _ (length_pos_of_ne_nil hn), have hj : j % l.length < l.length := mod_lt _ (length_pos_of_ne_nil hn), refine (nodup_iff_nth_le_inj.mp hl) _ _ hi hj _, rw [←nth_le_rotate' l i, ←nth_le_rotate' l j], simp [tsub_add_cancel_of_le, hi.le, hj.le, h] end section is_rotated variables (l l' : list α) /-- `is_rotated l₁ l₂` or `l₁ ~r l₂` asserts that `l₁` and `l₂` are cyclic permutations of each other. This is defined by claiming that `∃ n, l.rotate n = l'`. -/ def is_rotated : Prop := ∃ n, l.rotate n = l' infixr ` ~r `:1000 := is_rotated variables {l l'} @[refl] lemma is_rotated.refl (l : list α) : l ~r l := ⟨0, by simp⟩ @[symm] lemma is_rotated.symm (h : l ~r l') : l' ~r l := begin obtain ⟨n, rfl⟩ := h, cases l with hd tl, { simp }, { use (hd :: tl).length * n - n, rw [rotate_rotate, add_tsub_cancel_of_le, rotate_length_mul], exact nat.le_mul_of_pos_left (by simp) } end lemma is_rotated_comm : l ~r l' ↔ l' ~r l := ⟨is_rotated.symm, is_rotated.symm⟩ @[simp] protected lemma is_rotated.forall (l : list α) (n : ℕ) : l.rotate n ~r l := is_rotated.symm ⟨n, rfl⟩ @[trans] lemma is_rotated.trans {l'' : list α} (h : l ~r l') (h' : l' ~r l'') : l ~r l'' := begin obtain ⟨n, rfl⟩ := h, obtain ⟨m, rfl⟩ := h', rw rotate_rotate, use (n + m) end lemma is_rotated.eqv : equivalence (@is_rotated α) := mk_equivalence _ is_rotated.refl (λ _ _, is_rotated.symm) (λ _ _ _, is_rotated.trans) /-- The relation `list.is_rotated l l'` forms a `setoid` of cycles. -/ def is_rotated.setoid (α : Type*) : setoid (list α) := { r := is_rotated, iseqv := is_rotated.eqv } lemma is_rotated.perm (h : l ~r l') : l ~ l' := exists.elim h (λ _ hl, hl ▸ (rotate_perm _ _).symm) lemma is_rotated.nodup_iff (h : l ~r l') : nodup l ↔ nodup l' := h.perm.nodup_iff lemma is_rotated.mem_iff (h : l ~r l') {a : α} : a ∈ l ↔ a ∈ l' := h.perm.mem_iff @[simp] lemma is_rotated_nil_iff : l ~r [] ↔ l = [] := ⟨λ ⟨n, hn⟩, by simpa using hn, λ h, h ▸ by refl⟩ @[simp] lemma is_rotated_nil_iff' : [] ~r l ↔ [] = l := by rw [is_rotated_comm, is_rotated_nil_iff, eq_comm] @[simp] lemma is_rotated_singleton_iff {x : α} : l ~r [x] ↔ l = [x] := ⟨λ ⟨n, hn⟩, by simpa using hn, λ h, h ▸ by refl⟩ @[simp] lemma is_rotated_singleton_iff' {x : α} : [x] ~r l ↔ [x] = l := by rw [is_rotated_comm, is_rotated_singleton_iff, eq_comm] lemma is_rotated_concat (hd : α) (tl : list α) : (tl ++ [hd]) ~r (hd :: tl) := is_rotated.symm ⟨1, by simp⟩ lemma is_rotated_append : (l ++ l') ~r (l' ++ l) := ⟨l.length, by simp⟩ lemma is_rotated.reverse (h : l ~r l') : l.reverse ~r l'.reverse := begin obtain ⟨n, rfl⟩ := h, exact ⟨_, (reverse_rotate _ _).symm⟩ end lemma is_rotated_reverse_comm_iff : l.reverse ~r l' ↔ l ~r l'.reverse := begin split; { intro h, simpa using h.reverse } end @[simp] lemma is_rotated_reverse_iff : l.reverse ~r l'.reverse ↔ l ~r l' := by simp [is_rotated_reverse_comm_iff] lemma is_rotated_iff_mod : l ~r l' ↔ ∃ n ≤ l.length, l.rotate n = l' := begin refine ⟨λ h, _, λ ⟨n, _, h⟩, ⟨n, h⟩⟩, obtain ⟨n, rfl⟩ := h, cases l with hd tl, { simp }, { refine ⟨n % (hd :: tl).length, _, rotate_mod _ _⟩, refine (nat.mod_lt _ _).le, simp } end lemma is_rotated_iff_mem_map_range : l ~r l' ↔ l' ∈ (list.range (l.length + 1)).map l.rotate := begin simp_rw [mem_map, mem_range, is_rotated_iff_mod], exact ⟨λ ⟨n, hn, h⟩, ⟨n, nat.lt_succ_of_le hn, h⟩, λ ⟨n, hn, h⟩, ⟨n, nat.le_of_lt_succ hn, h⟩⟩ end @[congr] theorem is_rotated.map {β : Type*} {l₁ l₂ : list α} (h : l₁ ~r l₂) (f : α → β) : map f l₁ ~r map f l₂ := begin obtain ⟨n, rfl⟩ := h, rw map_rotate, use n end /-- List of all cyclic permutations of `l`. The `cyclic_permutations` of a nonempty list `l` will always contain `list.length l` elements. This implies that under certain conditions, there are duplicates in `list.cyclic_permutations l`. The `n`th entry is equal to `l.rotate n`, proven in `list.nth_le_cyclic_permutations`. The proof that every cyclic permutant of `l` is in the list is `list.mem_cyclic_permutations_iff`. cyclic_permutations [1, 2, 3, 2, 4] = [[1, 2, 3, 2, 4], [2, 3, 2, 4, 1], [3, 2, 4, 1, 2], [2, 4, 1, 2, 3], [4, 1, 2, 3, 2]] -/ def cyclic_permutations : list α → list (list α) | [] := [[]] | l@(_ :: _) := init (zip_with (++) (tails l) (inits l)) @[simp] lemma cyclic_permutations_nil : cyclic_permutations ([] : list α) = [[]] := rfl lemma cyclic_permutations_cons (x : α) (l : list α) : cyclic_permutations (x :: l) = init (zip_with (++) (tails (x :: l)) (inits (x :: l))) := rfl lemma cyclic_permutations_of_ne_nil (l : list α) (h : l ≠ []) : cyclic_permutations l = init (zip_with (++) (tails l) (inits l)) := begin obtain ⟨hd, tl, rfl⟩ := exists_cons_of_ne_nil h, exact cyclic_permutations_cons _ _, end lemma length_cyclic_permutations_cons (x : α) (l : list α) : length (cyclic_permutations (x :: l)) = length l + 1 := by simp [cyclic_permutations_of_ne_nil] @[simp] lemma length_cyclic_permutations_of_ne_nil (l : list α) (h : l ≠ []) : length (cyclic_permutations l) = length l := by simp [cyclic_permutations_of_ne_nil _ h] @[simp] lemma nth_le_cyclic_permutations (l : list α) (n : ℕ) (hn : n < length (cyclic_permutations l)) : nth_le (cyclic_permutations l) n hn = l.rotate n := begin obtain rfl | h := eq_or_ne l [], { simp }, { rw length_cyclic_permutations_of_ne_nil _ h at hn, simp [init_eq_take, cyclic_permutations_of_ne_nil _ h, nth_le_take', rotate_eq_drop_append_take hn.le] } end lemma mem_cyclic_permutations_self (l : list α) : l ∈ cyclic_permutations l := begin cases l with x l, { simp }, { rw mem_iff_nth_le, refine ⟨0, by simp, _⟩, simp } end lemma length_mem_cyclic_permutations (l : list α) (h : l' ∈ cyclic_permutations l) : length l' = length l := begin obtain ⟨k, hk, rfl⟩ := nth_le_of_mem h, simp end @[simp] lemma mem_cyclic_permutations_iff {l l' : list α} : l ∈ cyclic_permutations l' ↔ l ~r l' := begin split, { intro h, obtain ⟨k, hk, rfl⟩ := nth_le_of_mem h, simp }, { intro h, obtain ⟨k, rfl⟩ := h.symm, rw mem_iff_nth_le, simp only [exists_prop, nth_le_cyclic_permutations], cases l' with x l, { simp }, { refine ⟨k % length (x :: l), _, rotate_mod _ _⟩, simpa using nat.mod_lt _ (zero_lt_succ _) } } end @[simp] lemma cyclic_permutations_eq_nil_iff {l : list α} : cyclic_permutations l = [[]] ↔ l = [] := begin refine ⟨λ h, _, λ h, by simp [h]⟩, rw [eq_comm, ←is_rotated_nil_iff', ←mem_cyclic_permutations_iff, h, mem_singleton] end @[simp] lemma cyclic_permutations_eq_singleton_iff {l : list α} {x : α} : cyclic_permutations l = [[x]] ↔ l = [x] := begin refine ⟨λ h, _, λ h, by simp [cyclic_permutations, h, init_eq_take]⟩, rw [eq_comm, ←is_rotated_singleton_iff', ←mem_cyclic_permutations_iff, h, mem_singleton] end /-- If a `l : list α` is `nodup l`, then all of its cyclic permutants are distinct. -/ lemma nodup.cyclic_permutations {l : list α} (hn : nodup l) : nodup (cyclic_permutations l) := begin cases l with x l, { simp }, rw nodup_iff_nth_le_inj, intros i j hi hj h, simp only [length_cyclic_permutations_cons] at hi hj, rw [←mod_eq_of_lt hi, ←mod_eq_of_lt hj, ←length_cons x l], apply hn.rotate_congr, { simp }, { simpa using h } end @[simp] lemma cyclic_permutations_rotate (l : list α) (k : ℕ) : (l.rotate k).cyclic_permutations = l.cyclic_permutations.rotate k := begin have : (l.rotate k).cyclic_permutations.length = length (l.cyclic_permutations.rotate k), { cases l, { simp }, { rw length_cyclic_permutations_of_ne_nil; simp } }, refine ext_le this (λ n hn hn', _), rw [nth_le_cyclic_permutations, nth_le_rotate, nth_le_cyclic_permutations, rotate_rotate, ←rotate_mod, add_comm], cases l; simp end lemma is_rotated.cyclic_permutations {l l' : list α} (h : l ~r l') : l.cyclic_permutations ~r l'.cyclic_permutations := begin obtain ⟨k, rfl⟩ := h, exact ⟨k, by simp⟩ end @[simp] lemma is_rotated_cyclic_permutations_iff {l l' : list α} : l.cyclic_permutations ~r l'.cyclic_permutations ↔ l ~r l' := begin by_cases hl : l = [], { simp [hl, eq_comm] }, have hl' : l.cyclic_permutations.length = l.length := length_cyclic_permutations_of_ne_nil _ hl, refine ⟨λ h, _, is_rotated.cyclic_permutations⟩, obtain ⟨k, hk⟩ := h, refine ⟨k % l.length, _⟩, have hk' : k % l.length < l.length := mod_lt _ (length_pos_of_ne_nil hl), rw [←nth_le_cyclic_permutations _ _ (hk'.trans_le hl'.ge), ←nth_le_rotate' _ k], simp [hk, hl', tsub_add_cancel_of_le hk'.le] end section decidable variables [decidable_eq α] instance is_rotated_decidable (l l' : list α) : decidable (l ~r l') := decidable_of_iff' _ is_rotated_iff_mem_map_range instance {l l' : list α} : decidable (@setoid.r _ (is_rotated.setoid α) l l') := list.is_rotated_decidable _ _ end decidable end is_rotated end list
a1edf56cbf7e478cc8ca3526108027cd78f26a03
94e33a31faa76775069b071adea97e86e218a8ee
/src/data/fin/tuple/basic.lean
4c7776207ab0dd9d3781655c38dd81af81b91cef
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
27,196
lean
/- Copyright (c) 2019 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Yury Kudryashov, Sébastien Gouëzel, Chris Hughes -/ import data.fin.basic import data.pi.lex /-! # Operation on tuples We interpret maps `Π i : fin n, α i` as `n`-tuples of elements of possibly varying type `α i`, `(α 0, …, α (n-1))`. A particular case is `fin n → α` of elements with all the same type. In this case when `α i` is a constant map, then tuples are isomorphic (but not definitionally equal) to `vector`s. We define the following operations: * `fin.tail` : the tail of an `n+1` tuple, i.e., its last `n` entries; * `fin.cons` : adding an element at the beginning of an `n`-tuple, to get an `n+1`-tuple; * `fin.init` : the beginning of an `n+1` tuple, i.e., its first `n` entries; * `fin.snoc` : adding an element at the end of an `n`-tuple, to get an `n+1`-tuple. The name `snoc` comes from `cons` (i.e., adding an element to the left of a tuple) read in reverse order. * `fin.insert_nth` : insert an element to a tuple at a given position. * `fin.find p` : returns the first index `n` where `p n` is satisfied, and `none` if it is never satisfied. -/ universes u v namespace fin variables {m n : ℕ} open function section tuple /-- There is exactly one tuple of size zero. -/ example (α : fin 0 → Sort u) : unique (Π i : fin 0, α i) := by apply_instance @[simp] lemma tuple0_le {α : Π i : fin 0, Type*} [Π i, preorder (α i)] (f g : Π i, α i) : f ≤ g := fin_zero_elim variables {α : fin (n+1) → Type u} (x : α 0) (q : Πi, α i) (p : Π(i : fin n), α (i.succ)) (i : fin n) (y : α i.succ) (z : α 0) /-- The tail of an `n+1` tuple, i.e., its last `n` entries. -/ def tail (q : Πi, α i) : (Π(i : fin n), α (i.succ)) := λ i, q i.succ lemma tail_def {n : ℕ} {α : fin (n+1) → Type*} {q : Π i, α i} : tail (λ k : fin (n+1), q k) = (λ k : fin n, q k.succ) := rfl /-- Adding an element at the beginning of an `n`-tuple, to get an `n+1`-tuple. -/ def cons (x : α 0) (p : Π(i : fin n), α (i.succ)) : Πi, α i := λ j, fin.cases x p j @[simp] lemma tail_cons : tail (cons x p) = p := by simp [tail, cons] @[simp] lemma cons_succ : cons x p i.succ = p i := by simp [cons] @[simp] lemma cons_zero : cons x p 0 = x := by simp [cons] /-- Updating a tuple and adding an element at the beginning commute. -/ @[simp] lemma cons_update : cons x (update p i y) = update (cons x p) i.succ y := begin ext j, by_cases h : j = 0, { rw h, simp [ne.symm (succ_ne_zero i)] }, { let j' := pred j h, have : j'.succ = j := succ_pred j h, rw [← this, cons_succ], by_cases h' : j' = i, { rw h', simp }, { have : j'.succ ≠ i.succ, by rwa [ne.def, succ_inj], rw [update_noteq h', update_noteq this, cons_succ] } } end /-- As a binary function, `fin.cons` is injective. -/ lemma cons_injective2 : function.injective2 (@cons n α) := λ x₀ y₀ x y h, ⟨congr_fun h 0, funext $ λ i, by simpa using congr_fun h (fin.succ i)⟩ @[simp] lemma cons_eq_cons {x₀ y₀ : α 0} {x y : Π i : fin n, α (i.succ)} : cons x₀ x = cons y₀ y ↔ x₀ = y₀ ∧ x = y := cons_injective2.eq_iff lemma cons_left_injective (x : Π i : fin n, α (i.succ)) : function.injective (λ x₀, cons x₀ x) := cons_injective2.left _ lemma cons_right_injective (x₀ : α 0) : function.injective (cons x₀) := cons_injective2.right _ /-- Adding an element at the beginning of a tuple and then updating it amounts to adding it directly. -/ lemma update_cons_zero : update (cons x p) 0 z = cons z p := begin ext j, by_cases h : j = 0, { rw h, simp }, { simp only [h, update_noteq, ne.def, not_false_iff], let j' := pred j h, have : j'.succ = j := succ_pred j h, rw [← this, cons_succ, cons_succ] } end /-- Concatenating the first element of a tuple with its tail gives back the original tuple -/ @[simp] lemma cons_self_tail : cons (q 0) (tail q) = q := begin ext j, by_cases h : j = 0, { rw h, simp }, { let j' := pred j h, have : j'.succ = j := succ_pred j h, rw [← this, tail, cons_succ] } end /-- Recurse on an `n+1`-tuple by splitting it into a single element and an `n`-tuple. -/ @[elab_as_eliminator] def cons_induction {P : (Π i : fin n.succ, α i) → Sort v} (h : ∀ x₀ x, P (fin.cons x₀ x)) (x : (Π i : fin n.succ, α i)) : P x := _root_.cast (by rw cons_self_tail) $ h (x 0) (tail x) @[simp] lemma cons_induction_cons {P : (Π i : fin n.succ, α i) → Sort v} (h : Π x₀ x, P (fin.cons x₀ x)) (x₀ : α 0) (x : Π i : fin n, α i.succ) : @cons_induction _ _ _ h (cons x₀ x) = h x₀ x := begin rw [cons_induction, cast_eq], congr', exact tail_cons _ _ end @[simp] lemma forall_fin_zero_pi {α : fin 0 → Sort*} {P : (Π i, α i) → Prop} : (∀ x, P x) ↔ P fin_zero_elim := ⟨λ h, h _, λ h x, subsingleton.elim fin_zero_elim x ▸ h⟩ @[simp] lemma exists_fin_zero_pi {α : fin 0 → Sort*} {P : (Π i, α i) → Prop} : (∃ x, P x) ↔ P fin_zero_elim := ⟨λ ⟨x, h⟩, subsingleton.elim x fin_zero_elim ▸ h, λ h, ⟨_, h⟩⟩ lemma forall_fin_succ_pi {P : (Π i, α i) → Prop} : (∀ x, P x) ↔ (∀ a v, P (fin.cons a v)) := ⟨λ h a v, h (fin.cons a v), cons_induction⟩ lemma exists_fin_succ_pi {P : (Π i, α i) → Prop} : (∃ x, P x) ↔ (∃ a v, P (fin.cons a v)) := ⟨λ ⟨x, h⟩, ⟨x 0, tail x, (cons_self_tail x).symm ▸ h⟩, λ ⟨a, v, h⟩, ⟨_, h⟩⟩ /-- Updating the first element of a tuple does not change the tail. -/ @[simp] lemma tail_update_zero : tail (update q 0 z) = tail q := by { ext j, simp [tail, fin.succ_ne_zero] } /-- Updating a nonzero element and taking the tail commute. -/ @[simp] lemma tail_update_succ : tail (update q i.succ y) = update (tail q) i y := begin ext j, by_cases h : j = i, { rw h, simp [tail] }, { simp [tail, (fin.succ_injective n).ne h, h] } end lemma comp_cons {α : Type*} {β : Type*} (g : α → β) (y : α) (q : fin n → α) : g ∘ (cons y q) = cons (g y) (g ∘ q) := begin ext j, by_cases h : j = 0, { rw h, refl }, { let j' := pred j h, have : j'.succ = j := succ_pred j h, rw [← this, cons_succ, comp_app, cons_succ] } end lemma comp_tail {α : Type*} {β : Type*} (g : α → β) (q : fin n.succ → α) : g ∘ (tail q) = tail (g ∘ q) := by { ext j, simp [tail] } lemma le_cons [Π i, preorder (α i)] {x : α 0} {q : Π i, α i} {p : Π i : fin n, α i.succ} : q ≤ cons x p ↔ q 0 ≤ x ∧ tail q ≤ p := forall_fin_succ.trans $ and_congr iff.rfl $ forall_congr $ λ j, by simp [tail] lemma cons_le [Π i, preorder (α i)] {x : α 0} {q : Π i, α i} {p : Π i : fin n, α i.succ} : cons x p ≤ q ↔ x ≤ q 0 ∧ p ≤ tail q := @le_cons _ (λ i, (α i)ᵒᵈ) _ x q p lemma cons_le_cons [Π i, preorder (α i)] {x₀ y₀ : α 0} {x y : Π i : fin n, α (i.succ)} : cons x₀ x ≤ cons y₀ y ↔ x₀ ≤ y₀ ∧ x ≤ y := forall_fin_succ.trans $ and_congr_right' $ by simp only [cons_succ, pi.le_def] lemma pi_lex_lt_cons_cons {x₀ y₀ : α 0} {x y : Π i : fin n, α (i.succ)} (s : Π {i : fin n.succ}, α i → α i → Prop) : pi.lex (<) @s (fin.cons x₀ x) (fin.cons y₀ y) ↔ s x₀ y₀ ∨ x₀ = y₀ ∧ pi.lex (<) (λ i : fin n, @s i.succ) x y := begin simp_rw [pi.lex, fin.exists_fin_succ, fin.cons_succ, fin.cons_zero, fin.forall_fin_succ], simp [and_assoc, exists_and_distrib_left], end @[simp] lemma range_cons {α : Type*} {n : ℕ} (x : α) (b : fin n → α) : set.range (fin.cons x b : fin n.succ → α) = insert x (set.range b) := begin ext y, simp only [set.mem_range, set.mem_insert_iff], split, { rintros ⟨i, rfl⟩, refine cases (or.inl (cons_zero _ _)) (λ i, or.inr ⟨i, _⟩) i, rw cons_succ }, { rintros (rfl | ⟨i, hi⟩), { exact ⟨0, fin.cons_zero _ _⟩ }, { refine ⟨i.succ, _⟩, rw [cons_succ, hi] } } end /-- `fin.append ho u v` appends two vectors of lengths `m` and `n` to produce one of length `o = m + n`. `ho` provides control of definitional equality for the vector length. -/ def append {α : Type*} {o : ℕ} (ho : o = m + n) (u : fin m → α) (v : fin n → α) : fin o → α := λ i, if h : (i : ℕ) < m then u ⟨i, h⟩ else v ⟨(i : ℕ) - m, (tsub_lt_iff_left (le_of_not_lt h)).2 (ho ▸ i.property)⟩ @[simp] lemma fin_append_apply_zero {α : Type*} {o : ℕ} (ho : (o + 1) = (m + 1) + n) (u : fin (m + 1) → α) (v : fin n → α) : fin.append ho u v 0 = u 0 := rfl end tuple section tuple_right /-! In the previous section, we have discussed inserting or removing elements on the left of a tuple. In this section, we do the same on the right. A difference is that `fin (n+1)` is constructed inductively from `fin n` starting from the left, not from the right. This implies that Lean needs more help to realize that elements belong to the right types, i.e., we need to insert casts at several places. -/ variables {α : fin (n+1) → Type u} (x : α (last n)) (q : Πi, α i) (p : Π(i : fin n), α i.cast_succ) (i : fin n) (y : α i.cast_succ) (z : α (last n)) /-- The beginning of an `n+1` tuple, i.e., its first `n` entries -/ def init (q : Πi, α i) (i : fin n) : α i.cast_succ := q i.cast_succ lemma init_def {n : ℕ} {α : fin (n+1) → Type*} {q : Π i, α i} : init (λ k : fin (n+1), q k) = (λ k : fin n, q k.cast_succ) := rfl /-- Adding an element at the end of an `n`-tuple, to get an `n+1`-tuple. The name `snoc` comes from `cons` (i.e., adding an element to the left of a tuple) read in reverse order. -/ def snoc (p : Π(i : fin n), α i.cast_succ) (x : α (last n)) (i : fin (n+1)) : α i := if h : i.val < n then _root_.cast (by rw fin.cast_succ_cast_lt i h) (p (cast_lt i h)) else _root_.cast (by rw eq_last_of_not_lt h) x @[simp] lemma init_snoc : init (snoc p x) = p := begin ext i, have h' := fin.cast_lt_cast_succ i i.is_lt, simp [init, snoc, i.is_lt, h'], convert cast_eq rfl (p i) end @[simp] lemma snoc_cast_succ : snoc p x i.cast_succ = p i := begin have : i.cast_succ.val < n := i.is_lt, have h' := fin.cast_lt_cast_succ i i.is_lt, simp [snoc, this, h'], convert cast_eq rfl (p i) end @[simp] lemma snoc_comp_cast_succ {n : ℕ} {α : Sort*} {a : α} {f : fin n → α} : (snoc f a : fin (n + 1) → α) ∘ cast_succ = f := funext (λ i, by rw [function.comp_app, snoc_cast_succ]) @[simp] lemma snoc_last : snoc p x (last n) = x := by { simp [snoc] } @[simp] lemma snoc_comp_nat_add {n m : ℕ} {α : Sort*} (f : fin (m + n) → α) (a : α) : (snoc f a : fin _ → α) ∘ (nat_add m : fin (n + 1) → fin (m + n + 1)) = snoc (f ∘ nat_add m) a := begin ext i, refine fin.last_cases _ (λ i, _) i, { simp only [function.comp_app], rw [snoc_last, nat_add_last, snoc_last] }, { simp only [function.comp_app], rw [snoc_cast_succ, nat_add_cast_succ, snoc_cast_succ] } end @[simp] lemma snoc_cast_add {α : fin (n + m + 1) → Type*} (f : Π i : fin (n + m), α (cast_succ i)) (a : α (last (n + m))) (i : fin n) : (snoc f a) (cast_add (m + 1) i) = f (cast_add m i) := dif_pos _ @[simp] lemma snoc_comp_cast_add {n m : ℕ} {α : Sort*} (f : fin (n + m) → α) (a : α) : (snoc f a : fin _ → α) ∘ cast_add (m + 1) = f ∘ cast_add m := funext (snoc_cast_add f a) /-- Updating a tuple and adding an element at the end commute. -/ @[simp] lemma snoc_update : snoc (update p i y) x = update (snoc p x) i.cast_succ y := begin ext j, by_cases h : j.val < n, { simp only [snoc, h, dif_pos], by_cases h' : j = cast_succ i, { have C1 : α i.cast_succ = α j, by rw h', have E1 : update (snoc p x) i.cast_succ y j = _root_.cast C1 y, { have : update (snoc p x) j (_root_.cast C1 y) j = _root_.cast C1 y, by simp, convert this, { exact h'.symm }, { exact heq_of_cast_eq (congr_arg α (eq.symm h')) rfl } }, have C2 : α i.cast_succ = α (cast_succ (cast_lt j h)), by rw [cast_succ_cast_lt, h'], have E2 : update p i y (cast_lt j h) = _root_.cast C2 y, { have : update p (cast_lt j h) (_root_.cast C2 y) (cast_lt j h) = _root_.cast C2 y, by simp, convert this, { simp [h, h'] }, { exact heq_of_cast_eq C2 rfl } }, rw [E1, E2], exact eq_rec_compose _ _ _ }, { have : ¬(cast_lt j h = i), by { assume E, apply h', rw [← E, cast_succ_cast_lt] }, simp [h', this, snoc, h] } }, { rw eq_last_of_not_lt h, simp [ne.symm (ne_of_lt (cast_succ_lt_last i))] } end /-- Adding an element at the beginning of a tuple and then updating it amounts to adding it directly. -/ lemma update_snoc_last : update (snoc p x) (last n) z = snoc p z := begin ext j, by_cases h : j.val < n, { have : j ≠ last n := ne_of_lt h, simp [h, update_noteq, this, snoc] }, { rw eq_last_of_not_lt h, simp } end /-- Concatenating the first element of a tuple with its tail gives back the original tuple -/ @[simp] lemma snoc_init_self : snoc (init q) (q (last n)) = q := begin ext j, by_cases h : j.val < n, { have : j ≠ last n := ne_of_lt h, simp [h, update_noteq, this, snoc, init, cast_succ_cast_lt], have A : cast_succ (cast_lt j h) = j := cast_succ_cast_lt _ _, rw ← cast_eq rfl (q j), congr' 1; rw A }, { rw eq_last_of_not_lt h, simp } end /-- Updating the last element of a tuple does not change the beginning. -/ @[simp] lemma init_update_last : init (update q (last n) z) = init q := by { ext j, simp [init, ne_of_lt, cast_succ_lt_last] } /-- Updating an element and taking the beginning commute. -/ @[simp] lemma init_update_cast_succ : init (update q i.cast_succ y) = update (init q) i y := begin ext j, by_cases h : j = i, { rw h, simp [init] }, { simp [init, h] } end /-- `tail` and `init` commute. We state this lemma in a non-dependent setting, as otherwise it would involve a cast to convince Lean that the two types are equal, making it harder to use. -/ lemma tail_init_eq_init_tail {β : Type*} (q : fin (n+2) → β) : tail (init q) = init (tail q) := by { ext i, simp [tail, init, cast_succ_fin_succ] } /-- `cons` and `snoc` commute. We state this lemma in a non-dependent setting, as otherwise it would involve a cast to convince Lean that the two types are equal, making it harder to use. -/ lemma cons_snoc_eq_snoc_cons {β : Type*} (a : β) (q : fin n → β) (b : β) : @cons n.succ (λ i, β) a (snoc q b) = snoc (cons a q) b := begin ext i, by_cases h : i = 0, { rw h, refl }, set j := pred i h with ji, have : i = j.succ, by rw [ji, succ_pred], rw [this, cons_succ], by_cases h' : j.val < n, { set k := cast_lt j h' with jk, have : j = k.cast_succ, by rw [jk, cast_succ_cast_lt], rw [this, ← cast_succ_fin_succ], simp }, rw [eq_last_of_not_lt h', succ_last], simp end lemma comp_snoc {α : Type*} {β : Type*} (g : α → β) (q : fin n → α) (y : α) : g ∘ (snoc q y) = snoc (g ∘ q) (g y) := begin ext j, by_cases h : j.val < n, { have : j ≠ last n := ne_of_lt h, simp [h, this, snoc, cast_succ_cast_lt] }, { rw eq_last_of_not_lt h, simp } end lemma comp_init {α : Type*} {β : Type*} (g : α → β) (q : fin n.succ → α) : g ∘ (init q) = init (g ∘ q) := by { ext j, simp [init] } end tuple_right section insert_nth variables {α : fin (n+1) → Type u} {β : Type v} /-- Define a function on `fin (n + 1)` from a value on `i : fin (n + 1)` and values on each `fin.succ_above i j`, `j : fin n`. This version is elaborated as eliminator and works for propositions, see also `fin.insert_nth` for a version without an `@[elab_as_eliminator]` attribute. -/ @[elab_as_eliminator] def succ_above_cases {α : fin (n + 1) → Sort u} (i : fin (n + 1)) (x : α i) (p : Π j : fin n, α (i.succ_above j)) (j : fin (n + 1)) : α j := if hj : j = i then eq.rec x hj.symm else if hlt : j < i then eq.rec_on (succ_above_cast_lt hlt) (p _) else eq.rec_on (succ_above_pred $ (ne.lt_or_lt hj).resolve_left hlt) (p _) lemma forall_iff_succ_above {p : fin (n + 1) → Prop} (i : fin (n + 1)) : (∀ j, p j) ↔ p i ∧ ∀ j, p (i.succ_above j) := ⟨λ h, ⟨h _, λ j, h _⟩, λ h, succ_above_cases i h.1 h.2⟩ /-- Insert an element into a tuple at a given position. For `i = 0` see `fin.cons`, for `i = fin.last n` see `fin.snoc`. See also `fin.succ_above_cases` for a version elaborated as an eliminator. -/ def insert_nth (i : fin (n + 1)) (x : α i) (p : Π j : fin n, α (i.succ_above j)) (j : fin (n + 1)) : α j := succ_above_cases i x p j @[simp] lemma insert_nth_apply_same (i : fin (n + 1)) (x : α i) (p : Π j, α (i.succ_above j)) : insert_nth i x p i = x := by simp [insert_nth, succ_above_cases] @[simp] lemma insert_nth_apply_succ_above (i : fin (n + 1)) (x : α i) (p : Π j, α (i.succ_above j)) (j : fin n) : insert_nth i x p (i.succ_above j) = p j := begin simp only [insert_nth, succ_above_cases, dif_neg (succ_above_ne _ _)], by_cases hlt : j.cast_succ < i, { rw [dif_pos ((succ_above_lt_iff _ _).2 hlt)], apply eq_of_heq ((eq_rec_heq _ _).trans _), rw [cast_lt_succ_above hlt] }, { rw [dif_neg (mt (succ_above_lt_iff _ _).1 hlt)], apply eq_of_heq ((eq_rec_heq _ _).trans _), rw [pred_succ_above (le_of_not_lt hlt)] } end @[simp] lemma succ_above_cases_eq_insert_nth : @succ_above_cases.{u + 1} = @insert_nth.{u} := rfl @[simp] lemma insert_nth_comp_succ_above (i : fin (n + 1)) (x : β) (p : fin n → β) : insert_nth i x p ∘ i.succ_above = p := funext $ insert_nth_apply_succ_above i x p lemma insert_nth_eq_iff {i : fin (n + 1)} {x : α i} {p : Π j, α (i.succ_above j)} {q : Π j, α j} : i.insert_nth x p = q ↔ q i = x ∧ p = (λ j, q (i.succ_above j)) := by simp [funext_iff, forall_iff_succ_above i, eq_comm] lemma eq_insert_nth_iff {i : fin (n + 1)} {x : α i} {p : Π j, α (i.succ_above j)} {q : Π j, α j} : q = i.insert_nth x p ↔ q i = x ∧ p = (λ j, q (i.succ_above j)) := eq_comm.trans insert_nth_eq_iff lemma insert_nth_apply_below {i j : fin (n + 1)} (h : j < i) (x : α i) (p : Π k, α (i.succ_above k)) : i.insert_nth x p j = eq.rec_on (succ_above_cast_lt h) (p $ j.cast_lt _) := by rw [insert_nth, succ_above_cases, dif_neg h.ne, dif_pos h] lemma insert_nth_apply_above {i j : fin (n + 1)} (h : i < j) (x : α i) (p : Π k, α (i.succ_above k)) : i.insert_nth x p j = eq.rec_on (succ_above_pred h) (p $ j.pred _) := by rw [insert_nth, succ_above_cases, dif_neg h.ne', dif_neg h.not_lt] lemma insert_nth_zero (x : α 0) (p : Π j : fin n, α (succ_above 0 j)) : insert_nth 0 x p = cons x (λ j, _root_.cast (congr_arg α (congr_fun succ_above_zero j)) (p j)) := begin refine insert_nth_eq_iff.2 ⟨by simp, _⟩, ext j, convert (cons_succ _ _ _).symm end @[simp] lemma insert_nth_zero' (x : β) (p : fin n → β) : @insert_nth _ (λ _, β) 0 x p = cons x p := by simp [insert_nth_zero] lemma insert_nth_last (x : α (last n)) (p : Π j : fin n, α ((last n).succ_above j)) : insert_nth (last n) x p = snoc (λ j, _root_.cast (congr_arg α (succ_above_last_apply j)) (p j)) x := begin refine insert_nth_eq_iff.2 ⟨by simp, _⟩, ext j, apply eq_of_heq, transitivity snoc (λ j, _root_.cast (congr_arg α (succ_above_last_apply j)) (p j)) x j.cast_succ, { rw [snoc_cast_succ], exact (cast_heq _ _).symm }, { apply congr_arg_heq, rw [succ_above_last] } end @[simp] lemma insert_nth_last' (x : β) (p : fin n → β) : @insert_nth _ (λ _, β) (last n) x p = snoc p x := by simp [insert_nth_last] @[simp] lemma insert_nth_zero_right [Π j, has_zero (α j)] (i : fin (n + 1)) (x : α i) : i.insert_nth x 0 = pi.single i x := insert_nth_eq_iff.2 $ by simp [succ_above_ne, pi.zero_def] lemma insert_nth_binop (op : Π j, α j → α j → α j) (i : fin (n + 1)) (x y : α i) (p q : Π j, α (i.succ_above j)) : i.insert_nth (op i x y) (λ j, op _ (p j) (q j)) = λ j, op j (i.insert_nth x p j) (i.insert_nth y q j) := insert_nth_eq_iff.2 $ by simp @[simp] lemma insert_nth_mul [Π j, has_mul (α j)] (i : fin (n + 1)) (x y : α i) (p q : Π j, α (i.succ_above j)) : i.insert_nth (x * y) (p * q) = i.insert_nth x p * i.insert_nth y q := insert_nth_binop (λ _, (*)) i x y p q @[simp] lemma insert_nth_add [Π j, has_add (α j)] (i : fin (n + 1)) (x y : α i) (p q : Π j, α (i.succ_above j)) : i.insert_nth (x + y) (p + q) = i.insert_nth x p + i.insert_nth y q := insert_nth_binop (λ _, (+)) i x y p q @[simp] lemma insert_nth_div [Π j, has_div (α j)] (i : fin (n + 1)) (x y : α i) (p q : Π j, α (i.succ_above j)) : i.insert_nth (x / y) (p / q) = i.insert_nth x p / i.insert_nth y q := insert_nth_binop (λ _, (/)) i x y p q @[simp] lemma insert_nth_sub [Π j, has_sub (α j)] (i : fin (n + 1)) (x y : α i) (p q : Π j, α (i.succ_above j)) : i.insert_nth (x - y) (p - q) = i.insert_nth x p - i.insert_nth y q := insert_nth_binop (λ _, has_sub.sub) i x y p q @[simp] lemma insert_nth_sub_same [Π j, add_group (α j)] (i : fin (n + 1)) (x y : α i) (p : Π j, α (i.succ_above j)) : i.insert_nth x p - i.insert_nth y p = pi.single i (x - y) := by simp_rw [← insert_nth_sub, ← insert_nth_zero_right, pi.sub_def, sub_self, pi.zero_def] variables [Π i, preorder (α i)] lemma insert_nth_le_iff {i : fin (n + 1)} {x : α i} {p : Π j, α (i.succ_above j)} {q : Π j, α j} : i.insert_nth x p ≤ q ↔ x ≤ q i ∧ p ≤ (λ j, q (i.succ_above j)) := by simp [pi.le_def, forall_iff_succ_above i] lemma le_insert_nth_iff {i : fin (n + 1)} {x : α i} {p : Π j, α (i.succ_above j)} {q : Π j, α j} : q ≤ i.insert_nth x p ↔ q i ≤ x ∧ (λ j, q (i.succ_above j)) ≤ p := by simp [pi.le_def, forall_iff_succ_above i] open set lemma insert_nth_mem_Icc {i : fin (n + 1)} {x : α i} {p : Π j, α (i.succ_above j)} {q₁ q₂ : Π j, α j} : i.insert_nth x p ∈ Icc q₁ q₂ ↔ x ∈ Icc (q₁ i) (q₂ i) ∧ p ∈ Icc (λ j, q₁ (i.succ_above j)) (λ j, q₂ (i.succ_above j)) := by simp only [mem_Icc, insert_nth_le_iff, le_insert_nth_iff, and.assoc, and.left_comm] lemma preimage_insert_nth_Icc_of_mem {i : fin (n + 1)} {x : α i} {q₁ q₂ : Π j, α j} (hx : x ∈ Icc (q₁ i) (q₂ i)) : i.insert_nth x ⁻¹' (Icc q₁ q₂) = Icc (λ j, q₁ (i.succ_above j)) (λ j, q₂ (i.succ_above j)) := set.ext $ λ p, by simp only [mem_preimage, insert_nth_mem_Icc, hx, true_and] lemma preimage_insert_nth_Icc_of_not_mem {i : fin (n + 1)} {x : α i} {q₁ q₂ : Π j, α j} (hx : x ∉ Icc (q₁ i) (q₂ i)) : i.insert_nth x ⁻¹' (Icc q₁ q₂) = ∅ := set.ext $ λ p, by simp only [mem_preimage, insert_nth_mem_Icc, hx, false_and, mem_empty_eq] end insert_nth section find /-- `find p` returns the first index `n` where `p n` is satisfied, and `none` if it is never satisfied. -/ def find : Π {n : ℕ} (p : fin n → Prop) [decidable_pred p], option (fin n) | 0 p _ := none | (n+1) p _ := by resetI; exact option.cases_on (@find n (λ i, p (i.cast_lt (nat.lt_succ_of_lt i.2))) _) (if h : p (fin.last n) then some (fin.last n) else none) (λ i, some (i.cast_lt (nat.lt_succ_of_lt i.2))) /-- If `find p = some i`, then `p i` holds -/ lemma find_spec : Π {n : ℕ} (p : fin n → Prop) [decidable_pred p] {i : fin n} (hi : i ∈ by exactI fin.find p), p i | 0 p I i hi := option.no_confusion hi | (n+1) p I i hi := begin dsimp [find] at hi, resetI, cases h : find (λ i : fin n, (p (i.cast_lt (nat.lt_succ_of_lt i.2)))) with j, { rw h at hi, dsimp at hi, split_ifs at hi with hl hl, { exact hi ▸ hl }, { exact hi.elim } }, { rw h at hi, rw [← option.some_inj.1 hi], exact find_spec _ h } end /-- `find p` does not return `none` if and only if `p i` holds at some index `i`. -/ lemma is_some_find_iff : Π {n : ℕ} {p : fin n → Prop} [decidable_pred p], by exactI (find p).is_some ↔ ∃ i, p i | 0 p _ := iff_of_false (λ h, bool.no_confusion h) (λ ⟨i, _⟩, fin_zero_elim i) | (n+1) p _ := ⟨λ h, begin rw [option.is_some_iff_exists] at h, cases h with i hi, exactI ⟨i, find_spec _ hi⟩ end, λ ⟨⟨i, hin⟩, hi⟩, begin resetI, dsimp [find], cases h : find (λ i : fin n, (p (i.cast_lt (nat.lt_succ_of_lt i.2)))) with j, { split_ifs with hl hl, { exact option.is_some_some }, { have := (@is_some_find_iff n (λ x, p (x.cast_lt (nat.lt_succ_of_lt x.2))) _).2 ⟨⟨i, lt_of_le_of_ne (nat.le_of_lt_succ hin) (λ h, by clear_aux_decl; cases h; exact hl hi)⟩, hi⟩, rw h at this, exact this } }, { simp } end⟩ /-- `find p` returns `none` if and only if `p i` never holds. -/ lemma find_eq_none_iff {n : ℕ} {p : fin n → Prop} [decidable_pred p] : find p = none ↔ ∀ i, ¬ p i := by rw [← not_exists, ← is_some_find_iff]; cases (find p); simp /-- If `find p` returns `some i`, then `p j` does not hold for `j < i`, i.e., `i` is minimal among the indices where `p` holds. -/ lemma find_min : Π {n : ℕ} {p : fin n → Prop} [decidable_pred p] {i : fin n} (hi : i ∈ by exactI fin.find p) {j : fin n} (hj : j < i), ¬ p j | 0 p _ i hi j hj hpj := option.no_confusion hi | (n+1) p _ i hi ⟨j, hjn⟩ hj hpj := begin resetI, dsimp [find] at hi, cases h : find (λ i : fin n, (p (i.cast_lt (nat.lt_succ_of_lt i.2)))) with k, { rw [h] at hi, split_ifs at hi with hl hl, { subst hi, rw [find_eq_none_iff] at h, exact h ⟨j, hj⟩ hpj }, { exact hi.elim } }, { rw h at hi, dsimp at hi, obtain rfl := option.some_inj.1 hi, exact find_min h (show (⟨j, lt_trans hj k.2⟩ : fin n) < k, from hj) hpj } end lemma find_min' {p : fin n → Prop} [decidable_pred p] {i : fin n} (h : i ∈ fin.find p) {j : fin n} (hj : p j) : i ≤ j := le_of_not_gt (λ hij, find_min h hij hj) lemma nat_find_mem_find {p : fin n → Prop} [decidable_pred p] (h : ∃ i, ∃ hin : i < n, p ⟨i, hin⟩) : (⟨nat.find h, (nat.find_spec h).fst⟩ : fin n) ∈ find p := let ⟨i, hin, hi⟩ := h in begin cases hf : find p with f, { rw [find_eq_none_iff] at hf, exact (hf ⟨i, hin⟩ hi).elim }, { refine option.some_inj.2 (le_antisymm _ _), { exact find_min' hf (nat.find_spec h).snd }, { exact nat.find_min' _ ⟨f.2, by convert find_spec p hf; exact fin.eta _ _⟩ } } end lemma mem_find_iff {p : fin n → Prop} [decidable_pred p] {i : fin n} : i ∈ fin.find p ↔ p i ∧ ∀ j, p j → i ≤ j := ⟨λ hi, ⟨find_spec _ hi, λ _, find_min' hi⟩, begin rintros ⟨hpi, hj⟩, cases hfp : fin.find p, { rw [find_eq_none_iff] at hfp, exact (hfp _ hpi).elim }, { exact option.some_inj.2 (le_antisymm (find_min' hfp hpi) (hj _ (find_spec _ hfp))) } end⟩ lemma find_eq_some_iff {p : fin n → Prop} [decidable_pred p] {i : fin n} : fin.find p = some i ↔ p i ∧ ∀ j, p j → i ≤ j := mem_find_iff lemma mem_find_of_unique {p : fin n → Prop} [decidable_pred p] (h : ∀ i j, p i → p j → i = j) {i : fin n} (hi : p i) : i ∈ fin.find p := mem_find_iff.2 ⟨hi, λ j hj, le_of_eq $ h i j hi hj⟩ end find end fin
4f2e920d41741009e0f08a0425f908b65ad57d63
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/limits/shapes/terminal.lean
ac1431866c03b973530bba4d9b853442a0f66bcf
[ "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
27,320
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Bhavik Mehta -/ import category_theory.pempty import category_theory.limits.has_limits import category_theory.epi_mono import category_theory.category.preorder /-! # Initial and terminal objects in a category. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. ## References * [Stacks: Initial and final objects](https://stacks.math.columbia.edu/tag/002B) -/ noncomputable theory universes w w' v v₁ v₂ u u₁ u₂ open category_theory namespace category_theory.limits variables {C : Type u₁} [category.{v₁} C] local attribute [tidy] tactic.discrete_cases /-- Construct a cone for the empty diagram given an object. -/ @[simps] def as_empty_cone (X : C) : cone (functor.empty.{0} C) := { X := X, π := by tidy } /-- Construct a cocone for the empty diagram given an object. -/ @[simps] def as_empty_cocone (X : C) : cocone (functor.empty.{0} C) := { X := X, ι := by tidy } /-- `X` is terminal if the cone it induces on the empty diagram is limiting. -/ abbreviation is_terminal (X : C) := is_limit (as_empty_cone X) /-- `X` is initial if the cocone it induces on the empty diagram is colimiting. -/ abbreviation is_initial (X : C) := is_colimit (as_empty_cocone X) /-- An object `Y` is terminal iff for every `X` there is a unique morphism `X ⟶ Y`. -/ def is_terminal_equiv_unique (F : discrete.{0} pempty.{1} ⥤ C) (Y : C) : is_limit (⟨Y, by tidy⟩ : cone F) ≃ ∀ X : C, unique (X ⟶ Y) := { to_fun := λ t X, { default := t.lift ⟨X, by tidy⟩, uniq := λ f, t.uniq ⟨X, by tidy⟩ f (by tidy) }, inv_fun := λ u, { lift := λ s, (u s.X).default, uniq' := λ s _ _, (u s.X).2 _ }, left_inv := by tidy, right_inv := by tidy } /-- An object `Y` is terminal if for every `X` there is a unique morphism `X ⟶ Y` (as an instance). -/ def is_terminal.of_unique (Y : C) [h : Π X : C, unique (X ⟶ Y)] : is_terminal Y := { lift := λ s, (h s.X).default } /-- If `α` is a preorder with top, then `⊤` is a terminal object. -/ def is_terminal_top {α : Type*} [preorder α] [order_top α] : is_terminal (⊤ : α) := is_terminal.of_unique _ /-- Transport a term of type `is_terminal` across an isomorphism. -/ def is_terminal.of_iso {Y Z : C} (hY : is_terminal Y) (i : Y ≅ Z) : is_terminal Z := is_limit.of_iso_limit hY { hom := { hom := i.hom }, inv := { hom := i.inv } } /-- An object `X` is initial iff for every `Y` there is a unique morphism `X ⟶ Y`. -/ def is_initial_equiv_unique (F : discrete.{0} pempty.{1} ⥤ C) (X : C) : is_colimit (⟨X, by tidy⟩ : cocone F) ≃ ∀ Y : C, unique (X ⟶ Y) := { to_fun := λ t X, { default := t.desc ⟨X, by tidy⟩, uniq := λ f, t.uniq ⟨X, by tidy⟩ f (by tidy) }, inv_fun := λ u, { desc := λ s, (u s.X).default, uniq' := λ s _ _, (u s.X).2 _ }, left_inv := by tidy, right_inv := by tidy } /-- An object `X` is initial if for every `Y` there is a unique morphism `X ⟶ Y` (as an instance). -/ def is_initial.of_unique (X : C) [h : Π Y : C, unique (X ⟶ Y)] : is_initial X := { desc := λ s, (h s.X).default } /-- If `α` is a preorder with bot, then `⊥` is an initial object. -/ def is_initial_bot {α : Type*} [preorder α] [order_bot α] : is_initial (⊥ : α) := is_initial.of_unique _ /-- Transport a term of type `is_initial` across an isomorphism. -/ def is_initial.of_iso {X Y : C} (hX : is_initial X) (i : X ≅ Y) : is_initial Y := is_colimit.of_iso_colimit hX { hom := { hom := i.hom }, inv := { hom := i.inv } } /-- Give the morphism to a terminal object from any other. -/ def is_terminal.from {X : C} (t : is_terminal X) (Y : C) : Y ⟶ X := t.lift (as_empty_cone Y) /-- Any two morphisms to a terminal object are equal. -/ lemma is_terminal.hom_ext {X Y : C} (t : is_terminal X) (f g : Y ⟶ X) : f = g := t.hom_ext (by tidy) @[simp] lemma is_terminal.comp_from {Z : C} (t : is_terminal Z) {X Y : C} (f : X ⟶ Y) : f ≫ t.from Y = t.from X := t.hom_ext _ _ @[simp] lemma is_terminal.from_self {X : C} (t : is_terminal X) : t.from X = 𝟙 X := t.hom_ext _ _ /-- Give the morphism from an initial object to any other. -/ def is_initial.to {X : C} (t : is_initial X) (Y : C) : X ⟶ Y := t.desc (as_empty_cocone Y) /-- Any two morphisms from an initial object are equal. -/ lemma is_initial.hom_ext {X Y : C} (t : is_initial X) (f g : X ⟶ Y) : f = g := t.hom_ext (by tidy) @[simp] lemma is_initial.to_comp {X : C} (t : is_initial X) {Y Z : C} (f : Y ⟶ Z) : t.to Y ≫ f = t.to Z := t.hom_ext _ _ @[simp] lemma is_initial.to_self {X : C} (t : is_initial X) : t.to X = 𝟙 X := t.hom_ext _ _ /-- Any morphism from a terminal object is split mono. -/ lemma is_terminal.is_split_mono_from {X Y : C} (t : is_terminal X) (f : X ⟶ Y) : is_split_mono f := is_split_mono.mk' ⟨t.from _, t.hom_ext _ _⟩ /-- Any morphism to an initial object is split epi. -/ lemma is_initial.is_split_epi_to {X Y : C} (t : is_initial X) (f : Y ⟶ X) : is_split_epi f := is_split_epi.mk' ⟨t.to _, t.hom_ext _ _⟩ /-- Any morphism from a terminal object is mono. -/ lemma is_terminal.mono_from {X Y : C} (t : is_terminal X) (f : X ⟶ Y) : mono f := by haveI := t.is_split_mono_from f; apply_instance /-- Any morphism to an initial object is epi. -/ lemma is_initial.epi_to {X Y : C} (t : is_initial X) (f : Y ⟶ X) : epi f := by haveI := t.is_split_epi_to f; apply_instance /-- If `T` and `T'` are terminal, they are isomorphic. -/ @[simps] def is_terminal.unique_up_to_iso {T T' : C} (hT : is_terminal T) (hT' : is_terminal T') : T ≅ T' := { hom := hT'.from _, inv := hT.from _ } /-- If `I` and `I'` are initial, they are isomorphic. -/ @[simps] def is_initial.unique_up_to_iso {I I' : C} (hI : is_initial I) (hI' : is_initial I') : I ≅ I' := { hom := hI.to _, inv := hI'.to _ } variable (C) /-- A category has a terminal object if it has a limit over the empty diagram. Use `has_terminal_of_unique` to construct instances. -/ abbreviation has_terminal := has_limits_of_shape (discrete.{0} pempty) C /-- A category has an initial object if it has a colimit over the empty diagram. Use `has_initial_of_unique` to construct instances. -/ abbreviation has_initial := has_colimits_of_shape (discrete.{0} pempty) C section univ variables (X : C) {F₁ : discrete.{w} pempty ⥤ C} {F₂ : discrete.{w'} pempty ⥤ C} /-- Being terminal is independent of the empty diagram, its universe, and the cone over it, as long as the cone points are isomorphic. -/ def is_limit_change_empty_cone {c₁ : cone F₁} (hl : is_limit c₁) (c₂ : cone F₂) (hi : c₁.X ≅ c₂.X) : is_limit c₂ := { lift := λ c, hl.lift ⟨c.X, by tidy⟩ ≫ hi.hom, fac' := λ _ j, j.as.elim, uniq' := λ c f _, by { erw ← hl.uniq ⟨c.X, by tidy⟩ (f ≫ hi.inv) (λ j, j.as.elim), simp } } /-- Replacing an empty cone in `is_limit` by another with the same cone point is an equivalence. -/ def is_limit_empty_cone_equiv (c₁ : cone F₁) (c₂ : cone F₂) (h : c₁.X ≅ c₂.X) : is_limit c₁ ≃ is_limit c₂ := { to_fun := λ hl, is_limit_change_empty_cone C hl c₂ h, inv_fun := λ hl, is_limit_change_empty_cone C hl c₁ h.symm, left_inv := by tidy, right_inv := by tidy } lemma has_terminal_change_diagram (h : has_limit F₁) : has_limit F₂ := ⟨⟨⟨⟨limit F₁, by tidy⟩, is_limit_change_empty_cone C (limit.is_limit F₁) _ (eq_to_iso rfl)⟩⟩⟩ lemma has_terminal_change_universe [h : has_limits_of_shape (discrete.{w} pempty) C] : has_limits_of_shape (discrete.{w'} pempty) C := { has_limit := λ J, has_terminal_change_diagram C (let f := h.1 in f (functor.empty C)) } /-- Being initial is independent of the empty diagram, its universe, and the cocone over it, as long as the cocone points are isomorphic. -/ def is_colimit_change_empty_cocone {c₁ : cocone F₁} (hl : is_colimit c₁) (c₂ : cocone F₂) (hi : c₁.X ≅ c₂.X) : is_colimit c₂ := { desc := λ c, hi.inv ≫ hl.desc ⟨c.X, by tidy⟩, fac' := λ _ j, j.as.elim, uniq' := λ c f _, by { erw ← hl.uniq ⟨c.X, by tidy⟩ (hi.hom ≫ f) (λ j, j.as.elim), simp } } /-- Replacing an empty cocone in `is_colimit` by another with the same cocone point is an equivalence. -/ def is_colimit_empty_cocone_equiv (c₁ : cocone F₁) (c₂ : cocone F₂) (h : c₁.X ≅ c₂.X) : is_colimit c₁ ≃ is_colimit c₂ := { to_fun := λ hl, is_colimit_change_empty_cocone C hl c₂ h, inv_fun := λ hl, is_colimit_change_empty_cocone C hl c₁ h.symm, left_inv := by tidy, right_inv := by tidy } lemma has_initial_change_diagram (h : has_colimit F₁) : has_colimit F₂ := ⟨⟨⟨⟨colimit F₁, by tidy⟩, is_colimit_change_empty_cocone C (colimit.is_colimit F₁) _ (eq_to_iso rfl)⟩⟩⟩ lemma has_initial_change_universe [h : has_colimits_of_shape (discrete.{w} pempty) C] : has_colimits_of_shape (discrete.{w'} pempty) C := { has_colimit := λ J, has_initial_change_diagram C (let f := h.1 in f (functor.empty C)) } end univ /-- An arbitrary choice of terminal object, if one exists. You can use the notation `⊤_ C`. This object is characterized by having a unique morphism from any object. -/ abbreviation terminal [has_terminal C] : C := limit (functor.empty.{0} C) /-- An arbitrary choice of initial object, if one exists. You can use the notation `⊥_ C`. This object is characterized by having a unique morphism to any object. -/ abbreviation initial [has_initial C] : C := colimit (functor.empty.{0} C) notation `⊤_ ` C:20 := terminal C notation `⊥_ ` C:20 := initial C section variables {C} /-- We can more explicitly show that a category has a terminal object by specifying the object, and showing there is a unique morphism to it from any other object. -/ lemma has_terminal_of_unique (X : C) [h : Π Y : C, unique (Y ⟶ X)] : has_terminal C := { has_limit := λ F, has_limit.mk ⟨_, (is_terminal_equiv_unique F X).inv_fun h⟩ } lemma is_terminal.has_terminal {X : C} (h : is_terminal X) : has_terminal C := { has_limit := λ F, has_limit.mk ⟨⟨X, by tidy⟩, is_limit_change_empty_cone _ h _ (iso.refl _)⟩ } /-- We can more explicitly show that a category has an initial object by specifying the object, and showing there is a unique morphism from it to any other object. -/ lemma has_initial_of_unique (X : C) [h : Π Y : C, unique (X ⟶ Y)] : has_initial C := { has_colimit := λ F, has_colimit.mk ⟨_, (is_initial_equiv_unique F X).inv_fun h⟩ } lemma is_initial.has_initial {X : C} (h : is_initial X) : has_initial C := { has_colimit := λ F, has_colimit.mk ⟨⟨X, by tidy⟩, is_colimit_change_empty_cocone _ h _ (iso.refl _)⟩ } /-- The map from an object to the terminal object. -/ abbreviation terminal.from [has_terminal C] (P : C) : P ⟶ ⊤_ C := limit.lift (functor.empty C) (as_empty_cone P) /-- The map to an object from the initial object. -/ abbreviation initial.to [has_initial C] (P : C) : ⊥_ C ⟶ P := colimit.desc (functor.empty C) (as_empty_cocone P) /-- A terminal object is terminal. -/ def terminal_is_terminal [has_terminal C] : is_terminal (⊤_ C) := { lift := λ s, terminal.from _ } /-- An initial object is initial. -/ def initial_is_initial [has_initial C] : is_initial (⊥_ C) := { desc := λ s, initial.to _ } instance unique_to_terminal [has_terminal C] (P : C) : unique (P ⟶ ⊤_ C) := is_terminal_equiv_unique _ (⊤_ C) terminal_is_terminal P instance unique_from_initial [has_initial C] (P : C) : unique (⊥_ C ⟶ P) := is_initial_equiv_unique _ (⊥_ C) initial_is_initial P @[simp] lemma terminal.comp_from [has_terminal C] {P Q : C} (f : P ⟶ Q) : f ≫ terminal.from Q = terminal.from P := by tidy @[simp] lemma initial.to_comp [has_initial C] {P Q : C} (f : P ⟶ Q) : initial.to P ≫ f = initial.to Q := by tidy /-- The (unique) isomorphism between the chosen initial object and any other initial object. -/ @[simp] def initial_iso_is_initial [has_initial C] {P : C} (t : is_initial P) : ⊥_ C ≅ P := initial_is_initial.unique_up_to_iso t /-- The (unique) isomorphism between the chosen terminal object and any other terminal object. -/ @[simp] def terminal_iso_is_terminal [has_terminal C] {P : C} (t : is_terminal P) : ⊤_ C ≅ P := terminal_is_terminal.unique_up_to_iso t /-- Any morphism from a terminal object is split mono. -/ instance terminal.is_split_mono_from {Y : C} [has_terminal C] (f : ⊤_ C ⟶ Y) : is_split_mono f := is_terminal.is_split_mono_from terminal_is_terminal _ /-- Any morphism to an initial object is split epi. -/ instance initial.is_split_epi_to {Y : C} [has_initial C] (f : Y ⟶ ⊥_ C) : is_split_epi f := is_initial.is_split_epi_to initial_is_initial _ /-- An initial object is terminal in the opposite category. -/ def terminal_op_of_initial {X : C} (t : is_initial X) : is_terminal (opposite.op X) := { lift := λ s, (t.to s.X.unop).op, uniq' := λ s m w, quiver.hom.unop_inj (t.hom_ext _ _) } /-- An initial object in the opposite category is terminal in the original category. -/ def terminal_unop_of_initial {X : Cᵒᵖ} (t : is_initial X) : is_terminal X.unop := { lift := λ s, (t.to (opposite.op s.X)).unop, uniq' := λ s m w, quiver.hom.op_inj (t.hom_ext _ _) } /-- A terminal object is initial in the opposite category. -/ def initial_op_of_terminal {X : C} (t : is_terminal X) : is_initial (opposite.op X) := { desc := λ s, (t.from s.X.unop).op, uniq' := λ s m w, quiver.hom.unop_inj (t.hom_ext _ _) } /-- A terminal object in the opposite category is initial in the original category. -/ def initial_unop_of_terminal {X : Cᵒᵖ} (t : is_terminal X) : is_initial X.unop := { desc := λ s, (t.from (opposite.op s.X)).unop, uniq' := λ s m w, quiver.hom.op_inj (t.hom_ext _ _) } instance has_initial_op_of_has_terminal [has_terminal C] : has_initial Cᵒᵖ := (initial_op_of_terminal terminal_is_terminal).has_initial instance has_terminal_op_of_has_initial [has_initial C] : has_terminal Cᵒᵖ := (terminal_op_of_initial initial_is_initial).has_terminal lemma has_terminal_of_has_initial_op [has_initial Cᵒᵖ] : has_terminal C := (terminal_unop_of_initial initial_is_initial).has_terminal lemma has_initial_of_has_terminal_op [has_terminal Cᵒᵖ] : has_initial C := (initial_unop_of_terminal terminal_is_terminal).has_initial instance {J : Type*} [category J] {C : Type*} [category C] [has_terminal C] : has_limit ((category_theory.functor.const J).obj (⊤_ C)) := has_limit.mk { cone := { X := ⊤_ C, π := { app := λ _, terminal.from _, }, }, is_limit := { lift := λ s, terminal.from _, }, } /-- The limit of the constant `⊤_ C` functor is `⊤_ C`. -/ @[simps hom] def limit_const_terminal {J : Type*} [category J] {C : Type*} [category C] [has_terminal C] : limit ((category_theory.functor.const J).obj (⊤_ C)) ≅ ⊤_ C := { hom := terminal.from _, inv := limit.lift ((category_theory.functor.const J).obj (⊤_ C)) { X := ⊤_ C, π := { app := λ j, terminal.from _, }}, } @[simp, reassoc] lemma limit_const_terminal_inv_π {J : Type*} [category J] {C : Type*} [category C] [has_terminal C] {j : J} : limit_const_terminal.inv ≫ limit.π ((category_theory.functor.const J).obj (⊤_ C)) j = terminal.from _ := by ext ⟨⟨⟩⟩ instance {J : Type*} [category J] {C : Type*} [category C] [has_initial C] : has_colimit ((category_theory.functor.const J).obj (⊥_ C)) := has_colimit.mk { cocone := { X := ⊥_ C, ι := { app := λ _, initial.to _, }, }, is_colimit := { desc := λ s, initial.to _, }, } /-- The colimit of the constant `⊥_ C` functor is `⊥_ C`. -/ @[simps inv] def colimit_const_initial {J : Type*} [category J] {C : Type*} [category C] [has_initial C] : colimit ((category_theory.functor.const J).obj (⊥_ C)) ≅ ⊥_ C := { hom := colimit.desc ((category_theory.functor.const J).obj (⊥_ C)) { X := ⊥_ C, ι := { app := λ j, initial.to _, }, }, inv := initial.to _, } @[simp, reassoc] lemma ι_colimit_const_initial_hom {J : Type*} [category J] {C : Type*} [category C] [has_initial C] {j : J} : colimit.ι ((category_theory.functor.const J).obj (⊥_ C)) j ≫ colimit_const_initial.hom = initial.to _ := by ext ⟨⟨⟩⟩ /-- A category is a `initial_mono_class` if the canonical morphism of an initial object is a monomorphism. In practice, this is most useful when given an arbitrary morphism out of the chosen initial object, see `initial.mono_from`. Given a terminal object, this is equivalent to the assumption that the unique morphism from initial to terminal is a monomorphism, which is the second of Freyd's axioms for an AT category. TODO: This is a condition satisfied by categories with zero objects and morphisms. -/ class initial_mono_class (C : Type u₁) [category.{v₁} C] : Prop := (is_initial_mono_from : ∀ {I} (X : C) (hI : is_initial I), mono (hI.to X)) lemma is_initial.mono_from [initial_mono_class C] {I} {X : C} (hI : is_initial I) (f : I ⟶ X) : mono f := begin rw hI.hom_ext f (hI.to X), apply initial_mono_class.is_initial_mono_from, end @[priority 100] instance initial.mono_from [has_initial C] [initial_mono_class C] (X : C) (f : ⊥_ C ⟶ X) : mono f := initial_is_initial.mono_from f /-- To show a category is a `initial_mono_class` it suffices to give an initial object such that every morphism out of it is a monomorphism. -/ lemma initial_mono_class.of_is_initial {I : C} (hI : is_initial I) (h : ∀ X, mono (hI.to X)) : initial_mono_class C := { is_initial_mono_from := λ I' X hI', begin rw hI'.hom_ext (hI'.to X) ((hI'.unique_up_to_iso hI).hom ≫ hI.to X), apply mono_comp, end } /-- To show a category is a `initial_mono_class` it suffices to show every morphism out of the initial object is a monomorphism. -/ lemma initial_mono_class.of_initial [has_initial C] (h : ∀ X : C, mono (initial.to X)) : initial_mono_class C := initial_mono_class.of_is_initial initial_is_initial h /-- To show a category is a `initial_mono_class` it suffices to show the unique morphism from an initial object to a terminal object is a monomorphism. -/ lemma initial_mono_class.of_is_terminal {I T : C} (hI : is_initial I) (hT : is_terminal T) (f : mono (hI.to T)) : initial_mono_class C := initial_mono_class.of_is_initial hI (λ X, mono_of_mono_fac (hI.hom_ext (_ ≫ hT.from X) (hI.to T))) /-- To show a category is a `initial_mono_class` it suffices to show the unique morphism from the initial object to a terminal object is a monomorphism. -/ lemma initial_mono_class.of_terminal [has_initial C] [has_terminal C] (h : mono (initial.to (⊤_ C))) : initial_mono_class C := initial_mono_class.of_is_terminal initial_is_initial terminal_is_terminal h section comparison variables {D : Type u₂} [category.{v₂} D] (G : C ⥤ D) /-- The comparison morphism from the image of a terminal object to the terminal object in the target category. This is an isomorphism iff `G` preserves terminal objects, see `category_theory.limits.preserves_terminal.of_iso_comparison`. -/ def terminal_comparison [has_terminal C] [has_terminal D] : G.obj (⊤_ C) ⟶ ⊤_ D := terminal.from _ /-- The comparison morphism from the initial object in the target category to the image of the initial object. -/ -- TODO: Show this is an isomorphism if and only if `G` preserves initial objects. def initial_comparison [has_initial C] [has_initial D] : ⊥_ D ⟶ G.obj (⊥_ C) := initial.to _ end comparison variables {J : Type u} [category.{v} J] /-- From a functor `F : J ⥤ C`, given an initial object of `J`, construct a cone for `J`. In `limit_of_diagram_initial` we show it is a limit cone. -/ @[simps] def cone_of_diagram_initial {X : J} (tX : is_initial X) (F : J ⥤ C) : cone F := { X := F.obj X, π := { app := λ j, F.map (tX.to j), naturality' := λ j j' k, begin dsimp, rw [← F.map_comp, category.id_comp, tX.hom_ext (tX.to j ≫ k) (tX.to j')], end } } /-- From a functor `F : J ⥤ C`, given an initial object of `J`, show the cone `cone_of_diagram_initial` is a limit. -/ def limit_of_diagram_initial {X : J} (tX : is_initial X) (F : J ⥤ C) : is_limit (cone_of_diagram_initial tX F) := { lift := λ s, s.π.app X, uniq' := λ s m w, begin rw [← w X, cone_of_diagram_initial_π_app, tX.hom_ext (tX.to X) (𝟙 _)], dsimp, simp -- See note [dsimp, simp] end} -- This is reducible to allow usage of lemmas about `cone_point_unique_up_to_iso`. /-- For a functor `F : J ⥤ C`, if `J` has an initial object then the image of it is isomorphic to the limit of `F`. -/ @[reducible] def limit_of_initial (F : J ⥤ C) [has_initial J] [has_limit F] : limit F ≅ F.obj (⊥_ J) := is_limit.cone_point_unique_up_to_iso (limit.is_limit _) (limit_of_diagram_initial initial_is_initial F) /-- From a functor `F : J ⥤ C`, given a terminal object of `J`, construct a cone for `J`, provided that the morphisms in the diagram are isomorphisms. In `limit_of_diagram_terminal` we show it is a limit cone. -/ @[simps] def cone_of_diagram_terminal {X : J} (hX : is_terminal X) (F : J ⥤ C) [∀ (i j : J) (f : i ⟶ j), is_iso (F.map f)] : cone F := { X := F.obj X, π := { app := λ i, inv (F.map (hX.from _)), naturality' := begin intros i j f, dsimp, simp only [is_iso.eq_inv_comp, is_iso.comp_inv_eq, category.id_comp, ← F.map_comp, hX.hom_ext (hX.from i) (f ≫ hX.from j)], end } } /-- From a functor `F : J ⥤ C`, given a terminal object of `J` and that the morphisms in the diagram are isomorphisms, show the cone `cone_of_diagram_terminal` is a limit. -/ def limit_of_diagram_terminal {X : J} (hX : is_terminal X) (F : J ⥤ C) [∀ (i j : J) (f : i ⟶ j), is_iso (F.map f)] : is_limit (cone_of_diagram_terminal hX F) := { lift := λ S, S.π.app _ } -- This is reducible to allow usage of lemmas about `cone_point_unique_up_to_iso`. /-- For a functor `F : J ⥤ C`, if `J` has a terminal object and all the morphisms in the diagram are isomorphisms, then the image of the terminal object is isomorphic to the limit of `F`. -/ @[reducible] def limit_of_terminal (F : J ⥤ C) [has_terminal J] [has_limit F] [∀ (i j : J) (f : i ⟶ j), is_iso (F.map f)] : limit F ≅ F.obj (⊤_ J) := is_limit.cone_point_unique_up_to_iso (limit.is_limit _) (limit_of_diagram_terminal terminal_is_terminal F) /-- From a functor `F : J ⥤ C`, given a terminal object of `J`, construct a cocone for `J`. In `colimit_of_diagram_terminal` we show it is a colimit cocone. -/ @[simps] def cocone_of_diagram_terminal {X : J} (tX : is_terminal X) (F : J ⥤ C) : cocone F := { X := F.obj X, ι := { app := λ j, F.map (tX.from j), naturality' := λ j j' k, begin dsimp, rw [← F.map_comp, category.comp_id, tX.hom_ext (k ≫ tX.from j') (tX.from j)], end } } /-- From a functor `F : J ⥤ C`, given a terminal object of `J`, show the cocone `cocone_of_diagram_terminal` is a colimit. -/ def colimit_of_diagram_terminal {X : J} (tX : is_terminal X) (F : J ⥤ C) : is_colimit (cocone_of_diagram_terminal tX F) := { desc := λ s, s.ι.app X, uniq' := λ s m w, by { rw [← w X, cocone_of_diagram_terminal_ι_app, tX.hom_ext (tX.from X) (𝟙 _)], simp } } -- This is reducible to allow usage of lemmas about `cocone_point_unique_up_to_iso`. /-- For a functor `F : J ⥤ C`, if `J` has a terminal object then the image of it is isomorphic to the colimit of `F`. -/ @[reducible] def colimit_of_terminal (F : J ⥤ C) [has_terminal J] [has_colimit F] : colimit F ≅ F.obj (⊤_ J) := is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit _) (colimit_of_diagram_terminal terminal_is_terminal F) /-- From a functor `F : J ⥤ C`, given an initial object of `J`, construct a cocone for `J`, provided that the morphisms in the diagram are isomorphisms. In `colimit_of_diagram_initial` we show it is a colimit cocone. -/ @[simps] def cocone_of_diagram_initial {X : J} (hX : is_initial X) (F : J ⥤ C) [∀ (i j : J) (f : i ⟶ j), is_iso (F.map f)] : cocone F := { X := F.obj X, ι := { app := λ i, inv (F.map (hX.to _)), naturality' := begin intros i j f, dsimp, simp only [is_iso.eq_inv_comp, is_iso.comp_inv_eq, category.comp_id, ← F.map_comp, hX.hom_ext (hX.to i ≫ f) (hX.to j)], end } } /-- From a functor `F : J ⥤ C`, given an initial object of `J` and that the morphisms in the diagram are isomorphisms, show the cone `cocone_of_diagram_initial` is a colimit. -/ def colimit_of_diagram_initial {X : J} (hX : is_initial X) (F : J ⥤ C) [∀ (i j : J) (f : i ⟶ j), is_iso (F.map f)] : is_colimit (cocone_of_diagram_initial hX F) := { desc := λ S, S.ι.app _ } -- This is reducible to allow usage of lemmas about `cocone_point_unique_up_to_iso`. /-- For a functor `F : J ⥤ C`, if `J` has an initial object and all the morphisms in the diagram are isomorphisms, then the image of the initial object is isomorphic to the colimit of `F`. -/ @[reducible] def colimit_of_initial (F : J ⥤ C) [has_initial J] [has_colimit F] [∀ (i j : J) (f : i ⟶ j), is_iso (F.map f)] : colimit F ≅ F.obj (⊥_ J) := is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit _) (colimit_of_diagram_initial initial_is_initial _) /-- If `j` is initial in the index category, then the map `limit.π F j` is an isomorphism. -/ lemma is_iso_π_of_is_initial {j : J} (I : is_initial j) (F : J ⥤ C) [has_limit F] : is_iso (limit.π F j) := ⟨⟨limit.lift _ (cone_of_diagram_initial I F), ⟨by { ext, simp }, by simp⟩⟩⟩ instance is_iso_π_initial [has_initial J] (F : J ⥤ C) [has_limit F] : is_iso (limit.π F (⊥_ J)) := is_iso_π_of_is_initial (initial_is_initial) F lemma is_iso_π_of_is_terminal {j : J} (I : is_terminal j) (F : J ⥤ C) [has_limit F] [∀ (i j : J) (f : i ⟶ j), is_iso (F.map f)] : is_iso (limit.π F j) := ⟨⟨limit.lift _ (cone_of_diagram_terminal I F), by { ext, simp }, by simp ⟩⟩ instance is_iso_π_terminal [has_terminal J] (F : J ⥤ C) [has_limit F] [∀ (i j : J) (f : i ⟶ j), is_iso (F.map f)] : is_iso (limit.π F (⊤_ J)) := is_iso_π_of_is_terminal terminal_is_terminal F /-- If `j` is terminal in the index category, then the map `colimit.ι F j` is an isomorphism. -/ lemma is_iso_ι_of_is_terminal {j : J} (I : is_terminal j) (F : J ⥤ C) [has_colimit F] : is_iso (colimit.ι F j) := ⟨⟨colimit.desc _ (cocone_of_diagram_terminal I F), ⟨by simp, by { ext, simp }⟩⟩⟩ instance is_iso_ι_terminal [has_terminal J] (F : J ⥤ C) [has_colimit F] : is_iso (colimit.ι F (⊤_ J)) := is_iso_ι_of_is_terminal (terminal_is_terminal) F lemma is_iso_ι_of_is_initial {j : J} (I : is_initial j) (F : J ⥤ C) [has_colimit F] [∀ (i j : J) (f : i ⟶ j), is_iso (F.map f)] : is_iso (colimit.ι F j) := ⟨⟨colimit.desc _ (cocone_of_diagram_initial I F), ⟨by tidy, by { ext, simp }⟩⟩⟩ instance is_iso_ι_initial [has_initial J] (F : J ⥤ C) [has_colimit F] [∀ (i j : J) (f : i ⟶ j), is_iso (F.map f)] : is_iso (colimit.ι F (⊥_ J)) := is_iso_ι_of_is_initial initial_is_initial F end end category_theory.limits
085dbd2d82320a9783c79144875324b0a52011a5
618003631150032a5676f229d13a079ac875ff77
/src/tactic/core.lean
31be16763be627d6585837f99ac0ba74e051a344
[ "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
83,799
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek -/ import data.dlist.basic import control.basic import meta.expr import meta.rb_map import data.bool import tactic.lean_core_docs universe variable u instance : has_lt pos := { lt := λ x y, (x.line, x.column) < (y.line, y.column) } namespace expr open tactic /-- Given an expr `α` representing a type with numeral structure, `of_nat α n` creates the `α`-valued numeral expression corresponding to `n`. -/ protected meta def of_nat (α : expr) : ℕ → tactic expr := nat.binary_rec (tactic.mk_mapp ``has_zero.zero [some α, none]) (λ b n tac, if n = 0 then mk_mapp ``has_one.one [some α, none] else do e ← tac, tactic.mk_app (cond b ``bit1 ``bit0) [e]) /-- Given an expr `α` representing a type with numeral structure, `of_int α n` creates the `α`-valued numeral expression corresponding to `n`. The output is either a numeral or the negation of a numeral. -/ protected meta def of_int (α : expr) : ℤ → tactic expr | (n : ℕ) := expr.of_nat α n | -[1+ n] := do e ← expr.of_nat α (n+1), tactic.mk_app ``has_neg.neg [e] /-- Generates an expression of the form `∃(args), inner`. `args` is assumed to be a list of local constants. When possible, `p ∧ q` is used instead of `∃(_ : p), q`. -/ meta def mk_exists_lst (args : list expr) (inner : expr) : tactic expr := args.mfoldr (λarg i:expr, do t ← infer_type arg, sort l ← infer_type t, return $ if arg.occurs i ∨ l ≠ level.zero then (const `Exists [l] : expr) t (i.lambdas [arg]) else (const `and [] : expr) t i) inner /-- `traverse f e` applies the monadic function `f` to the direct descendants of `e`. -/ meta def traverse {m : Type → Type u} [applicative m] {elab elab' : bool} (f : expr elab → m (expr elab')) : expr elab → m (expr elab') | (var v) := pure $ var v | (sort l) := pure $ sort l | (const n ls) := pure $ const n ls | (mvar n n' e) := mvar n n' <$> f e | (local_const n n' bi e) := local_const n n' bi <$> f e | (app e₀ e₁) := app <$> f e₀ <*> f e₁ | (lam n bi e₀ e₁) := lam n bi <$> f e₀ <*> f e₁ | (pi n bi e₀ e₁) := pi n bi <$> f e₀ <*> f e₁ | (elet n e₀ e₁ e₂) := elet n <$> f e₀ <*> f e₁ <*> f e₂ | (macro mac es) := macro mac <$> list.traverse f es /-- `mfoldl f a e` folds the monadic function `f` over the subterms of the expression `e`, with initial value `a`. -/ meta def mfoldl {α : Type} {m} [monad m] (f : α → expr → m α) : α → expr → m α | x e := prod.snd <$> (state_t.run (e.traverse $ λ e', (get >>= monad_lift ∘ flip f e' >>= put) $> e') x : m _) end expr namespace interaction_monad open result variables {σ : Type} {α : Type u} /-- `get_state` returns the underlying state inside an interaction monad, from within that monad. -/ -- Note that this is a generalization of `tactic.read` in core. meta def get_state : interaction_monad σ σ := λ state, success state state /-- `set_state` sets the underlying state inside an interaction monad, from within that monad. -/ -- Note that this is a generalization of `tactic.write` in core. meta def set_state (state : σ) : interaction_monad σ unit := λ _, success () state /-- `run_with_state state tac` applies `tac` to the given state `state` and returns the result, subsequently restoring the original state. If `tac` fails, then `run_with_state` does too. -/ meta def run_with_state (state : σ) (tac : interaction_monad σ α) : interaction_monad σ α := λ s, match tac state with | success val _ := success val s | exception fn pos _ := exception fn pos s end end interaction_monad namespace format /-- `join' [a,b,c]` produces the format object `abc`. It differs from `format.join` by using `format.nil` instead of `""` for the empty list. -/ meta def join' (xs : list format) : format := xs.foldl compose nil /-- `intercalate x [a, b, c]` produces the format object `a.x.b.x.c`, where `.` represents `format.join`. -/ meta def intercalate (x : format) : list format → format := join' ∘ list.intersperse x /-- `soft_break` is similar to `line`. Whereas in `group (x ++ line ++ y ++ line ++ z)` the result either fits on one line or in three, `x ++ soft_break ++ y ++ soft_break ++ z` each line break is decided independently -/ meta def soft_break : format := group line end format section format open format /-- format a `list` by separating elements with `soft_break` instead of `line` -/ meta def list.to_line_wrap_format {α : Type u} [has_to_format α] : list α → format | [] := to_fmt "[]" | xs := to_fmt "[" ++ group (nest 1 $ intercalate ("," ++ soft_break) $ xs.map to_fmt) ++ to_fmt "]" end format namespace tactic open function /-- Private work function for `add_local_consts_as_local_hyps`: given `mappings : list (expr × expr)` corresponding to pairs `(var, hyp)` of variables and the local hypothesis created as a result and `(var :: rest) : list expr` of more local variables we examine `var` to see if it contains any other variables in `rest`. If it does, we put it to the back of the queue and recurse. If it does not, then we perform replacements inside the type of `var` using the `mappings`, create a new associate local hypothesis, add this to the list of mappings, and recurse. We are done once all local hypotheses have been processed. If the list of passed local constants have types which depend on one another (which can only happen by hand-crafting the `expr`s manually), this function will loop forever. -/ private meta def add_local_consts_as_local_hyps_aux : list (expr × expr) → list expr → tactic (list (expr × expr)) | mappings [] := return mappings | mappings (var :: rest) := do /- Determine if `var` contains any local variables in the lift `rest`. -/ let is_dependent := var.local_type.fold ff $ λ e n b, if b then b else e ∈ rest, /- If so, then skip it---add it to the end of the variable queue. -/ if is_dependent then add_local_consts_as_local_hyps_aux mappings (rest ++ [var]) else do /- Otherwise, replace all of the local constants referenced by the type of `var` with the respective new corresponding local hypotheses as recorded in the list `mappings`. -/ let new_type := var.local_type.replace_subexprs mappings, /- Introduce a new local new local hypothesis `hyp` for `var`, with the correct type. -/ hyp ← assertv var.local_pp_name new_type (var.local_const_set_type new_type), /- Process the next variable in the queue, with the mapping list updated to include the local hypothesis which we just created. -/ add_local_consts_as_local_hyps_aux ((var, hyp) :: mappings) rest /-- `add_local_consts_as_local_hyps vars` add the given list `vars` of `expr.local_const`s to the tactic state. This is harder than it sounds, since the list of local constants which we have been passed can have dependencies between their types. For example, suppose we have two local constants `n : ℕ` and `h : n = 3`. Then we cannot blindly add `h` as a local hypothesis, since we need the `n` to which it refers to be the `n` created as a new local hypothesis, not the old local constant `n` with the same name. Of course, these dependencies can be nested arbitrarily deep. If the list of passed local constants have types which depend on one another (which can only happen by hand-crafting the `expr`s manually), this function will loop forever. -/ meta def add_local_consts_as_local_hyps (vars : list expr) : tactic (list (expr × expr)) := /- The `list.reverse` below is a performance optimisation since the list of available variables reported by the system is often mostly the reverse of the order in which they are dependent. -/ add_local_consts_as_local_hyps_aux [] vars.reverse.erase_dup /-- `mk_local_pisn e n` instantiates the first `n` variables of a pi expression `e`, and returns the new local constants along with the instantiated expression. Fails if `e` does not begin with at least `n` pi binders. -/ meta def mk_local_pisn : expr → nat → tactic (list expr × expr) | (expr.pi n bi d b) (c + 1) := do p ← mk_local' n bi d, (ps, r) ← mk_local_pisn (b.instantiate_var p) c, return ((p :: ps), r) | e 0 := return ([], e) | _ _ := failed -- TODO: move to `declaration` namespace in `meta/expr.lean` /-- `mk_theorem n ls t e` creates a theorem declaration with name `n`, universe parameters named `ls`, type `t`, and body `e`. -/ meta def mk_theorem (n : name) (ls : list name) (t : expr) (e : expr) : declaration := declaration.thm n ls t (task.pure e) /-- `add_theorem_by n ls type tac` uses `tac` to synthesize a term with type `type`, and adds this to the environment as a theorem with name `n` and universe parameters `ls`. -/ meta def add_theorem_by (n : name) (ls : list name) (type : expr) (tac : tactic unit) : tactic expr := do ((), body) ← solve_aux type tac, body ← instantiate_mvars body, add_decl $ mk_theorem n ls type body, return $ expr.const n $ ls.map level.param /-- `eval_expr' α e` attempts to evaluate the expression `e` in the type `α`. This is a variant of `eval_expr` in core. Due to unexplained behavior in the VM, in rare situations the latter will fail but the former will succeed. -/ meta def eval_expr' (α : Type*) [_inst_1 : reflected α] (e : expr) : tactic α := mk_app ``id [e] >>= eval_expr α /-- `mk_fresh_name` returns identifiers starting with underscores, which are not legal when emitted by tactic programs. `mk_user_fresh_name` turns the useful source of random names provided by `mk_fresh_name` into names which are usable by tactic programs. The returned name has four components which are all strings. -/ meta def mk_user_fresh_name : tactic name := do nm ← mk_fresh_name, return $ `user__ ++ nm.pop_prefix.sanitize_name ++ `user__ /-- `has_attribute' attr_name decl_name` checks whether `decl_name` exists and has attribute `attr_name`. -/ meta def has_attribute' (attr_name decl_name : name) : tactic bool := succeeds (has_attribute attr_name decl_name) /-- Checks whether the name is a simp lemma -/ meta def is_simp_lemma : name → tactic bool := has_attribute' `simp /-- Checks whether the name is an instance. -/ meta def is_instance : name → tactic bool := has_attribute' `instance /-- `local_decls` returns a dictionary mapping names to their corresponding declarations. Covers all declarations from the current file. -/ meta def local_decls : tactic (name_map declaration) := do e ← tactic.get_env, let xs := e.fold native.mk_rb_map (λ d s, if environment.in_current_file' e d.to_name then s.insert d.to_name d else s), pure xs /-- If `{nm}_{n}` doesn't exist in the environment, returns that, otherwise tries `{nm}_{n+1}` -/ meta def get_unused_decl_name_aux (e : environment) (nm : name) : ℕ → tactic name | n := let nm' := nm.append_suffix ("_" ++ to_string n) in if e.contains nm' then get_unused_decl_name_aux (n+1) else return nm' /-- Return a name which doesn't already exist in the environment. If `nm` doesn't exist, it returns that, otherwise it tries `nm_2`, `nm_3`, ... -/ meta def get_unused_decl_name (nm : name) : tactic name := get_env >>= λ e, if e.contains nm then get_unused_decl_name_aux e nm 2 else return nm /-- Returns a pair `(e, t)`, where `e ← mk_const d.to_name`, and `t = d.type` but with universe params updated to match the fresh universe metavariables in `e`. This should have the same effect as just ```lean do e ← mk_const d.to_name, t ← infer_type e, return (e, t) ``` but is hopefully faster. -/ meta def decl_mk_const (d : declaration) : tactic (expr × expr) := do subst ← d.univ_params.mmap $ λ u, prod.mk u <$> mk_meta_univ, let e : expr := expr.const d.to_name (prod.snd <$> subst), return (e, d.type.instantiate_univ_params subst) /-- Replace every universe metavariable in an expression with a universe parameter. (This is useful when making new declarations.) -/ meta def replace_univ_metas_with_univ_params (e : expr) : tactic expr := do e.list_univ_meta_vars.enum.mmap (λ n, do let n' := (`u).append_suffix ("_" ++ to_string (n.1+1)), unify (expr.sort (level.mvar n.2)) (expr.sort (level.param n'))), instantiate_mvars e /-- `mk_local n` creates a dummy local variable with name `n`. The type of this local constant is a constant with name `n`, so it is very unlikely to be a meaningful expression. -/ meta def mk_local (n : name) : expr := expr.local_const n n binder_info.default (expr.const n []) /-- `pis loc_consts f` is used to create a pi expression whose body is `f`. `loc_consts` should be a list of local constants. The function will abstract these local constants from `f` and bind them with pi binders. For example, if `a, b` are local constants with types `Ta, Tb`, ``pis [a, b] `(f a b)`` will return the expression `Π (a : Ta) (b : Tb), f a b`. -/ meta def pis : list expr → expr → tactic expr | (e@(expr.local_const uniq pp info _) :: es) f := do t ← infer_type e, f' ← pis es f, pure $ expr.pi pp info t (expr.abstract_local f' uniq) | _ f := pure f /-- `lambdas loc_consts f` is used to create a lambda expression whose body is `f`. `loc_consts` should be a list of local constants. The function will abstract these local constants from `f` and bind them with lambda binders. For example, if `a, b` are local constants with types `Ta, Tb`, ``lambdas [a, b] `(f a b)`` will return the expression `λ (a : Ta) (b : Tb), f a b`. -/ meta def lambdas : list expr → expr → tactic expr | (e@(expr.local_const uniq pp info _) :: es) f := do t ← infer_type e, f' ← lambdas es f, pure $ expr.lam pp info t (expr.abstract_local f' uniq) | _ f := pure f /-- `mk_psigma [x,y,z]`, with `[x,y,z]` list of local constants of types `x : tx`, `y : ty x` and `z : tz x y`, creates an expression of sigma type: `⟨x,y,z⟩ : Σ' (x : tx) (y : ty x), tz x y`. -/ meta def mk_psigma : list expr → tactic expr | [] := mk_const ``punit | [x@(expr.local_const _ _ _ _)] := pure x | (x@(expr.local_const _ _ _ _) :: xs) := do y ← mk_psigma xs, α ← infer_type x, β ← infer_type y, t ← lambdas [x] β >>= instantiate_mvars, r ← mk_mapp ``psigma.mk [α,t], pure $ r x y | _ := fail "mk_psigma expects a list of local constants" /-- `elim_gen_prod n e _ ns` with `e` an expression of type `psigma _`, applies `cases` on `e` `n` times and uses `ns` to name the resulting variables. Returns a triple: list of new variables, remaining term and unused variable names. -/ meta def elim_gen_prod : nat → expr → list expr → list name → tactic (list expr × expr × list name) | 0 e hs ns := return (hs.reverse, e, ns) | (n + 1) e hs ns := do t ← infer_type e, if t.is_app_of `eq then return (hs.reverse, e, ns) else do [(_, [h, h'], _)] ← cases_core e (ns.take 1), elim_gen_prod n h' (h :: hs) (ns.drop 1) private meta def elim_gen_sum_aux : nat → expr → list expr → tactic (list expr × expr) | 0 e hs := return (hs, e) | (n + 1) e hs := do [(_, [h], _), (_, [h'], _)] ← induction e [], swap, elim_gen_sum_aux n h' (h::hs) /-- `elim_gen_sum n e` applies cases on `e` `n` times. `e` is assumed to be a local constant whose type is a (nested) sum `⊕`. Returns the list of local constants representing the components of `e`. -/ meta def elim_gen_sum (n : nat) (e : expr) : tactic (list expr) := do (hs, h') ← elim_gen_sum_aux n e [], gs ← get_goals, set_goals $ (gs.take (n+1)).reverse ++ gs.drop (n+1), return $ hs.reverse ++ [h'] /-- Given `elab_def`, a tactic to solve the current goal, `extract_def n trusted elab_def` will create an auxiliary definition named `n` and use it to close the goal. If `trusted` is false, it will be a meta definition. -/ meta def extract_def (n : name) (trusted : bool) (elab_def : tactic unit) : tactic unit := do cxt ← list.map expr.to_implicit_local_const <$> local_context, t ← target, (eqns,d) ← solve_aux t elab_def, d ← instantiate_mvars d, t' ← pis cxt t, d' ← lambdas cxt d, let univ := t'.collect_univ_params, add_decl $ declaration.defn n univ t' d' (reducibility_hints.regular 1 tt) trusted, applyc n /-- Attempts to close the goal with `dec_trivial`. -/ meta def exact_dec_trivial : tactic unit := `[exact dec_trivial] /-- Runs a tactic for a result, reverting the state after completion. -/ meta def retrieve {α} (tac : tactic α) : tactic α := λ s, result.cases_on (tac s) (λ a s', result.success a s) result.exception /-- Repeat a tactic at least once, calling it recursively on all subgoals, until it fails. This tactic fails if the first invocation fails. -/ meta def repeat1 (t : tactic unit) : tactic unit := t; repeat t /-- `iterate_range m n t`: Repeat the given tactic at least `m` times and at most `n` times or until `t` fails. Fails if `t` does not run at least `m` times. -/ meta def iterate_range : ℕ → ℕ → tactic unit → tactic unit | 0 0 t := skip | 0 (n+1) t := try (t >> iterate_range 0 n t) | (m+1) n t := t >> iterate_range m (n-1) t /-- Given a tactic `tac` that takes an expression and returns a new expression and a proof of equality, use that tactic to change the type of the hypotheses listed in `hs`, as well as the goal if `tgt = tt`. Returns `tt` if any types were successfully changed. -/ meta def replace_at (tac : expr → tactic (expr × expr)) (hs : list expr) (tgt : bool) : tactic bool := do to_remove ← hs.mfilter $ λ h, do { h_type ← infer_type h, succeeds $ do (new_h_type, pr) ← tac h_type, assert h.local_pp_name new_h_type, mk_eq_mp pr h >>= tactic.exact }, goal_simplified ← succeeds $ do { guard tgt, (new_t, pr) ← target >>= tac, replace_target new_t pr }, to_remove.mmap' (λ h, try (clear h)), return (¬ to_remove.empty ∨ goal_simplified) /-- `revert_after e` reverts all local constants after local constant `e`. -/ meta def revert_after (e : expr) : tactic ℕ := do l ← local_context, [pos] ← return $ l.indexes_of e | pp e >>= λ s, fail format!"No such local constant {s}", let l := l.drop pos.succ, -- all local hypotheses after `e` revert_lst l /-- `generalize' e n` generalizes the target with respect to `e`. It creates a new local constant with name `n` of the same type as `e` and replaces all occurrences of `e` by `n`. `generalize'` is similar to `generalize` but also succeeds when `e` does not occur in the goal, in which case it just calls `assert`. In contrast to `generalize` it already introduces the generalized variable. -/ meta def generalize' (e : expr) (n : name) : tactic expr := (generalize e n >> intro1) <|> note n none e /-! ### Various tactics related to local definitions (local constants of the form `x : α := t`) We call `t` the value of `x`. -/ /-- `local_def_value e` returns the value of the expression `e`, assuming that `e` has been defined locally using a `let` expression. Otherwise it fails. -/ meta def local_def_value (e : expr) : tactic expr := pp e >>= λ s, -- running `pp` here, because we cannot access it in the `type_context` monad. tactic.unsafe.type_context.run $ do lctx <- tactic.unsafe.type_context.get_local_context, some ldecl <- return $ lctx.get_local_decl e.local_uniq_name | tactic.unsafe.type_context.fail format!"No such hypothesis {s}.", some let_val <- return ldecl.value | tactic.unsafe.type_context.fail format!"Variable {e} is not a local definition.", return let_val /-- `revert_deps e` reverts all the hypotheses that depend on one of the local constants `e`, including the local definitions that have `e` in their definition. This fixes a bug in `revert_kdeps` that does not revert local definitions for which `e` only appears in the definition. -/ /- We cannot implement it as `revert e >> intro1`, because that would change the local constant in the context. -/ meta def revert_deps (e : expr) : tactic ℕ := do n ← revert_kdeps e, l ← local_context, [pos] ← return $ l.indexes_of e, let l := l.drop pos.succ, -- local hypotheses after `e` ls ← l.mfilter $ λ e', try_core (local_def_value e') >>= λ o, return $ o.elim ff $ λ e'', e''.has_local_constant e, n' ← revert_lst ls, return $ n + n' /-- `is_local_def e` succeeds when `e` is a local definition (a local constant of the form `e : α := t`) and otherwise fails. -/ meta def is_local_def (e : expr) : tactic unit := retrieve $ do revert e, expr.elet _ _ _ _ ← target, skip /-- `clear_value e` clears the body of the local definition `e`, changing it into a regular hypothesis. A hypothesis `e : α := t` is changed to `e : α`. This tactic is called `clearbody` in Coq. -/ meta def clear_value (e : expr) : tactic unit := do n ← revert_after e, is_local_def e <|> pp e >>= λ s, fail format!"Cannot clear the body of {s}. It is not a local definition.", let nm := e.local_pp_name, (generalize' e nm >> clear e) <|> fail format!"Cannot clear the body of {nm}. The resulting goal is not type correct.", intron n /-- A variant of `simplify_bottom_up`. Given a tactic `post` for rewriting subexpressions, `simp_bottom_up post e` tries to rewrite `e` starting at the leaf nodes. Returns the resulting expression and a proof of equality. -/ meta def simp_bottom_up' (post : expr → tactic (expr × expr)) (e : expr) (cfg : simp_config := {}) : tactic (expr × expr) := prod.snd <$> simplify_bottom_up () (λ _, (<$>) (prod.mk ()) ∘ post) e cfg /-- Caches unary type classes on a type `α : Type.{univ}`. -/ meta structure instance_cache := (α : expr) (univ : level) (inst : name_map expr) /-- Creates an `instance_cache` for the type `α`. -/ meta def mk_instance_cache (α : expr) : tactic instance_cache := do u ← mk_meta_univ, infer_type α >>= unify (expr.sort (level.succ u)), u ← get_univ_assignment u, return ⟨α, u, mk_name_map⟩ namespace instance_cache /-- If `n` is the name of a type class with one parameter, `get c n` tries to find an instance of `n c.α` by checking the cache `c`. If there is no entry in the cache, it tries to find the instance via type class resolution, and updates the cache. -/ meta def get (c : instance_cache) (n : name) : tactic (instance_cache × expr) := match c.inst.find n with | some i := return (c, i) | none := do e ← mk_app n [c.α] >>= mk_instance, return (⟨c.α, c.univ, c.inst.insert n e⟩, e) end open expr /-- If `e` is a `pi` expression that binds an instance-implicit variable of type `n`, `append_typeclasses e c l` searches `c` for an instance `p` of type `n` and returns `p :: l`. -/ meta def append_typeclasses : expr → instance_cache → list expr → tactic (instance_cache × list expr) | (pi _ binder_info.inst_implicit (app (const n _) (var _)) body) c l := do (c, p) ← c.get n, return (c, p :: l) | _ c l := return (c, l) /-- Creates the application `n c.α p l`, where `p` is a type class instance found in the cache `c`. -/ meta def mk_app (c : instance_cache) (n : name) (l : list expr) : tactic (instance_cache × expr) := do d ← get_decl n, (c, l) ← append_typeclasses d.type.binding_body c l, return (c, (expr.const n [c.univ]).mk_app (c.α :: l)) /-- `c.of_nat n` creates the `c.α`-valued numeral expression corresponding to `n`. -/ protected meta def of_nat (c : instance_cache) (n : ℕ) : tactic (instance_cache × expr) := if n = 0 then c.mk_app ``has_zero.zero [] else do (c, ai) ← c.get ``has_add, (c, oi) ← c.get ``has_one, (c, one) ← c.mk_app ``has_one.one [], return (c, n.binary_rec one $ λ b n e, if n = 0 then one else cond b ((expr.const ``bit1 [c.univ]).mk_app [c.α, oi, ai, e]) ((expr.const ``bit0 [c.univ]).mk_app [c.α, ai, e])) /-- `c.of_int n` creates the `c.α`-valued numeral expression corresponding to `n`. The output is either a numeral or the negation of a numeral. -/ protected meta def of_int (c : instance_cache) : ℤ → tactic (instance_cache × expr) | (n : ℕ) := c.of_nat n | -[1+ n] := do (c, e) ← c.of_nat (n+1), c.mk_app ``has_neg.neg [e] end instance_cache private meta def get_expl_pi_arity_aux : expr → tactic nat | (expr.pi n bi d b) := do m ← mk_fresh_name, let l := expr.local_const m n bi d, new_b ← whnf (expr.instantiate_var b l), r ← get_expl_pi_arity_aux new_b, if bi = binder_info.default then return (r + 1) else return r | e := return 0 /-- Compute the arity of explicit arguments of the given (Pi-)type. -/ meta def get_expl_pi_arity (type : expr) : tactic nat := whnf type >>= get_expl_pi_arity_aux /-- Compute the arity of explicit arguments of the given function. -/ meta def get_expl_arity (fn : expr) : tactic nat := infer_type fn >>= get_expl_pi_arity /-- Auxilliary defintion for `get_pi_binders`. -/ meta def get_pi_binders_aux : list binder → expr → tactic (list binder × expr) | es (expr.pi n bi d b) := do m ← mk_fresh_name, let l := expr.local_const m n bi d, let new_b := expr.instantiate_var b l, get_pi_binders_aux (⟨n, bi, d⟩::es) new_b | es e := return (es, e) /-- Get the binders and target of a pi-type. Instantiates bound variables by local constants. Cf. `pi_binders` in `meta.expr` (which produces open terms). See also `mk_local_pis` in `init.core.tactic` which does almost the same. -/ meta def get_pi_binders : expr → tactic (list binder × expr) | e := do (es, e) ← get_pi_binders_aux [] e, return (es.reverse, e) /-- Auxilliary definition for `get_pi_binders_dep`. -/ meta def get_pi_binders_dep_aux : ℕ → expr → tactic (list (ℕ × binder) × expr) | n (expr.pi nm bi d b) := do l ← mk_local' nm bi d, (ls, r) ← get_pi_binders_dep_aux (n+1) (expr.instantiate_var b l), return (if b.has_var then ls else (n, ⟨nm, bi, d⟩)::ls, r) | n e := return ([], e) /-- A variant of `get_pi_binders` that only returns the binders that do not occur in later arguments or in the target. Also returns the argument position of each returned binder. -/ meta def get_pi_binders_dep : expr → tactic (list (ℕ × binder) × expr) := get_pi_binders_dep_aux 0 /-- A variation on `assert` where a (possibly incomplete) proof of the assertion is provided as a parameter. ``(h,gs) ← local_proof `h p tac`` creates a local `h : p` and use `tac` to (partially) construct a proof for it. `gs` is the list of remaining goals in the proof of `h`. The benefits over assert are: - unlike with ``h ← assert `h p, tac`` , `h` cannot be used by `tac`; - when `tac` does not complete the proof of `h`, returning the list of goals allows one to write a tactic using `h` and with the confidence that a proof will not boil over to goals left over from the proof of `h`, unlike what would be the case when using `tactic.swap`. -/ meta def local_proof (h : name) (p : expr) (tac₀ : tactic unit) : tactic (expr × list expr) := focus1 $ do h' ← assert h p, [g₀,g₁] ← get_goals, set_goals [g₀], tac₀, gs ← get_goals, set_goals [g₁], return (h', gs) /-- `var_names e` returns a list of the unique names of the initial pi bindings in `e`. -/ meta def var_names : expr → list name | (expr.pi n _ _ b) := n :: var_names b | _ := [] /-- When `struct_n` is the name of a structure type, `subobject_names struct_n` returns two lists of names `(instances, fields)`. The names in `instances` are the projections from `struct_n` to the structures that it extends (assuming it was defined with `old_structure_cmd false`). The names in `fields` are the standard fields of `struct_n`. -/ meta def subobject_names (struct_n : name) : tactic (list name × list name) := do env ← get_env, [c] ← pure $ env.constructors_of struct_n | fail "too many constructors", vs ← var_names <$> (mk_const c >>= infer_type), fields ← env.structure_fields struct_n, return $ fields.partition (λ fn, ↑("_" ++ fn.to_string) ∈ vs) private meta def expanded_field_list' : name → tactic (dlist $ name × name) | struct_n := do (so,fs) ← subobject_names struct_n, ts ← so.mmap (λ n, do (_, e) ← mk_const (n.update_prefix struct_n) >>= infer_type >>= mk_local_pis, expanded_field_list' $ e.get_app_fn.const_name), return $ dlist.join ts ++ dlist.of_list (fs.map $ prod.mk struct_n) open functor function /-- `expanded_field_list struct_n` produces a list of the names of the fields of the structure named `struct_n`. These are returned as pairs of names `(prefix, name)`, where the full name of the projection is `prefix.name`. -/ meta def expanded_field_list (struct_n : name) : tactic (list $ name × name) := dlist.to_list <$> expanded_field_list' struct_n /-- Return a list of all type classes which can be instantiated for the given expression. -/ meta def get_classes (e : expr) : tactic (list name) := attribute.get_instances `class >>= list.mfilter (λ n, succeeds $ mk_app n [e] >>= mk_instance) open nat /-- Create a list of `n` fresh metavariables. -/ meta def mk_mvar_list : ℕ → tactic (list expr) | 0 := pure [] | (succ n) := (::) <$> mk_mvar <*> mk_mvar_list n /-- Returns the only goal, or fails if there isn't just one goal. -/ meta def get_goal : tactic expr := do gs ← get_goals, match gs with | [a] := return a | [] := fail "there are no goals" | _ := fail "there are too many goals" end /-- `iterate_at_most_on_all_goals n t`: repeat the given tactic at most `n` times on all goals, or until it fails. Always succeeds. -/ meta def iterate_at_most_on_all_goals : nat → tactic unit → tactic unit | 0 tac := trace "maximal iterations reached" | (succ n) tac := tactic.all_goals' $ (do tac, iterate_at_most_on_all_goals n tac) <|> skip /-- `iterate_at_most_on_subgoals n t`: repeat the tactic `t` at most `n` times on the first goal and on all subgoals thus produced, or until it fails. Fails iff `t` fails on current goal. -/ meta def iterate_at_most_on_subgoals : nat → tactic unit → tactic unit | 0 tac := trace "maximal iterations reached" | (succ n) tac := focus1 (do tac, iterate_at_most_on_all_goals n tac) /-- `apply_list l`: try to apply the tactics in the list `l` on the first goal, and fail if none succeeds -/ meta def apply_list_expr : list expr → tactic unit | [] := fail "no matching rule" | (h::t) := do interactive.concat_tags (apply h) <|> apply_list_expr t /-- constructs a list of expressions given a list of p-expressions, as follows: - if the p-expression is the name of a theorem, use `i_to_expr_for_apply` on it - if the p-expression is a user attribute, add all the theorems with this attribute to the list.-/ meta def build_list_expr_for_apply : list pexpr → tactic (list expr) | [] := return [] | (h::t) := do tail ← build_list_expr_for_apply t, a ← i_to_expr_for_apply h, (do l ← attribute.get_instances (expr.const_name a), m ← list.mmap mk_const l, return (m.append tail)) <|> return (a::tail) /--`apply_rules hs n`: apply the list of rules `hs` (given as pexpr) and `assumption` on the first goal and the resulting subgoals, iteratively, at most `n` times. Unlike `solve_by_elim`, `apply_rules` does not do any backtracking, and just greedily applies a lemma from the list until it can't. -/ meta def apply_rules (hs : list pexpr) (n : nat) : tactic unit := do l ← build_list_expr_for_apply hs, iterate_at_most_on_subgoals n (assumption <|> apply_list_expr l) /-- `replace h p` elaborates the pexpr `p`, clears the existing hypothesis named `h` from the local context, and adds a new hypothesis named `h`. The type of this hypothesis is the type of `p`. Fails if there is nothing named `h` in the local context. -/ meta def replace (h : name) (p : pexpr) : tactic unit := do h' ← get_local h, p ← to_expr p, note h none p, clear h' /-- Auxiliary function for `iff_mp` and `iff_mpr`. Takes a name, which should be either `` `iff.mp`` or `` `iff.mpr``. If the passed expression is an iterated function type eventually producing an `iff`, returns an expression with the `iff` converted to either the forwards or backwards implication, as requested. -/ meta def mk_iff_mp_app (iffmp : name) : expr → (nat → expr) → option expr | (expr.pi n bi e t) f := expr.lam n bi e <$> mk_iff_mp_app t (λ n, f (n+1) (expr.var n)) | `(%%a ↔ %%b) f := some $ @expr.const tt iffmp [] a b (f 0) | _ f := none /-- `iff_mp_core e ty` assumes that `ty` is the type of `e`. If `ty` has the shape `Π ..., A ↔ B`, returns an expression whose type is `Π ..., A → B`. -/ meta def iff_mp_core (e ty: expr) : option expr := mk_iff_mp_app `iff.mp ty (λ_, e) /-- `iff_mpr_core e ty` assumes that `ty` is the type of `e`. If `ty` has the shape `Π ..., A ↔ B`, returns an expression whose type is `Π ..., B → A`. -/ meta def iff_mpr_core (e ty: expr) : option expr := mk_iff_mp_app `iff.mpr ty (λ_, e) /-- Given an expression whose type is (a possibly iterated function producing) an `iff`, create the expression which is the forward implication. -/ meta def iff_mp (e : expr) : tactic expr := do t ← infer_type e, iff_mp_core e t <|> fail "Target theorem must have the form `Π x y z, a ↔ b`" /-- Given an expression whose type is (a possibly iterated function producing) an `iff`, create the expression which is the reverse implication. -/ meta def iff_mpr (e : expr) : tactic expr := do t ← infer_type e, iff_mpr_core e t <|> fail "Target theorem must have the form `Π x y z, a ↔ b`" /-- Attempts to apply `e`, and if that fails, if `e` is an `iff`, try applying both directions separately. -/ meta def apply_iff (e : expr) : tactic (list (name × expr)) := let ap e := tactic.apply e {new_goals := new_goals.non_dep_only} in ap e <|> (iff_mp e >>= ap) <|> (iff_mpr e >>= ap) /-- Configuration options for `apply_any`: * `use_symmetry`: if `apply_any` fails to apply any lemma, call `symmetry` and try again. * `use_exfalso`: if `apply_any` fails to apply any lemma, call `exfalso` and try again. * `apply`: specify an alternative to `tactic.apply`; usually `apply := tactic.eapply`. -/ meta structure apply_any_opt := (use_symmetry : bool := tt) (use_exfalso : bool := tt) (apply : expr → tactic (list (name × expr)) := tactic.apply) /-- This is a version of `apply_any` that takes a list of `tactic expr`s instead of `expr`s, and evaluates these as thunks before trying to apply them. We need to do this to avoid metavariables getting stuck during subsequent rounds of `apply`. -/ meta def apply_any_thunk (lemmas : list (tactic expr)) (opt : apply_any_opt := {}) (tac : tactic unit := skip) : tactic unit := do let modes := [skip] ++ (if opt.use_symmetry then [symmetry] else []) ++ (if opt.use_exfalso then [exfalso] else []), modes.any_of (λ m, do m, lemmas.any_of (λ H, H >>= opt.apply >> tac)) <|> fail "apply_any tactic failed; no lemma could be applied" /-- `apply_any lemmas` tries to apply one of the list `lemmas` to the current goal. `apply_any lemmas opt` allows control over how lemmas are applied. `opt` has fields: * `use_symmetry`: if no lemma applies, call `symmetry` and try again. (Defaults to `tt`.) * `use_exfalso`: if no lemma applies, call `exfalso` and try again. (Defaults to `tt`.) * `apply`: use a tactic other than `tactic.apply` (e.g. `tactic.fapply` or `tactic.eapply`). `apply_any lemmas tac` calls the tactic `tac` after a successful application. Defaults to `skip`. This is used, for example, by `solve_by_elim` to arrange recursive invocations of `apply_any`. -/ meta def apply_any (lemmas : list expr) (opt : apply_any_opt := {}) (tac : tactic unit := skip) : tactic unit := apply_any_thunk (lemmas.map pure) opt tac /-- Try to apply a hypothesis from the local context to the goal. -/ meta def apply_assumption : tactic unit := local_context >>= apply_any /-- `change_core e none` is equivalent to `change e`. It tries to change the goal to `e` and fails if this is not a definitional equality. `change_core e (some h)` assumes `h` is a local constant, and tries to change the type of `h` to `e` by reverting `h`, changing the goal, and reintroducing hypotheses. -/ meta def change_core (e : expr) : option expr → tactic unit | none := tactic.change e | (some h) := do num_reverted : ℕ ← revert h, expr.pi n bi d b ← target, tactic.change $ expr.pi n bi e b, intron num_reverted /-- `change_with_at olde newe hyp` replaces occurences of `olde` with `newe` at hypothesis `hyp`, assuming `olde` and `newe` are defeq when elaborated. -/ meta def change_with_at (olde newe : pexpr) (hyp : name) : tactic unit := do h ← get_local hyp, tp ← infer_type h, olde ← to_expr olde, newe ← to_expr newe, let repl_tp := tp.replace (λ a n, if a = olde then some newe else none), change_core repl_tp (some h) /-- Returns a list of all metavariables in the current partial proof. This can differ from the list of goals, since the goals can be manually edited. -/ meta def metavariables : tactic (list expr) := expr.list_meta_vars <$> result /-- Fail if the target contains a metavariable. -/ meta def no_mvars_in_target : tactic unit := expr.has_meta_var <$> target >>= guardb ∘ bnot /-- Succeeds only if the current goal is a proposition. -/ meta def propositional_goal : tactic unit := do g :: _ ← get_goals, is_proof g >>= guardb /-- Succeeds only if we can construct an instance showing the current goal is a subsingleton type. -/ meta def subsingleton_goal : tactic unit := do g :: _ ← get_goals, ty ← infer_type g >>= instantiate_mvars, to_expr ``(subsingleton %%ty) >>= mk_instance >> skip /-- Succeeds only if the current goal is "terminal", in the sense that no other goals depend on it (except possibly through shared metavariables; see `independent_goal`). -/ meta def terminal_goal : tactic unit := propositional_goal <|> subsingleton_goal <|> do g₀ :: _ ← get_goals, mvars ← (λ L, list.erase L g₀) <$> metavariables, mvars.mmap' $ λ g, do t ← infer_type g >>= instantiate_mvars, d ← kdepends_on t g₀, monad.whenb d $ pp t >>= λ s, fail ("The current goal is not terminal: " ++ s.to_string ++ " depends on it.") /-- Succeeds only if the current goal is "independent", in the sense that no other goals depend on it, even through shared meta-variables. -/ meta def independent_goal : tactic unit := no_mvars_in_target >> terminal_goal /-- `triv'` tries to close the first goal with the proof `trivial : true`. Unlike `triv`, it only unfolds reducible definitions, so it sometimes fails faster. -/ meta def triv' : tactic unit := do c ← mk_const `trivial, exact c reducible variable {α : Type} /-- Apply a tactic as many times as possible, collecting the results in a list. Fail if the tactic does not succeed at least once. -/ meta def iterate1 (t : tactic α) : tactic (list α) := do r ← decorate_ex "iterate1 failed: tactic did not succeed" t, L ← iterate t, return (r :: L) /-- Introduces one or more variables and returns the new local constants. Fails if `intro` cannot be applied. -/ meta def intros1 : tactic (list expr) := iterate1 intro1 /-- Run a tactic "under binders", by running `intros` before, and `revert` afterwards. -/ meta def under_binders {α : Type} (t : tactic α) : tactic α := do v ← intros, r ← t, revert_lst v, return r namespace interactive /-- Run a tactic "under binders", by running `intros` before, and `revert` afterwards. -/ meta def under_binders (i : itactic) : itactic := tactic.under_binders i end interactive /-- `successes` invokes each tactic in turn, returning the list of successful results. -/ meta def successes (tactics : list (tactic α)) : tactic (list α) := list.filter_map id <$> monad.sequence (tactics.map (λ t, try_core t)) /-- Try all the tactics in a list, each time starting at the original `tactic_state`, returning the list of successful results, and reverting to the original `tactic_state`. -/ -- Note this is not the same as `successes`, which keeps track of the evolving `tactic_state`. meta def try_all {α : Type} (tactics : list (tactic α)) : tactic (list α) := λ s, result.success (tactics.map $ λ t : tactic α, match t s with | result.success a s' := [a] | _ := [] end).join s /-- Try all the tactics in a list, each time starting at the original `tactic_state`, returning the list of successful results sorted by the value produced by a subsequent execution of the `sort_by` tactic, and reverting to the original `tactic_state`. -/ meta def try_all_sorted {α : Type} (tactics : list (tactic α)) (sort_by : tactic ℕ := num_goals) : tactic (list (α × ℕ)) := λ s, result.success ((tactics.map $ λ t : tactic α, match (do a ← t, n ← sort_by, return (a, n)) s with | result.success a s' := [a] | _ := [] end).join.qsort (λ p q : α × ℕ, p.2 < q.2)) s /-- Return target after instantiating metavars and whnf. -/ private meta def target' : tactic expr := target >>= instantiate_mvars >>= whnf /-- Just like `split`, `fsplit` applies the constructor when the type of the target is an inductive data type with one constructor. However it does not reorder goals or invoke `auto_param` tactics. -/ -- FIXME check if we can remove `auto_param := ff` meta def fsplit : tactic unit := do [c] ← target' >>= get_constructors_for | fail "fsplit tactic failed, target is not an inductive datatype with only one constructor", mk_const c >>= λ e, apply e {new_goals := new_goals.all, auto_param := ff} >> skip run_cmd add_interactive [`fsplit] add_tactic_doc { name := "fsplit", category := doc_category.tactic, decl_names := [`tactic.interactive.fsplit], tags := ["logic", "goal management"] } /-- Calls `injection` on each hypothesis, and then, for each hypothesis on which `injection` succeeds, clears the old hypothesis. -/ meta def injections_and_clear : tactic unit := do l ← local_context, results ← successes $ l.map $ λ e, injection e >> clear e, when (results.empty) (fail "could not use `injection` then `clear` on any hypothesis") run_cmd add_interactive [`injections_and_clear] add_tactic_doc { name := "injections_and_clear", category := doc_category.tactic, decl_names := [`tactic.interactive.injections_and_clear], tags := ["context management"] } /-- Calls `cases` on every local hypothesis, succeeding if it succeeds on at least one hypothesis. -/ meta def case_bash : tactic unit := do l ← local_context, r ← successes (l.reverse.map (λ h, cases h >> skip)), when (r.empty) failed /-- `note_anon t v`, given a proof `v : t`, adds `h : t` to the current context, where the name `h` is fresh. `note_anon none v` will infer the type `t` from `v`. -/ -- While `note` provides a default value for `t`, it doesn't seem this could ever be used. meta def note_anon (t : option expr) (v : expr) : tactic expr := do h ← get_unused_name `h none, note h t v /-- `find_local t` returns a local constant with type t, or fails if none exists. -/ meta def find_local (t : pexpr) : tactic expr := do t' ← to_expr t, (prod.snd <$> solve_aux t' assumption >>= instantiate_mvars) <|> fail format!"No hypothesis found of the form: {t'}" /-- `dependent_pose_core l`: introduce dependent hypotheses, where the proofs depend on the values of the previous local constants. `l` is a list of local constants and their values. -/ meta def dependent_pose_core (l : list (expr × expr)) : tactic unit := do let lc := l.map prod.fst, let lm := l.map (λ⟨l, v⟩, (l.local_uniq_name, v)), t ← target, new_goal ← mk_meta_var (t.pis lc), old::other_goals ← get_goals, set_goals (old :: new_goal :: other_goals), exact ((new_goal.mk_app lc).instantiate_locals lm), return () /-- Like `mk_local_pis` but translating into weak head normal form before checking if it is a `Π`. -/ meta def mk_local_pis_whnf : expr → tactic (list expr × expr) | e := do (expr.pi n bi d b) ← whnf e | return ([], e), p ← mk_local' n bi d, (ps, r) ← mk_local_pis (expr.instantiate_var b p), return ((p :: ps), r) /-- Changes `(h : ∀xs, ∃a:α, p a) ⊢ g` to `(d : ∀xs, a) (s : ∀xs, p (d xs) ⊢ g`. -/ meta def choose1 (h : expr) (data : name) (spec : name) : tactic expr := do t ← infer_type h, (ctxt, t) ← mk_local_pis_whnf t, `(@Exists %%α %%p) ← whnf t transparency.all | fail "expected a term of the shape ∀xs, ∃a, p xs a", α_t ← infer_type α, expr.sort u ← whnf α_t transparency.all, value ← mk_local_def data (α.pis ctxt), t' ← head_beta (p.app (value.mk_app ctxt)), spec ← mk_local_def spec (t'.pis ctxt), dependent_pose_core [ (value, ((((expr.const `classical.some [u]).app α).app p).app (h.mk_app ctxt)).lambdas ctxt), (spec, ((((expr.const `classical.some_spec [u]).app α).app p).app (h.mk_app ctxt)).lambdas ctxt)], try (tactic.clear h), intro1, intro1 /-- Changes `(h : ∀xs, ∃as, p as) ⊢ g` to a list of functions `as`, and a final hypothesis on `p as`. -/ meta def choose : expr → list name → tactic unit | h [] := fail "expect list of variables" | h [n] := do cnt ← revert h, intro n, intron (cnt - 1), return () | h (n::ns) := do v ← get_unused_name >>= choose1 h n, choose v ns /-- Instantiates metavariables that appear in the current goal. -/ meta def instantiate_mvars_in_target : tactic unit := target >>= instantiate_mvars >>= change /-- Instantiates metavariables in all goals. -/ meta def instantiate_mvars_in_goals : tactic unit := all_goals' $ instantiate_mvars_in_target /-- This makes sure that the execution of the tactic does not change the tactic state. This can be helpful while using rewrite, apply, or expr munging. Remember to instantiate your metavariables before you're done! -/ meta def lock_tactic_state {α} (t : tactic α) : tactic α | s := match t s with | result.success a s' := result.success a s | result.exception msg pos s' := result.exception msg pos s end /-- Similar to `mk_local_pis` but make meta variables instead of local constants. -/ meta def mk_meta_pis : expr → tactic (list expr × expr) | (expr.pi n bi d b) := do p ← mk_meta_var d, (ps, r) ← mk_meta_pis (expr.instantiate_var b p), return ((p :: ps), r) | e := return ([], e) /-- Protect the declaration `n` -/ meta def mk_protected (n : name) : tactic unit := do env ← get_env, set_env (env.mk_protected n) end tactic namespace lean.parser open tactic interaction_monad /-- `emit_command_here str` behaves as if the string `str` were placed as a user command at the current line. -/ meta def emit_command_here (str : string) : lean.parser string := do (_, left) ← with_input command_like str, return left /-- `emit_code_here str` behaves as if the string `str` were placed at the current location in source code. -/ meta def emit_code_here : string → lean.parser unit | str := do left ← emit_command_here str, if left.length = 0 then return () else emit_code_here left /-- `get_current_namespace` returns the current namespace (it could be `name.anonymous`). This function deserves a C++ implementation in core lean, and will fail if it is not called from the body of a command (i.e. anywhere else that the `lean.parser` monad can be invoked). -/ meta def get_current_namespace : lean.parser name := do n ← tactic.mk_user_fresh_name, emit_code_here $ sformat!"def {n} := ()", nfull ← tactic.resolve_constant n, return $ nfull.get_nth_prefix n.components.length /-- `get_variables` returns a list of existing variable names, along with their types and binder info. -/ meta def get_variables : lean.parser (list (name × binder_info × expr)) := list.map expr.get_local_const_kind <$> list_available_include_vars /-- `get_included_variables` returns those variables `v` returned by `get_variables` which have been "included" by an `include v` statement and are not (yet) `omit`ed. -/ meta def get_included_variables : lean.parser (list (name × binder_info × expr)) := do ns ← list_include_var_names, list.filter (λ v, v.1 ∈ ns) <$> get_variables /-- From the `lean.parser` monad, synthesize a `tactic_state` which includes all of the local variables referenced in `es : list pexpr`, and those variables which have been `include`ed in the local context---precisely those variables which would be ambiently accessible if we were in a tactic-mode block where the goals had types `es.mmap to_expr`, for example. Returns a new `ts : tactic_state` with these local variables added, and `mappings : list (expr × expr)`, for which pairs `(var, hyp)` correspond to an existing variable `var` and the local hypothesis `hyp` which was added to the tactic state `ts` as a result. -/ meta def synthesize_tactic_state_with_variables_as_hyps (es : list pexpr) : lean.parser (tactic_state × list (expr × expr)) := do /- First, in order to get `to_expr e` to resolve declared `variables`, we add all of the declared variables to a fake `tactic_state`, and perform the resolution. At the end, `to_expr e` has done the work of determining which variables were actually referenced, which we then obtain from `fe` via `expr.list_local_consts` (which, importantly, is not defined for `pexpr`s). -/ vars ← list_available_include_vars, fake_es ← lean.parser.of_tactic $ lock_tactic_state $ do { /- Note that `add_local_consts_as_local_hyps` returns the mappings it generated, but we discard them on this first pass. (We return the mappings generated by our second invocation of this function below.) -/ add_local_consts_as_local_hyps vars, es.mmap to_expr }, /- Now calculate lists of a) the explicitly `include`ed variables and b) the variables which were referenced in `e` when it was resolved to `fake_e`. It is important that we include variables of the kind a) because we want `simp` to have access to declared local instances, and it is important that we only restrict to variables of kind a) and b) together since we do not to recognise a hypothesis which is posited as a `variable` in the environment but not referenced in the `pexpr` we were passed. One use case for this behaviour is running `simp` on the passed `pexpr`, since we do not want simp to use arbitrary hypotheses which were declared as `variables` in the local environment but not referenced in the expression to simplify (as one would be expect generally in tactic mode). -/ included_vars ← list_include_var_names, let referenced_vars := list.join $ fake_es.map $ λ e, e.list_local_consts.map expr.local_pp_name, /- Look up the explicit `included_vars` and the `referenced_vars` (which have appeared in the `pexpr` list which we were passed.) -/ let directly_included_vars := vars.filter $ λ var, (var.local_pp_name ∈ included_vars) ∨ (var.local_pp_name ∈ referenced_vars), /- Inflate the list `directly_included_vars` to include those variables which are "implicitly included" by virtue of reference to one or multiple others. For example, given `variables (n : ℕ) [prime n] [ih : even n]`, a reference to `n` implies that the typeclass instance `prime n` should be included, but `ih : even n` should not. -/ let all_implicitly_included_vars := expr.all_implicitly_included_variables vars directly_included_vars, /- Capture a tactic state where both of these kinds of variables have been added as local hypotheses, and resolve `e` against this state with `to_expr`, this time for real. -/ lean.parser.of_tactic $ do { mappings ← add_local_consts_as_local_hyps all_implicitly_included_vars, ts ← get_state, return (ts, mappings) } end lean.parser namespace tactic variables {α : Type} /-- Hole command used to fill in a structure's field when specifying an instance. In the following: ```lean instance : monad id := {! !} ``` invoking the hole command "Instance Stub" ("Generate a skeleton for the structure under construction.") produces: ```lean instance : monad id := { map := _, map_const := _, pure := _, seq := _, seq_left := _, seq_right := _, bind := _ } ``` -/ @[hole_command] meta def instance_stub : hole_command := { name := "Instance Stub", descr := "Generate a skeleton for the structure under construction.", action := λ _, do tgt ← target >>= whnf, let cl := tgt.get_app_fn.const_name, env ← get_env, fs ← expanded_field_list cl, let fs := fs.map prod.snd, let fs := format.intercalate (",\n " : format) $ fs.map (λ fn, format!"{fn} := _"), let out := format.to_string format!"{{ {fs} }", return [(out,"")] } add_tactic_doc { name := "instance_stub", category := doc_category.hole_cmd, decl_names := [`tactic.instance_stub], tags := ["instances"] } /-- Like `resolve_name` except when the list of goals is empty. In that situation `resolve_name` fails whereas `resolve_name'` simply proceeds on a dummy goal -/ meta def resolve_name' (n : name) : tactic pexpr := do [] ← get_goals | resolve_name n, g ← mk_mvar, set_goals [g], resolve_name n <* set_goals [] private meta def strip_prefix' (n : name) : list string → name → tactic name | s name.anonymous := pure $ s.foldl (flip name.mk_string) name.anonymous | s (name.mk_string a p) := do let n' := s.foldl (flip name.mk_string) name.anonymous, do { n'' ← tactic.resolve_constant n', if n'' = n then pure n' else strip_prefix' (a :: s) p } <|> strip_prefix' (a :: s) p | s n@(name.mk_numeral a p) := pure $ s.foldl (flip name.mk_string) n /-- Strips unnecessary prefixes from a name, e.g. if a namespace is open. -/ meta def strip_prefix : name → tactic name | n@(name.mk_string a a_1) := if (`_private).is_prefix_of n then let n' := n.update_prefix name.anonymous in n' <$ resolve_name' n' <|> pure n else strip_prefix' n [a] a_1 | n := pure n /-- Used to format return strings for the hole commands `match_stub` and `eqn_stub`. -/ meta def mk_patterns (t : expr) : tactic (list format) := do let cl := t.get_app_fn.const_name, env ← get_env, let fs := env.constructors_of cl, fs.mmap $ λ f, do { (vs,_) ← mk_const f >>= infer_type >>= mk_local_pis, let vs := vs.filter (λ v, v.is_default_local), vs ← vs.mmap (λ v, do v' ← get_unused_name v.local_pp_name, pose v' none `(()), pure v' ), vs.mmap' $ λ v, get_local v >>= clear, let args := list.intersperse (" " : format) $ vs.map to_fmt, f ← strip_prefix f, if args.empty then pure $ format!"| {f} := _\n" else pure format!"| ({f} {format.join args}) := _\n" } /-- Hole command used to generate a `match` expression. In the following: ```lean meta def foo (e : expr) : tactic unit := {! e !} ``` invoking hole command "Match Stub" ("Generate a list of equations for a `match` expression") produces: ```lean meta def foo (e : expr) : tactic unit := match e with | (expr.var a) := _ | (expr.sort a) := _ | (expr.const a a_1) := _ | (expr.mvar a a_1 a_2) := _ | (expr.local_const a a_1 a_2 a_3) := _ | (expr.app a a_1) := _ | (expr.lam a a_1 a_2 a_3) := _ | (expr.pi a a_1 a_2 a_3) := _ | (expr.elet a a_1 a_2 a_3) := _ | (expr.macro a a_1) := _ end ``` -/ @[hole_command] meta def match_stub : hole_command := { name := "Match Stub", descr := "Generate a list of equations for a `match` expression.", action := λ es, do [e] ← pure es | fail "expecting one expression", e ← to_expr e, t ← infer_type e >>= whnf, fs ← mk_patterns t, e ← pp e, let out := format.to_string format!"match {e} with\n{format.join fs}end\n", return [(out,"")] } add_tactic_doc { name := "Match Stub", category := doc_category.hole_cmd, decl_names := [`tactic.match_stub], tags := ["pattern matching"] } /-- Invoking hole command "Equations Stub" ("Generate a list of equations for a recursive definition") in the following: ```lean meta def foo : {! expr → tactic unit !} -- `:=` is omitted ``` produces: ```lean meta def foo : expr → tactic unit | (expr.var a) := _ | (expr.sort a) := _ | (expr.const a a_1) := _ | (expr.mvar a a_1 a_2) := _ | (expr.local_const a a_1 a_2 a_3) := _ | (expr.app a a_1) := _ | (expr.lam a a_1 a_2 a_3) := _ | (expr.pi a a_1 a_2 a_3) := _ | (expr.elet a a_1 a_2 a_3) := _ | (expr.macro a a_1) := _ ``` A similar result can be obtained by invoking "Equations Stub" on the following: ```lean meta def foo : expr → tactic unit := -- do not forget to write `:=`!! {! !} ``` ```lean meta def foo : expr → tactic unit := -- don't forget to erase `:=`!! | (expr.var a) := _ | (expr.sort a) := _ | (expr.const a a_1) := _ | (expr.mvar a a_1 a_2) := _ | (expr.local_const a a_1 a_2 a_3) := _ | (expr.app a a_1) := _ | (expr.lam a a_1 a_2 a_3) := _ | (expr.pi a a_1 a_2 a_3) := _ | (expr.elet a a_1 a_2 a_3) := _ | (expr.macro a a_1) := _ ``` -/ @[hole_command] meta def eqn_stub : hole_command := { name := "Equations Stub", descr := "Generate a list of equations for a recursive definition.", action := λ es, do t ← match es with | [t] := to_expr t | [] := target | _ := fail "expecting one type" end, e ← whnf t, (v :: _,_) ← mk_local_pis e | fail "expecting a Pi-type", t' ← infer_type v, fs ← mk_patterns t', t ← pp t, let out := if es.empty then format.to_string format!"-- do not forget to erase `:=`!!\n{format.join fs}" else format.to_string format!"{t}\n{format.join fs}", return [(out,"")] } add_tactic_doc { name := "Equations Stub", category := doc_category.hole_cmd, decl_names := [`tactic.eqn_stub], tags := ["pattern matching"] } /-- This command lists the constructors that can be used to satisfy the expected type. Invoking "List Constructors" ("Show the list of constructors of the expected type") in the following hole: ```lean def foo : ℤ ⊕ ℕ := {! !} ``` produces: ```lean def foo : ℤ ⊕ ℕ := {! sum.inl, sum.inr !} ``` and will display: ```lean sum.inl : ℤ → ℤ ⊕ ℕ sum.inr : ℕ → ℤ ⊕ ℕ ``` -/ @[hole_command] meta def list_constructors_hole : hole_command := { name := "List Constructors", descr := "Show the list of constructors of the expected type.", action := λ es, do t ← target >>= whnf, (_,t) ← mk_local_pis t, let cl := t.get_app_fn.const_name, let args := t.get_app_args, env ← get_env, let cs := env.constructors_of cl, ts ← cs.mmap $ λ c, do { e ← mk_const c, t ← infer_type (e.mk_app args) >>= pp, c ← strip_prefix c, pure format!"\n{c} : {t}\n" }, fs ← format.intercalate ", " <$> cs.mmap (strip_prefix >=> pure ∘ to_fmt), let out := format.to_string format!"{{! {fs} !}", trace (format.join ts).to_string, return [(out,"")] } add_tactic_doc { name := "List Constructors", category := doc_category.hole_cmd, decl_names := [`tactic.list_constructors_hole], tags := ["goal information"] } /-- Makes the declaration `classical.prop_decidable` available to type class inference. This asserts that all propositions are decidable, but does not have computational content. -/ meta def classical : tactic unit := do h ← get_unused_name `_inst, mk_const `classical.prop_decidable >>= note h none, reset_instance_cache open expr /-- `mk_comp v e` checks whether `e` is a sequence of nested applications `f (g (h v))`, and if so, returns the expression `f ∘ g ∘ h`. -/ meta def mk_comp (v : expr) : expr → tactic expr | (app f e) := if e = v then pure f else do guard (¬ v.occurs f) <|> fail "bad guard", e' ← mk_comp e >>= instantiate_mvars, f ← instantiate_mvars f, mk_mapp ``function.comp [none,none,none,f,e'] | e := do guard (e = v), t ← infer_type e, mk_mapp ``id [t] /-- From a lemma of the shape `∀ x, f (g x) = h x` derive an auxiliary lemma of the form `f ∘ g = h` for reasoning about higher-order functions. -/ meta def mk_higher_order_type : expr → tactic expr | (pi n bi d b@(pi _ _ _ _)) := do v ← mk_local_def n d, let b' := (b.instantiate_var v), (pi n bi d ∘ flip abstract_local v.local_uniq_name) <$> mk_higher_order_type b' | (pi n bi d b) := do v ← mk_local_def n d, let b' := (b.instantiate_var v), (l,r) ← match_eq b' <|> fail format!"not an equality {b'}", l' ← mk_comp v l, r' ← mk_comp v r, mk_app ``eq [l',r'] | e := failed open lean.parser interactive.types /-- A user attribute that applies to lemmas of the shape `∀ x, f (g x) = h x`. It derives an auxiliary lemma of the form `f ∘ g = h` for reasoning about higher-order functions. -/ @[user_attribute] meta def higher_order_attr : user_attribute unit (option name) := { name := `higher_order, parser := optional ident, descr := "From a lemma of the shape `∀ x, f (g x) = h x` derive an auxiliary lemma of the form `f ∘ g = h` for reasoning about higher-order functions.", after_set := some $ λ lmm _ _, do env ← get_env, decl ← env.get lmm, let num := decl.univ_params.length, let lvls := (list.iota num).map (`l).append_after, let l : expr := expr.const lmm $ lvls.map level.param, t ← infer_type l >>= instantiate_mvars, t' ← mk_higher_order_type t, (_,pr) ← solve_aux t' $ do { intros, applyc ``_root_.funext, intro1, applyc lmm; assumption }, pr ← instantiate_mvars pr, lmm' ← higher_order_attr.get_param lmm, lmm' ← (flip name.update_prefix lmm.get_prefix <$> lmm') <|> pure lmm.add_prime, add_decl $ declaration.thm lmm' lvls t' (pure pr), copy_attribute `simp lmm lmm', copy_attribute `functor_norm lmm lmm' } add_tactic_doc { name := "higher_order", category := doc_category.attr, decl_names := [`tactic.higher_order_attr], tags := ["lemma derivation"] } attribute [higher_order map_comp_pure] map_pure /-- Use `refine` to partially discharge the goal, or call `fconstructor` and try again. -/ private meta def use_aux (h : pexpr) : tactic unit := (focus1 (refine h >> done)) <|> (fconstructor >> use_aux) /-- Similar to `existsi`, `use l` will use entries in `l` to instantiate existential obligations at the beginning of a target. Unlike `existsi`, the pexprs in `l` are elaborated with respect to the expected type. ```lean example : ∃ x : ℤ, x = x := by tactic.use ``(42) ``` See the doc string for `tactic.interactive.use` for more information. -/ protected meta def use (l : list pexpr) : tactic unit := focus1 $ seq' (l.mmap' $ λ h, use_aux h <|> fail format!"failed to instantiate goal with {h}") instantiate_mvars_in_target /-- `clear_aux_decl_aux l` clears all expressions in `l` that represent aux decls from the local context. -/ meta def clear_aux_decl_aux : list expr → tactic unit | [] := skip | (e::l) := do cond e.is_aux_decl (tactic.clear e) skip, clear_aux_decl_aux l /-- `clear_aux_decl` clears all expressions from the local context that represent aux decls. -/ meta def clear_aux_decl : tactic unit := local_context >>= clear_aux_decl_aux /-- `apply_at_aux e et [] h ht` (with `et` the type of `e` and `ht` the type of `h`) finds a list of expressions `vs` and returns `(e.mk_args (vs ++ [h]), vs)`. -/ meta def apply_at_aux (arg t : expr) : list expr → expr → expr → tactic (expr × list expr) | vs e (pi n bi d b) := do { v ← mk_meta_var d, apply_at_aux (v :: vs) (e v) (b.instantiate_var v) } <|> (e arg, vs) <$ unify d t | vs e _ := failed /-- `apply_at e h` applies implication `e` on hypothesis `h` and replaces `h` with the result. -/ meta def apply_at (e h : expr) : tactic unit := do ht ← infer_type h, et ← infer_type e, (h', gs') ← apply_at_aux h ht [] e et, note h.local_pp_name none h', clear h, gs' ← gs'.mfilter is_assigned, (g :: gs) ← get_goals, set_goals (g :: gs' ++ gs) /-- `symmetry_hyp h` applies `symmetry` on hypothesis `h`. -/ meta def symmetry_hyp (h : expr) (md := semireducible) : tactic unit := do tgt ← infer_type h, env ← get_env, let r := get_app_fn tgt, match env.symm_for (const_name r) with | (some symm) := do s ← mk_const symm, apply_at s h | none := fail "symmetry tactic failed, target is not a relation application with the expected property." end precedence `setup_tactic_parser`:0 /-- `setup_tactic_parser` is a user command that opens the namespaces used in writing interactive tactics, and declares the local postfix notation `?` for `optional` and `*` for `many`. It does *not* use the `namespace` command, so it will typically be used after `namespace tactic.interactive`. -/ @[user_command] meta def setup_tactic_parser_cmd (_ : interactive.parse $ tk "setup_tactic_parser") : lean.parser unit := emit_code_here " open lean open lean.parser open interactive interactive.types local postfix `?`:9001 := optional local postfix *:9001 := many . " /-- `finally tac finalizer` runs `tac` first, then runs `finalizer` even if `tac` fails. `finally tac finalizer` fails if either `tac` or `finalizer` fails. -/ meta def finally {β} (tac : tactic α) (finalizer : tactic β) : tactic α := λ s, match tac s with | (result.success r s') := (finalizer >> pure r) s' | (result.exception msg p s') := (finalizer >> result.exception msg p) s' end /-- `on_exception handler tac` runs `tac` first, and then runs `handler` only if `tac` failed. -/ meta def on_exception {β} (handler : tactic β) (tac : tactic α) : tactic α | s := match tac s with | result.exception msg p s' := (handler *> result.exception msg p) s' | ok := ok end /-- `decorate_error add_msg tac` prepends `add_msg` to an exception produced by `tac` -/ meta def decorate_error (add_msg : string) (tac : tactic α) : tactic α | s := match tac s with | result.exception msg p s := let msg (_ : unit) : format := match msg with | some msg := add_msg ++ format.line ++ msg () | none := add_msg end in result.exception msg p s | ok := ok end /-- Applies tactic `t`. If it succeeds, revert the state, and return the value. If it fails, returns the error message. -/ meta def retrieve_or_report_error {α : Type u} (t : tactic α) : tactic (α ⊕ string) := λ s, match t s with | (interaction_monad.result.success a s') := result.success (sum.inl a) s | (interaction_monad.result.exception msg' _ s') := result.success (sum.inr (msg'.iget ()).to_string) s end /-- This tactic succeeds if `t` succeeds or fails with message `msg` such that `p msg` is `tt`. -/ meta def succeeds_or_fails_with_msg {α : Type} (t : tactic α) (p : string → bool) : tactic unit := do x ← retrieve_or_report_error t, match x with | (sum.inl _) := skip | (sum.inr msg) := if p msg then skip else fail msg end add_tactic_doc { name := "setup_tactic_parser", category := doc_category.cmd, decl_names := [`tactic.setup_tactic_parser_cmd], tags := ["parsing", "notation"] } /-- `trace_error msg t` executes the tactic `t`. If `t` fails, traces `msg` and the failure message of `t`. -/ meta def trace_error (msg : string) (t : tactic α) : tactic α | s := match t s with | (result.success r s') := result.success r s' | (result.exception (some msg') p s') := (trace msg >> trace (msg' ()) >> result.exception (some msg') p) s' | (result.exception none p s') := result.exception none p s' end /-- ``trace_if_enabled `n msg`` traces the message `msg` only if tracing is enabled for the name `n`. Create new names registered for tracing with `declare_trace n`. Then use `set_option trace.n true/false` to enable or disable tracing for `n`. -/ meta def trace_if_enabled (n : name) {α : Type u} [has_to_tactic_format α] (msg : α) : tactic unit := when_tracing n (trace msg) /-- ``trace_state_if_enabled `n msg`` prints the tactic state, preceded by the optional string `msg`, only if tracing is enabled for the name `n`. -/ meta def trace_state_if_enabled (n : name) (msg : string := "") : tactic unit := when_tracing n ((if msg = "" then skip else trace msg) >> trace_state) /-- This combinator is for testing purposes. It succeeds if `t` fails with message `msg`, and fails otherwise. -/ meta def success_if_fail_with_msg {α : Type u} (t : tactic α) (msg : string) : tactic unit := λ s, match t s with | (interaction_monad.result.exception msg' _ s') := let expected_msg := (msg'.iget ()).to_string in if msg = expected_msg then result.success () s else mk_exception format!"failure messages didn't match. Expected:\n{expected_msg}" none s | (interaction_monad.result.success a s) := mk_exception "success_if_fail_with_msg combinator failed, given tactic succeeded" none s end /-- `with_local_goals gs tac` runs `tac` on the goals `gs` and then restores the initial goals and returns the goals `tac` ended on. -/ meta def with_local_goals {α} (gs : list expr) (tac : tactic α) : tactic (α × list expr) := do gs' ← get_goals, set_goals gs, finally (prod.mk <$> tac <*> get_goals) (set_goals gs') /-- like `with_local_goals` but discards the resulting goals -/ meta def with_local_goals' {α} (gs : list expr) (tac : tactic α) : tactic α := prod.fst <$> with_local_goals gs tac /-- Representation of a proof goal that lends itself to comparison. The following goal: ```lean l₀ : T, l₁ : T ⊢ ∀ v : T, foo ``` is represented as ``` (2, ∀ l₀ l₁ v : T, foo) ``` The number 2 indicates that first the two bound variables of the `∀` are actually local constant. Comparing two such goals with `=` rather than `=ₐ` or `is_def_eq` tells us that proof script should not see the difference between the two. -/ meta def packaged_goal := ℕ × expr /-- proof state made of multiple `goal` meant for comparing the result of running different tactics -/ meta def proof_state := list packaged_goal meta instance goal.inhabited : inhabited packaged_goal := ⟨(0,var 0)⟩ meta instance proof_state.inhabited : inhabited proof_state := (infer_instance : inhabited (list packaged_goal)) /-- create a `packaged_goal` corresponding to the current goal -/ meta def get_packaged_goal : tactic packaged_goal := do ls ← local_context, tgt ← target >>= instantiate_mvars, tgt ← pis ls tgt, pure (ls.length, tgt) /-- `goal_of_mvar g`, with `g` a meta variable, creates a `packaged_goal` corresponding to `g` interpretted as a proof goal -/ meta def goal_of_mvar (g : expr) : tactic packaged_goal := with_local_goals' [g] get_packaged_goal /-- `get_proof_state` lists the user visible goal for each goal of the current state and for each goal, abstracts all of the meta variables of the other gaols. This produces a list of goals in the form of `ℕ × expr` where the `expr` encodes the following proof state: ```lean 2 goals l₁ : t₁, l₂ : t₂, l₃ : t₃ ⊢ tgt₁ ⊢ tgt₂ ``` as ```lean [ (3, ∀ (mv : tgt₁) (mv : tgt₂) (l₁ : t₁) (l₂ : t₂) (l₃ : t₃), tgt₁), (0, ∀ (mv : tgt₁) (mv : tgt₂), tgt₂) ] ``` with 2 goals, the first 2 bound variables encode the meta variable of all the goals, the next 3 (in the first goal) and 0 (in the second goal) are the local constants. This representation allows us to compare goals and proof states while ignoring information like the unique name of local constants and the equality or difference of meta variables that encode the same goal. -/ meta def get_proof_state : tactic proof_state := do gs ← get_goals, gs.mmap $ λ g, do ⟨n,g⟩ ← goal_of_mvar g, g ← gs.mfoldl (λ g v, do g ← kabstract g v reducible ff, pure $ pi `goal binder_info.default `(true) g ) g, pure (n,g) /-- Run `tac` in a disposable proof state and return the state. See `proof_state`, `goal` and `get_proof_state`. -/ meta def get_proof_state_after (tac : tactic unit) : tactic (option proof_state) := try_core $ retrieve $ tac >> get_proof_state open lean interactive /-- A type alias for `tactic format`, standing for "pretty print format". -/ meta def pformat := tactic format /-- `mk` lifts `fmt : format` to the tactic monad (`pformat`). -/ meta def pformat.mk (fmt : format) : pformat := pure fmt /-- an alias for `pp`. -/ meta def to_pfmt {α} [has_to_tactic_format α] (x : α) : pformat := pp x meta instance pformat.has_to_tactic_format : has_to_tactic_format pformat := ⟨ id ⟩ meta instance : has_append pformat := ⟨ λ x y, (++) <$> x <*> y ⟩ meta instance tactic.has_to_tactic_format [has_to_tactic_format α] : has_to_tactic_format (tactic α) := ⟨ λ x, x >>= to_pfmt ⟩ private meta def parse_pformat : string → list char → parser pexpr | acc [] := pure ``(to_pfmt %%(reflect acc)) | acc ('\n'::s) := do f ← parse_pformat "" s, pure ``(to_pfmt %%(reflect acc) ++ pformat.mk format.line ++ %%f) | acc ('{'::'{'::s) := parse_pformat (acc ++ "{") s | acc ('{'::s) := do (e, s) ← with_input (lean.parser.pexpr 0) s.as_string, '}'::s ← return s.to_list | fail "'}' expected", f ← parse_pformat "" s, pure ``(to_pfmt %%(reflect acc) ++ to_pfmt %%e ++ %%f) | acc (c::s) := parse_pformat (acc.str c) s reserve prefix `pformat! `:100 /-- See `format!` in `init/meta/interactive_base.lean`. The main differences are that `pp` is called instead of `to_fmt` and that we can use arguments of type `tactic α` in the quotations. Now, consider the following: ```lean e ← to_expr ``(3 + 7), trace format!"{e}" -- outputs `has_add.add.{0} nat nat.has_add (bit1.{0} nat nat.has_one nat.has_add (has_one.one.{0} nat nat.has_one)) ...` trace pformat!"{e}" -- outputs `3 + 7` ``` The difference is significant. And now, the following is expressible: ```lean e ← to_expr ``(3 + 7), trace pformat!"{e} : {infer_type e}" -- outputs `3 + 7 : ℕ` ``` See also: `trace!` and `fail!` -/ @[user_notation] meta def pformat_macro (_ : parse $ tk "pformat!") (s : string) : parser pexpr := do e ← parse_pformat "" s.to_list, return ``(%%e : pformat) reserve prefix `fail! `:100 /-- The combination of `pformat` and `fail`. -/ @[user_notation] meta def fail_macro (_ : parse $ tk "fail!") (s : string) : parser pexpr := do e ← pformat_macro () s, pure ``((%%e : pformat) >>= fail) reserve prefix `trace! `:100 /-- The combination of `pformat` and `fail`. -/ @[user_notation] meta def trace_macro (_ : parse $ tk "trace!") (s : string) : parser pexpr := do e ← pformat_macro () s, pure ``((%%e : pformat) >>= trace) /-- A hackish way to get the `src` directory of mathlib. -/ meta def get_mathlib_dir : tactic string := do e ← get_env, s ← e.decl_olean `tactic.reset_instance_cache, return $ s.popn_back 17 /-- Checks whether a declaration with the given name is declared in mathlib. If you want to run this tactic many times, you should use `environment.is_prefix_of_file` instead, since it is expensive to execute `get_mathlib_dir` many times. -/ meta def is_in_mathlib (n : name) : tactic bool := do ml ← get_mathlib_dir, e ← get_env, return $ e.is_prefix_of_file ml n /-- Runs a tactic by name. If it is a `tactic string`, return whatever string it returns. If it is a `tactic unit`, return the name. (This is mostly used in invoking "self-reporting tactics", e.g. by `tidy` and `hint`.) -/ meta def name_to_tactic (n : name) : tactic string := do d ← get_decl n, e ← mk_const n, let t := d.type, if (t =ₐ `(tactic unit)) then (eval_expr (tactic unit) e) >>= (λ t, t >> (name.to_string <$> strip_prefix n)) else if (t =ₐ `(tactic string)) then (eval_expr (tactic string) e) >>= (λ t, t) else fail!"name_to_tactic cannot take `{n} as input: its type must be `tactic string` or `tactic unit`" /-- auxiliary function for `apply_under_n_pis` -/ private meta def apply_under_n_pis_aux (func arg : pexpr) : ℕ → ℕ → expr → pexpr | n 0 _ := let vars := ((list.range n).reverse.map (@expr.var ff)), bd := vars.foldl expr.app arg.mk_explicit in func bd | n (k+1) (expr.pi nm bi tp bd) := expr.pi nm bi (pexpr.of_expr tp) (apply_under_n_pis_aux (n+1) k bd) | n (k+1) t := apply_under_n_pis_aux n 0 t /-- Assumes `pi_expr` is of the form `Π x1 ... xn xn+1..., _`. Creates a pexpr of the form `Π x1 ... xn, func (arg x1 ... xn)`. All arguments (implicit and explicit) to `arg` should be supplied. -/ meta def apply_under_n_pis (func arg : pexpr) (pi_expr : expr) (n : ℕ) : pexpr := apply_under_n_pis_aux func arg 0 n pi_expr /-- Assumes `pi_expr` is of the form `Π x1 ... xn, _`. Creates a pexpr of the form `Π x1 ... xn, func (arg x1 ... xn)`. All arguments (implicit and explicit) to `arg` should be supplied. -/ meta def apply_under_pis (func arg : pexpr) (pi_expr : expr) : pexpr := apply_under_n_pis func arg pi_expr pi_expr.pi_arity /-- If `func` is a `pexpr` representing a function that takes an argument `a`, `get_pexpr_arg_arity_with_tgt func tgt` returns the arity of `a`. When `tgt` is a `pi` expr, `func` is elaborated in a context with the domain of `tgt`. Examples: * ```get_pexpr_arg_arity ``(ring) `(true)``` returns 0, since `ring` takes one non-function argument. * ```get_pexpr_arg_arity_with_tgt ``(monad) `(true)``` returns 1, since `monad` takes one argument of type `α → α`. * ```get_pexpr_arg_arity_with_tgt ``(module R) `(Π (R : Type), comm_ring R → true)``` returns 0 -/ private meta def get_pexpr_arg_arity_with_tgt (func : pexpr) (tgt : expr) : tactic ℕ := lock_tactic_state $ do mv ← mk_mvar, solve_aux tgt $ intros >> to_expr ``(%%func %%mv), expr.pi_arity <$> (instantiate_mvars mv >>= infer_type) /-- Tries to derive instances by unfolding the newly introduced type and applying type class resolution. For example, ```lean @[derive ring] def new_int : Type := ℤ ``` adds an instance `ring new_int`, defined to be the instance of `ring ℤ` found by `apply_instance`. Multiple instances can be added with `@[derive [ring, module ℝ]]`. This derive handler applies only to declarations made using `def`, and will fail on such a declaration if it is unable to derive an instance. It is run with higher priority than the built-in handlers, which will fail on `def`s. -/ @[derive_handler, priority 2000] meta def delta_instance : derive_handler := λ cls new_decl_name, do env ← get_env, if env.is_inductive new_decl_name then return ff else do new_decl ← get_decl new_decl_name, new_decl_pexpr ← resolve_name new_decl_name, arity ← get_pexpr_arg_arity_with_tgt cls new_decl.type, tgt ← to_expr $ apply_under_n_pis cls new_decl_pexpr new_decl.type (new_decl.type.pi_arity - arity), (_, inst) ← solve_aux tgt (intros >> reset_instance_cache >> delta_target [new_decl_name] >> apply_instance >> done), inst ← instantiate_mvars inst, inst ← replace_univ_metas_with_univ_params inst, tgt ← instantiate_mvars tgt, nm ← get_unused_decl_name $ new_decl_name <.> match cls with | (expr.const nm _) := nm.last | _ := "inst" end, add_protected_decl $ declaration.defn nm inst.collect_univ_params tgt inst new_decl.reducibility_hints new_decl.is_trusted, set_basic_attribute `instance nm tt, return tt /-- `find_private_decl n none` finds a private declaration named `n` in any of the imported files. `find_private_decl n (some m)` finds a private declaration named `n` in the same file where a declaration named `m` can be found. -/ meta def find_private_decl (n : name) (fr : option name) : tactic name := do env ← get_env, fn ← option_t.run (do fr ← option_t.mk (return fr), d ← monad_lift $ get_decl fr, option_t.mk (return $ env.decl_olean d.to_name) ), let p : string → bool := match fn with | (some fn) := λ x, fn = x | none := λ _, tt end, let xs := env.decl_filter_map (λ d, do fn ← env.decl_olean d.to_name, guard ((`_private).is_prefix_of d.to_name ∧ p fn ∧ d.to_name.update_prefix name.anonymous = n), pure d.to_name), match xs with | [n] := pure n | [] := fail "no such private found" | _ := fail "many matches found" end open lean.parser interactive /-- `import_private foo from bar` finds a private declaration `foo` in the same file as `bar` and creates a local notation to refer to it. `import_private foo` looks for `foo` in all imported files. When possible, make `foo` non-private rather than using this feature. -/ @[user_command] meta def import_private_cmd (_ : parse $ tk "import_private") : lean.parser unit := do n ← ident, fr ← optional (tk "from" *> ident), n ← find_private_decl n fr, c ← resolve_constant n, d ← get_decl n, let c := @expr.const tt c d.univ_levels, new_n ← new_aux_decl_name, add_decl $ declaration.defn new_n d.univ_params d.type c reducibility_hints.abbrev d.is_trusted, let new_not := sformat!"local notation `{n.update_prefix name.anonymous}` := {new_n}", emit_command_here $ new_not, skip . add_tactic_doc { name := "import_private", category := doc_category.cmd, decl_names := [`tactic.import_private_cmd], tags := ["renaming"] } /-- The command `mk_simp_attribute simp_name "description"` creates a simp set with name `simp_name`. Lemmas tagged with `@[simp_name]` will be included when `simp with simp_name` is called. `mk_simp_attribute simp_name none` will use a default description. Appending the command with `with attr1 attr2 ...` will include all declarations tagged with `attr1`, `attr2`, ... in the new simp set. This command is preferred to using ``run_cmd mk_simp_attr `simp_name`` since it adds a doc string to the attribute that is defined. If you need to create a simp set in a file where this command is not available, you should use ```lean run_cmd mk_simp_attr `simp_name run_cmd add_doc_string `simp_attr.simp_name "Description of the simp set here" ``` -/ @[user_command] meta def mk_simp_attribute_cmd (_ : parse $ tk "mk_simp_attribute") : lean.parser unit := do n ← ident, d ← parser.pexpr, d ← to_expr ``(%%d : option string), descr ← eval_expr (option string) d, with_list ← types.with_ident_list <|> return [], mk_simp_attr n with_list, add_doc_string (name.append `simp_attr n) $ descr.get_or_else $ "simp set for " ++ to_string n add_tactic_doc { name := "mk_simp_attribute", category := doc_category.cmd, decl_names := [`tactic.mk_simp_attribute_cmd], tags := ["simplification"] } end tactic
bce20951efc3834d38e9450399a62cd5715d3293
597e185014db6ce8a949dac0322798f11218338b
/src/kruskal_katona_rewrite.lean
0f7bf6e18905f9c8e6ffd4a935de948c9e46460c
[]
no_license
b-mehta/lean-experiments
58ce21c7106dfde163c236175fee30b341ba69ee
5f0aed189f724ae6f739ec75dcdddcd2687614e1
refs/heads/master
1,598,987,002,293
1,576,649,380,000
1,576,649,380,000
219,032,370
0
0
null
null
null
null
UTF-8
Lean
false
false
76,746
lean
import algebra.geom_sum import data.finset import data.fintype import data.list import tactic open fintype open finset variables {n : ℕ} local notation `X` := fin n variables {𝒜 : finset (finset X)} lemma union_singleton_eq_insert {α : Type*} [decidable_eq α] (a : α) (s : finset α) : finset.singleton a ∪ s = insert a s := begin ext, rw [mem_insert, mem_union, mem_singleton] end lemma mem_powerset_len_iff_card {r : ℕ} : ∀ (x : finset X), x ∈ powerset_len r (elems X) ↔ card x = r := by intro x; rw mem_powerset_len; exact and_iff_right (subset_univ _) def example1 : finset (finset (fin 5)) := { {0,1,2}, {0,1,3}, {0,2,3}, {0,2,4} } section layers variables {r : ℕ} def is_layer (𝒜 : finset (finset X)) (r : ℕ) : Prop := ∀ A ∈ 𝒜, card A = r lemma union_layer {A B : finset (finset X)} : is_layer A r ∧ is_layer B r ↔ is_layer (A ∪ B) r := begin split; intros p, rw is_layer, intros, rw mem_union at H, cases H, exact (p.1 _ H), exact (p.2 _ H), split, all_goals {rw is_layer, intros, apply p, rw mem_union, tauto}, end lemma powerset_len_iff_is_layer : is_layer 𝒜 r ↔ 𝒜 ⊆ powerset_len r (elems X) := begin split; intros p A h, rw mem_powerset_len_iff_card, exact (p _ h), rw ← mem_powerset_len_iff_card, exact p h end lemma size_in_layer (h : is_layer 𝒜 r) : card 𝒜 ≤ nat.choose (card X) r := begin rw [fintype.card, ← card_powerset_len], apply card_le_of_subset, rwa [univ, ← powerset_len_iff_is_layer] end end layers lemma bind_sub_bind_of_sub_left {α β : Type*} [decidable_eq β] {s₁ s₂ : finset α} {t : α → finset β} (h : s₁ ⊆ s₂) : s₁.bind t ⊆ s₂.bind t := by intro x; simp; intros y hy hty; refine ⟨y, h hy, hty⟩ section shadow def all_removals (A : finset X) : finset (finset X) := A.image (erase A) lemma all_removals_size {A : finset X} {r : ℕ} (h : A.card = r) : is_layer (all_removals A) (r-1) := begin intros B H, rw [all_removals, mem_image] at H, rcases H with ⟨i, ih, Bh⟩, rw [← Bh, card_erase_of_mem ih, h], refl end def mem_all_removals {A : finset X} {B : finset X} : B ∈ all_removals A ↔ ∃ i ∈ A, erase A i = B := by simp only [all_removals, mem_image] lemma card_all_removals {A : finset X} {r : ℕ} (H : card A = r) : (all_removals A).card = r := begin rwa [all_removals, card_image_of_inj_on], intros i ih j _ k, have q: i ∉ erase A j := k ▸ not_mem_erase i A, rw [mem_erase, not_and] at q, by_contra a, apply q a ih end def shadow (𝒜 : finset (finset X)) : finset (finset X) := 𝒜.bind all_removals reserve prefix `∂`:90 notation ∂𝒜 := shadow 𝒜 def mem_shadow (B : finset X) : B ∈ shadow 𝒜 ↔ ∃ A ∈ 𝒜, ∃ i ∈ A, erase A i = B := by simp only [shadow, all_removals, mem_bind, mem_image] def mem_shadow' {B : finset X} : B ∈ shadow 𝒜 ↔ ∃ j ∉ B, insert j B ∈ 𝒜 := begin rw mem_shadow, split, rintro ⟨A, HA, i, Hi, k⟩, rw ← k, refine ⟨i, not_mem_erase i A, _⟩, rwa insert_erase Hi, rintro ⟨i, Hi, k⟩, refine ⟨insert i B, k, i, mem_insert_self _ _, _⟩, rw erase_insert Hi end lemma shadow_layer {r : ℕ} : is_layer 𝒜 r → is_layer (∂𝒜) (r-1) := begin intros a A H, rw [shadow, mem_bind] at H, rcases H with ⟨B, _, _⟩, exact all_removals_size (a _ ‹_›) _ ‹A ∈ all_removals B›, end def sub_of_shadow {B : finset X} : B ∈ ∂𝒜 → ∃ A ∈ 𝒜, B ⊆ A := begin intro k, rw mem_shadow at k, rcases k with ⟨A, H, _, _, k⟩, rw ← k, exact ⟨A, H, erase_subset _ _⟩ end def sub_iff_shadow_one {B : finset X} : B ∈ shadow 𝒜 ↔ ∃ A ∈ 𝒜, B ⊆ A ∧ card (A \ B) = 1 := begin rw mem_shadow', split, rintro ⟨i, ih, inA⟩, refine ⟨insert i B, inA, subset_insert _ _, _⟩, rw card_sdiff (subset_insert _ _), rw card_insert_of_not_mem ih, simp, rintro ⟨A, hA, _⟩, rw card_eq_one at a_h_h, rcases a_h_h with ⟨subs, j, eq⟩, use j, refine ⟨_, _⟩, intro, have: j ∈ finset.singleton j, rw mem_singleton, rw ← eq at this, rw mem_sdiff at this, exact this.2 a, rw ← union_singleton_eq_insert, rw ← eq, rwa sdiff_union_of_subset subs, end def sub_iff_shadow_iter {B : finset X} (k : ℕ) : B ∈ nat.iterate shadow k 𝒜 ↔ ∃ A ∈ 𝒜, B ⊆ A ∧ card (A \ B) = k := begin revert 𝒜 B, induction k with k ih, simp, intros 𝒜 B, split, intro p, refine ⟨B, p, subset.refl _, _⟩, apply eq_empty_of_forall_not_mem, intro x, rw mem_sdiff, tauto, rintro ⟨A, _, _⟩, rw sdiff_eq_empty_iff_subset at a_h_right, have: A = B := subset.antisymm a_h_right.2 a_h_right.1, rwa ← this, simp, intros 𝒜 B, have := @ih (∂𝒜) B, rw this, clear this ih, split, rintro ⟨A, hA, BsubA, card_AdiffB_is_k⟩, rw sub_iff_shadow_one at hA, rcases hA with ⟨C, CinA, AsubC, card_CdiffA_is_1⟩, refine ⟨C, CinA, trans BsubA AsubC, _⟩, rw card_sdiff (trans BsubA AsubC), rw card_sdiff BsubA at card_AdiffB_is_k, rw card_sdiff AsubC at card_CdiffA_is_1, by calc card C - card B = (card C - card A + card A) - card B : begin rw nat.sub_add_cancel, apply card_le_of_subset AsubC end ... = (card C - card A) + (card A - card B) : begin rw nat.add_sub_assoc, apply card_le_of_subset BsubA end ... = k + 1 : begin rw [card_CdiffA_is_1, card_AdiffB_is_k, add_comm] end, rintro ⟨A, hA, _, _⟩, have z: A \ B ≠ ∅, rw ← card_pos, rw a_h_right_right, exact nat.succ_pos _, rw [ne, ← exists_mem_iff_ne_empty] at z, rcases z with ⟨i, hi⟩, have: i ∈ A, rw mem_sdiff at hi, exact hi.1, have: B ⊆ erase A i, { intros t th, apply mem_erase_of_ne_of_mem _ (a_h_right_left th), intro, rw mem_sdiff at hi, rw a at th, exact hi.2 th }, refine ⟨erase A i, _, ‹_›, _⟩, { rw mem_shadow, refine ⟨A, hA, i, ‹_›, rfl⟩ }, rw card_sdiff ‹B ⊆ erase A i›, rw card_erase_of_mem ‹i ∈ A›, rw nat.pred_sub, rw ← card_sdiff a_h_right_left, rw a_h_right_right, simp, end end shadow #eval shadow example1 section local_lym lemma multiply_out {A B n r : ℕ} (hr1 : 1 ≤ r) (hr2 : r ≤ n) (h : A * r ≤ B * (n - r + 1)) : (A : ℚ) / (nat.choose n r) ≤ B / nat.choose n (r-1) := begin rw div_le_div_iff; norm_cast, apply le_of_mul_le_mul_right _ ‹0 < r›, cases r, simp, rw nat.succ_eq_add_one at *, rw [← nat.sub_add_comm hr2, nat.add_sub_add_right] at h, rw [nat.add_sub_cancel, mul_assoc B, nat.choose_succ_right_eq, mul_right_comm, ← mul_assoc, mul_right_comm B], exact nat.mul_le_mul_right _ h, apply nat.choose_pos hr2, apply nat.choose_pos (le_trans (nat.pred_le _) hr2) end def the_pairs (𝒜 : finset (finset X)) : finset (finset X × finset X) := 𝒜.bind (λ A, (all_removals A).image (prod.mk A)) lemma card_the_pairs {r : ℕ} (𝒜 : finset (finset X)) : is_layer 𝒜 r → (the_pairs 𝒜).card = 𝒜.card * r := begin intro, rw [the_pairs, card_bind], { convert (sum_congr rfl _), { rw [← nat.smul_eq_mul, ← sum_const] }, intros, rw [card_image_of_inj_on, card_all_removals (a _ H)], exact (λ _ _ _ _ k, (prod.mk.inj k).2) }, simp only [disjoint_left, mem_image], rintros _ _ _ _ k a ⟨_, _, a₁⟩ ⟨_, _, a₂⟩, exact k (prod.mk.inj (a₁.trans a₂.symm)).1, end def from_below (𝒜 : finset (finset X)) : finset (finset X × finset X) := (∂𝒜).bind (λ B, (univ \ B).image (λ x, (insert x B, B))) lemma mem_the_pairs (A B : finset X) : (A,B) ∈ the_pairs 𝒜 ↔ A ∈ 𝒜 ∧ B ∈ all_removals A := begin simp only [the_pairs, mem_bind, mem_image], split, { rintro ⟨a, Ha, b, Hb, h⟩, rw [(prod.mk.inj h).1, (prod.mk.inj h).2] at *, exact ⟨Ha, Hb⟩ }, { intro h, exact ⟨A, h.1, B, h.2, rfl⟩} end lemma mem_from_below (A B : finset X) : A ∈ 𝒜 ∧ (∃ (i ∉ B), insert i B = A) → (A,B) ∈ from_below 𝒜 := begin rw [from_below, mem_bind], rintro ⟨Ah, i, ih, a⟩, refine ⟨B, _, _⟩, rw mem_shadow', refine ⟨i, ih, a.symm ▸ Ah⟩, rw mem_image, refine ⟨i, mem_sdiff.2 ⟨complete _, ih⟩, by rw a⟩, end lemma above_sub_below (𝒜 : finset (finset X)) : the_pairs 𝒜 ⊆ from_below 𝒜 := begin rintros ⟨A,B⟩ h, rw [mem_the_pairs, mem_all_removals] at h, apply mem_from_below, rcases h with ⟨Ah, i, ih, AeB⟩, refine ⟨Ah, i, _, _⟩; rw ← AeB, apply not_mem_erase, apply insert_erase ih end lemma card_from_below (r : ℕ) : is_layer 𝒜 r → (from_below 𝒜).card ≤ (∂𝒜).card * (n - (r - 1)) := begin intro, rw [from_below], convert card_bind_le, rw [← nat.smul_eq_mul, ← sum_const], apply sum_congr rfl, intros, rw [card_image_of_inj_on, card_sdiff (subset_univ _), card_univ, card_fin, shadow_layer a _ H], intros x1 x1h _ _ h, have q := mem_insert_self x1 x, rw [(prod.mk.inj h).1, mem_insert] at q, apply or.resolve_right q ((mem_sdiff.1 x1h).2), end theorem local_lym {r : ℕ} (hr1 : r ≥ 1) (hr2 : r ≤ n) (H : is_layer 𝒜 r): (𝒜.card : ℚ) / nat.choose n r ≤ (∂𝒜).card / nat.choose n (r-1) := begin apply multiply_out hr1 hr2, rw ← card_the_pairs _ H, transitivity, apply card_le_of_subset (above_sub_below _), rw ← nat.sub_sub_assoc hr2 hr1, apply card_from_below _ H end end local_lym section slice def slice (𝒜 : finset (finset X)) (r : ℕ) : finset (finset X) := 𝒜.filter (λ i, card i = r) reserve infix `#`:100 notation 𝒜#r := slice 𝒜 r lemma mem_slice {r : ℕ} {A : finset X} : A ∈ 𝒜#r ↔ A ∈ 𝒜 ∧ A.card = r := by rw [slice, mem_filter] lemma layered_slice {𝒜 : finset (finset X)} {r : ℕ} : is_layer (𝒜#r) r := λ _ h, (mem_slice.1 h).2 lemma ne_of_diff_slice {r₁ r₂ : ℕ} {A₁ A₂ : finset X} (h₁ : A₁ ∈ 𝒜#r₁) (h₂ : A₂ ∈ 𝒜#r₂) : r₁ ≠ r₂ → A₁ ≠ A₂ := mt (λ h, (layered_slice A₁ h₁).symm.trans ((congr_arg card h).trans (layered_slice A₂ h₂))) end slice section lym def antichain (𝒜 : finset (finset X)) : Prop := ∀ A ∈ 𝒜, ∀ B ∈ 𝒜, A ≠ B → ¬(A ⊆ B) def decompose' (𝒜 : finset (finset X)) : Π (k : ℕ), finset (finset X) | 0 := 𝒜#n | (k+1) := 𝒜#(n - (k+1)) ∪ shadow (decompose' k) def decompose'_layer (𝒜 : finset (finset X)) (k : ℕ) : is_layer (decompose' 𝒜 k) (n-k) := begin induction k with k ih; rw decompose', apply layered_slice, rw ← union_layer, split, apply layered_slice, apply shadow_layer ih, end theorem antichain_prop {r k : ℕ} (hk : k ≤ n) (hr : r < k) (H : antichain 𝒜) : ∀ A ∈ 𝒜#(n - k), ∀ B ∈ ∂decompose' 𝒜 r, ¬(A ⊆ B) := begin intros A HA B HB k, rcases sub_of_shadow HB with ⟨C, HC, _⟩, replace k := trans k ‹B ⊆ C›, clear HB h_h B, induction r with r ih generalizing A C; rw decompose' at HC, any_goals { rw mem_union at HC, cases HC }, any_goals { refine H A (mem_slice.1 HA).1 C (mem_slice.1 HC).1 _ ‹A ⊆ C›, apply ne_of_diff_slice HA HC _, apply ne_of_lt }, { apply nat.sub_lt_of_pos_le _ _ hr hk }, { mono }, obtain ⟨_, HB', HB''⟩ := sub_of_shadow HC, refine ih (nat.lt_of_succ_lt hr) _ _ HA HB' (trans k_1 HB'') end lemma disjoint_of_antichain {k : ℕ} (hk : k + 1 ≤ n) (H : antichain 𝒜) : disjoint (𝒜#(n - (k + 1))) (∂decompose' 𝒜 k) := disjoint_left.2 $ λ A HA HB, antichain_prop hk (lt_add_one k) H A HA A HB (subset.refl _) lemma card_decompose'_other {k : ℕ} (hk : k ≤ n) (H : antichain 𝒜) : sum (range (k+1)) (λ r, ((𝒜#(n-r)).card : ℚ) / nat.choose n (n-r)) ≤ ((decompose' 𝒜 k).card : ℚ) / nat.choose n (n-k) := begin induction k with k ih, rw [sum_range_one, div_le_div_iff]; norm_cast, exact nat.choose_pos (nat.sub_le _ _), exact nat.choose_pos (nat.sub_le _ _), rw [sum_range_succ, decompose'], have: (𝒜#(n - (k + 1)) ∪ ∂decompose' 𝒜 k).card = (𝒜#(n - (k + 1))).card + (∂decompose' 𝒜 k).card, apply card_disjoint_union, rw disjoint_iff_ne, intros A hA B hB m, apply antichain_prop hk (lt_add_one k) H A hA B hB, rw m, refl, rw this, have: ↑((𝒜#(n - (k + 1))).card + (∂decompose' 𝒜 k).card) / (nat.choose n (n - nat.succ k) : ℚ) = ((𝒜#(n - (k + 1))).card : ℚ) / (nat.choose n (n - nat.succ k)) + ((∂decompose' 𝒜 k).card : ℚ) / (nat.choose n (n - nat.succ k)), rw ← add_div, norm_cast, rw this, apply add_le_add_left, transitivity, exact ih (le_of_lt hk), apply local_lym (nat.le_sub_left_of_add_le hk) (nat.sub_le _ _) (decompose'_layer _ _) end lemma sum_flip {α : Type*} [add_comm_monoid α] {n : ℕ} (f : ℕ → α) : sum (range (n+1)) (λ r, f (n - r)) = sum (range (n+1)) (λ r, f r) := begin induction n with n ih, rw [sum_range_one, sum_range_one], rw sum_range_succ', rw sum_range_succ _ (nat.succ n), simp [ih], end lemma card_decompose_other (H : antichain 𝒜) : (range (n+1)).sum (λ r, ((𝒜#r).card : ℚ) / nat.choose n r) ≤ (decompose' 𝒜 n).card / nat.choose n 0 := begin rw [← nat.sub_self n], convert ← card_decompose'_other (le_refl n) H using 1, apply sum_flip (λ r, ((𝒜#r).card : ℚ) / nat.choose n r), end lemma lubell_yamamoto_meshalkin (H : antichain 𝒜) : (range (n+1)).sum (λ r, ((𝒜#r).card : ℚ) / nat.choose n r) ≤ 1 := begin transitivity, apply card_decompose_other H, rw div_le_iff; norm_cast, simpa only [card_fin, mul_one, nat.choose_zero_right, nat.sub_self] using size_in_layer (decompose'_layer 𝒜 n), apply nat.choose_pos (zero_le n) end end lym lemma dominate_choose_lt {r n : ℕ} (h : r < n/2) : nat.choose n r ≤ nat.choose n (r+1) := begin refine le_of_mul_le_mul_right _ (nat.lt_sub_left_of_add_lt (lt_of_lt_of_le h (nat.div_le_self n 2))), rw ← nat.choose_succ_right_eq, apply nat.mul_le_mul_left, rw ← nat.lt_iff_add_one_le, apply nat.lt_sub_left_of_add_lt, rw ← mul_two, exact lt_of_lt_of_le (mul_lt_mul_of_pos_right h zero_lt_two) (nat.div_mul_le_self n 2), end lemma dominate_choose_lt' {n r : ℕ} (hr : r ≤ n/2) : nat.choose n r ≤ nat.choose n (n/2) := begin refine (@nat.decreasing_induction (λ k, k ≤ n/2 → nat.choose n k ≤ nat.choose n (n/2)) _ r (n/2) hr (λ _, by refl)) hr, intros m k a, cases lt_or_eq_of_le a, transitivity nat.choose n (m + 1), exact dominate_choose_lt h, exact k h, rw h, end lemma dominate_choose {r n : ℕ} : nat.choose n r ≤ nat.choose n (n/2) := begin cases le_or_gt r n with b b, cases le_or_gt r (n/2) with a, apply dominate_choose_lt' a, rw ← nat.choose_symm b, apply dominate_choose_lt', rw [gt_iff_lt, nat.div_lt_iff_lt_mul _ _ zero_lt_two] at h, rw [nat.le_div_iff_mul_le _ _ zero_lt_two, nat.mul_sub_right_distrib, nat.sub_le_iff, mul_two, nat.add_sub_cancel], exact le_of_lt h, rw nat.choose_eq_zero_of_lt b, apply zero_le end lemma sum_div {α : Type*} {s : finset α} {f : α → ℚ} {b : ℚ} : s.sum f / b = s.sum (λx, f x / b) := calc s.sum f / b = s.sum (λ x, f x * (1 / b)) : by rw [div_eq_mul_one_div, sum_mul] ... = s.sum (λ x, f x / b) : by congr; ext; rw ← div_eq_mul_one_div lemma sperner (H : antichain 𝒜) : 𝒜.card ≤ nat.choose n (n / 2) := begin have q1 := lubell_yamamoto_meshalkin H, set f := (λ (r : ℕ), ((𝒜#r).card : ℚ) / nat.choose n r), set g := (λ (r : ℕ), ((𝒜#r).card : ℚ) / nat.choose n (n/2)), have q2 : sum (range (n + 1)) g ≤ sum (range (n + 1)) f, apply sum_le_sum, intros r hr, apply div_le_div_of_le_left; norm_cast, apply zero_le, apply nat.choose_pos, rw mem_range at hr, rwa ← nat.lt_succ_iff, apply dominate_choose, have := trans q2 q1, rw [← sum_div, ← sum_nat_cast, div_le_one_iff_le] at this, swap, norm_cast, apply nat.choose_pos (nat.div_le_self _ _), norm_cast at this, rw ← card_bind at this, suffices m: finset.bind (range (n + 1)) (λ (u : ℕ), 𝒜#u) = 𝒜, rwa m at this, ext, rw mem_bind, split, rintro ⟨_,_,q⟩, rw mem_slice at q, exact q.1, intro, refine ⟨a.card, _, _⟩, rw [mem_range, nat.lt_succ_iff], conv {to_rhs, rw ← card_fin n}, apply card_le_of_subset (subset_univ a), rw mem_slice, tauto, intros x _ y _ ne, rw disjoint_left, intros a Ha k, exact ne_of_diff_slice Ha k ne rfl end lemma sdiff_union_inter {α : Type*} [decidable_eq α] (A B : finset α) : (A \ B) ∪ (A ∩ B) = A := by simp only [ext, mem_union, mem_sdiff, mem_inter]; tauto lemma sdiff_inter_inter {α : Type*} [decidable_eq α] (A B : finset α) : disjoint (A \ B) (A ∩ B) := disjoint_of_subset_right (inter_subset_right _ _) sdiff_disjoint -- by simp only [ext, mem_inter, mem_sdiff, not_mem_empty]; tauto namespace ij section variables (i j : X) def compress (i j : X) (A : finset X) : finset X := if (j ∈ A ∧ i ∉ A) then insert i (A.erase j) else A local notation `C` := compress i j def compressed_set {A : finset X} : ¬ (j ∈ C A ∧ i ∉ C A) := begin intro, rw compress at a, split_ifs at a, apply a.2, apply mem_insert_self, exact h a end lemma compress_idem (A : finset X) : C (C A) = C A := begin rw compress, split_ifs, exfalso, apply compressed_set _ _ h, refl end @[reducible] def compress_motion (𝒜 : finset (finset X)) : finset (finset X) := 𝒜.filter (λ A, C A ∈ 𝒜) @[reducible] def compress_remains (𝒜 : finset (finset X)) : finset (finset X) := (𝒜.filter (λ A, C A ∉ 𝒜)).image (λ A, C A) def compress_family (i j : X) (𝒜 : finset (finset X)) : finset (finset X) := @compress_remains _ i j 𝒜 ∪ @compress_motion _ i j 𝒜 local notation `CC` := compress_family i j lemma mem_compress_motion (A : finset X) : A ∈ compress_motion i j 𝒜 ↔ A ∈ 𝒜 ∧ C A ∈ 𝒜 := by rw mem_filter lemma mem_compress_remains (A : finset X) : A ∈ compress_remains i j 𝒜 ↔ A ∉ 𝒜 ∧ (∃ B ∈ 𝒜, C B = A) := begin simp [compress_remains], split; rintro ⟨p, q, r⟩, exact ⟨r ▸ q.2, p, ⟨q.1, r⟩⟩, exact ⟨q, ⟨r.1, r.2.symm ▸ p⟩, r.2⟩, end lemma mem_compress {A : finset X} : A ∈ CC 𝒜 ↔ (A ∉ 𝒜 ∧ (∃ B ∈ 𝒜, C B = A)) ∨ (A ∈ 𝒜 ∧ C A ∈ 𝒜) := by rw [compress_family, mem_union, mem_compress_motion, mem_compress_remains] lemma compress_disjoint (i j : fin n) : disjoint (compress_remains i j 𝒜) (compress_motion i j 𝒜) := begin rw disjoint_left, intros A HA HB, rw mem_compress_motion at HB, rw mem_compress_remains at HA, exact HA.1 HB.1 end lemma inj_ish {i j : X} (A B : finset X) (hA : j ∈ A ∧ i ∉ A) (hY : j ∈ B ∧ i ∉ B) (Z : insert i (erase A j) = insert i (erase B j)) : A = B := begin ext x, split, all_goals { intro p, by_cases h₁: (x=j), {rw h₁, tauto}, have h₂: x ≠ i, {intro, rw a at p, tauto}, rw ext at Z, replace Z := Z x, simp only [mem_insert, mem_erase] at Z, tauto } end lemma compressed_size : (CC 𝒜).card = 𝒜.card := begin rw [compress_family, card_disjoint_union (compress_disjoint _ _), card_image_of_inj_on], rw [← card_disjoint_union, union_comm, filter_union_filter_neg_eq], rw [disjoint_iff_inter_eq_empty, inter_comm], apply filter_inter_filter_neg_eq, intros A HX Y HY Z, rw mem_filter at HX HY, rw compress at HX Z, split_ifs at HX Z, rw compress at HY Z, split_ifs at HY Z, refine inj_ish A Y h h_1 Z, tauto, tauto end lemma insert_erase_comm {i j : fin n} {A : finset X} (h : i ≠ j) : insert i (erase A j) = erase (insert i A) j := begin simp only [ext, mem_insert, mem_erase], intro x, split; intro p, cases p, split, rw p, all_goals {tauto}, end lemma compress_moved {i j : X} {A : finset X} (h₁ : A ∈ compress_family i j 𝒜) (h₂ : A ∉ 𝒜) : i ∈ A ∧ j ∉ A ∧ erase (insert j A) i ∈ 𝒜 := begin rw mem_compress at h₁, rcases h₁ with ⟨_, B, H, HB⟩ | _, rw compress at HB, split_ifs at HB, rw ← HB, refine ⟨mem_insert_self _ _, _, _⟩, rw mem_insert, intro, cases a, safe, apply not_mem_erase j B a, have: erase (insert j (insert i (erase B j))) i = B, rw [insert_erase_comm, insert_erase (mem_insert_of_mem h.1), erase_insert h.2], safe, rwa this, rw HB at H, tauto, tauto end lemma compress_held {i j : X} {A : finset X} (h₁ : j ∈ A) (h₂ : A ∈ compress_family i j 𝒜) : A ∈ 𝒜 := begin rw mem_compress at h₂, rcases h₂ with ⟨_, B, H, HB⟩ | _, rw ← HB at h₁, rw compress at HB h₁, split_ifs at HB h₁, rw mem_insert at h₁, cases h₁, safe, exfalso, apply not_mem_erase _ _ h₁, rwa ← HB, tauto end lemma compress_both {i j : X} {A : finset X} (h₁ : A ∈ compress_family i j 𝒜) (h₂ : j ∈ A) (h₃ : i ∉ A) : erase (insert i A) j ∈ 𝒜 := begin have: A ∈ 𝒜, apply compress_held ‹_› ‹_›, rw mem_compress at h₁, replace h₁ : C A ∈ 𝒜, tauto, rw compress at h₁, have: j ∈ A ∧ i ∉ A := ⟨h₂, h₃⟩, split_ifs at h₁, rwa ← insert_erase_comm, intro, rw a at *, tauto, end lemma compression_reduces_shadow : (∂ CC 𝒜).card ≤ (∂𝒜).card := begin set 𝒜' := CC 𝒜, suffices: (∂𝒜' \ ∂𝒜).card ≤ (∂𝒜 \ ∂𝒜').card, suffices z: card (∂𝒜' \ ∂𝒜 ∪ ∂𝒜' ∩ ∂𝒜) ≤ card (∂𝒜 \ ∂𝒜' ∪ ∂𝒜 ∩ ∂𝒜'), rwa [sdiff_union_inter, sdiff_union_inter] at z, rw [card_disjoint_union, card_disjoint_union, inter_comm], apply add_le_add_right ‹_›, any_goals { apply sdiff_inter_inter }, have q₁: ∀ B ∈ ∂𝒜' \ ∂𝒜, i ∈ B ∧ j ∉ B ∧ erase (insert j B) i ∈ ∂𝒜 \ ∂𝒜', intros B HB, obtain ⟨k, k'⟩: B ∈ ∂𝒜' ∧ B ∉ ∂𝒜 := mem_sdiff.1 HB, have m: ∀ y ∉ B, insert y B ∉ 𝒜, intros y _ _, apply k', rw mem_shadow', exact ⟨y, H, a⟩, rcases mem_shadow'.1 k with ⟨x, _, _⟩, have q := compress_moved ‹insert x B ∈ 𝒜'› (m _ ‹x ∉ B›), rw insert.comm at q, have: j ∉ B := q.2.1 ∘ mem_insert_of_mem, have: i ≠ j, safe, have: x ≠ i, intro a, rw a at *, rw [erase_insert] at q, exact m _ ‹j ∉ B› q.2.2, rw mem_insert, tauto, have: x ≠ j, intro a, rw a at q, exact q.2.1 (mem_insert_self _ _), have: i ∈ B := mem_of_mem_insert_of_ne q.1 ‹x ≠ i›.symm, refine ⟨‹_›, ‹_›, _⟩, rw mem_sdiff, split, rw mem_shadow', rw ← insert_erase_comm ‹x ≠ i› at q, refine ⟨x, _, q.2.2⟩, intro a, exact ‹x ∉ B› (mem_of_mem_insert_of_ne (mem_of_mem_erase a) ‹x ≠ j›), intro a, rw mem_shadow' at a, rcases a with ⟨y, yH, H⟩, have: y ≠ i, intro b, rw [b, insert_erase (mem_insert_of_mem ‹i ∈ B›)] at H, exact m _ ‹j ∉ B› (compress_held (mem_insert_self _ _) H), have: y ≠ j, rw [mem_erase, mem_insert] at yH, tauto, have: y ∉ B, rw [mem_erase, mem_insert] at yH, tauto, have: j ∈ insert y (erase (insert j B) i), finish, have: i ∉ insert y (erase (insert j B) i), finish, have := compress_both H ‹_› ‹_›, rw [insert.comm, ← insert_erase_comm ‹y ≠ j›, insert_erase (mem_insert_of_mem ‹i ∈ B›), erase_insert ‹j ∉ B›] at this, exact m _ ‹y ∉ B› ‹insert y B ∈ 𝒜›, set f := (λ (B : finset X), erase (insert j B) i), apply card_le_card_of_inj_on f, intros _ HB, exact (q₁ _ HB).2.2, intros B₁ HB₁ B₂ HB₂ f₁, have := q₁ B₁ HB₁, have := q₁ B₂ HB₂, rw ext at f₁, ext, split, all_goals { intro, have p := f₁ a, simp only [mem_erase, mem_insert] at p, by_cases (a = i), rw h, tauto, rw [and_iff_right h, and_iff_right h] at p, have z: j ∉ B₁ ∧ j ∉ B₂, tauto, have: a ≠ j, safe, tauto } end end end ij @[simp] lemma sdiff_empty {α : Type*} [decidable_eq α] (s : finset α) : s \ ∅ = s := empty_union s @[simp] lemma sdiff_idem {α : Type*} [decidable_eq α] (s t : finset α) : s \ t \ t = s \ t := by simp only [ext, mem_sdiff]; tauto lemma union_sdiff {α : Type*} [decidable_eq α] (s₁ s₂ t : finset α) : (s₁ ∪ s₂) \ t = s₁ \ t ∪ s₂ \ t := by simp only [ext, mem_sdiff, mem_union]; tauto lemma inter_union_self {α : Type*} [decidable_eq α] (s t : finset α) : s ∩ (t ∪ s) = s := by simp only [ext, mem_inter, mem_union]; tauto lemma union_sdiff_self {α : Type*} [decidable_eq α] (s t : finset α) : (s ∪ t) \ t = s \ t := by simp only [ext, mem_union, mem_sdiff]; tauto lemma sdiff_singleton_eq_erase {α : Type*} [decidable_eq α] (a : α) (s : finset α) : s \ finset.singleton a = erase s a := begin ext, rw [mem_erase, mem_sdiff, mem_singleton], tauto end lemma sdiff_union {α : Type*} [decidable_eq α] (s t₁ t₂ : finset α) : s \ (t₁ ∪ t₂) = (s \ t₁) ∩ (s \ t₂) := by simp only [ext, mem_union, mem_sdiff, mem_inter]; tauto lemma not_sure {α : Type*} [decidable_eq α] {s t : finset α} (h : t ⊆ s) : s ∪ t = s := by simp only [ext, mem_union]; tauto lemma new_thing {α : Type*} [decidable_eq α] {s t : finset α} : disjoint s t ↔ s \ t = s := begin split; intro p, rw disjoint_iff_inter_eq_empty at p, exact union_empty (s \ t) ▸ (p ▸ sdiff_union_inter s t), rw ← p, apply sdiff_disjoint end lemma disjoint_self_iff_empty {α : Type*} [decidable_eq α] (s : finset α) : disjoint s s ↔ s = ∅ := disjoint_self lemma sdiff_subset_left {α : Type*} [decidable_eq α] (s t : finset α) : s \ t ⊆ s := by have := sdiff_subset_sdiff (le_refl s) (empty_subset t); rwa sdiff_empty at this instance decidable_disjoint (U V : finset X) : decidable (disjoint U V) := dite (U ∩ V = ∅) (is_true ∘ disjoint_iff_inter_eq_empty.2) (is_false ∘ mt disjoint_iff_inter_eq_empty.1) lemma sum_lt_sum {α β : Type*} {s : finset α} {f g : α → β} [decidable_eq α] [ordered_cancel_comm_monoid β] : s ≠ ∅ → (∀x∈s, f x < g x) → s.sum f < s.sum g := begin apply finset.induction_on s, intro a, exfalso, apply a, refl, intros x s not_mem ih _ assump, rw sum_insert not_mem, rw sum_insert not_mem, apply lt_of_lt_of_le, rw add_lt_add_iff_right (s.sum f), apply assump x (mem_insert_self _ _), rw add_le_add_iff_left, by_cases (s = ∅), rw h, rw sum_empty, rw sum_empty, apply le_of_lt, apply ih h, intros x hx, apply assump, apply mem_insert_of_mem hx end namespace UV section variables (U V : finset X) -- We'll only use this when |U| = |V| and U ∩ V = ∅ def compress (U V : finset X) (A : finset X) := if disjoint U A ∧ (V ⊆ A) then (A ∪ U) \ V else A local notation `C` := compress U V lemma compress_size (A : finset X) (h₁ : disjoint U V) (h₂ : U.card = V.card) : (C A).card = A.card := begin rw compress, split_ifs, rw card_sdiff (subset.trans h.2 (subset_union_left _ _)), rw card_disjoint_union h.1.symm, rw h₂, apply nat.add_sub_cancel, refl end lemma compress_idem (A : finset X) : C (C A) = C A := begin rw [compress, compress], split_ifs, suffices: U = ∅, rw [this, union_empty, union_empty, sdiff_idem], have: U \ V = U := new_thing.1 (disjoint_of_subset_right h.2 h.1), rw ← disjoint_self_iff_empty, apply disjoint_of_subset_right (subset_union_right (A\V) _), rw [union_sdiff, ‹U \ V = U›] at h_1, tauto, refl, refl, end @[reducible] def compress_motion (𝒜 : finset (finset X)) : finset (finset X) := 𝒜.filter (λ A, C A ∈ 𝒜) @[reducible] def compress_remains (𝒜 : finset (finset X)) : finset (finset X) := (𝒜.filter (λ A, C A ∉ 𝒜)).image (λ A, C A) def compress_family (U V : finset X) (𝒜 : finset (finset X)) : finset (finset X) := compress_remains U V 𝒜 ∪ compress_motion U V 𝒜 local notation `CC` := compress_family U V lemma mem_compress_motion (A : finset X) : A ∈ compress_motion U V 𝒜 ↔ A ∈ 𝒜 ∧ C A ∈ 𝒜 := by rw mem_filter lemma mem_compress_remains (A : finset X) : A ∈ compress_remains U V 𝒜 ↔ A ∉ 𝒜 ∧ (∃ B ∈ 𝒜, C B = A) := begin simp [compress_remains], split; rintro ⟨p, q, r⟩, exact ⟨r ▸ q.2, p, ⟨q.1, r⟩⟩, exact ⟨q, ⟨r.1, r.2.symm ▸ p⟩, r.2⟩, end def is_compressed (𝒜 : finset (finset X)) : Prop := CC 𝒜 = 𝒜 lemma is_compressed_empty (𝒜 : finset (finset X)) : is_compressed ∅ ∅ 𝒜 := begin have q: ∀ (A : finset X), compress ∅ ∅ A = A, simp [compress], rw [is_compressed, compress_family], ext, rw mem_union, rw mem_compress_remains, rw mem_compress_motion, repeat {conv in (compress ∅ ∅ _) {rw q _}}, safe end lemma mem_compress {A : finset X} : A ∈ CC 𝒜 ↔ (A ∉ 𝒜 ∧ (∃ B ∈ 𝒜, C B = A)) ∨ (A ∈ 𝒜 ∧ C A ∈ 𝒜) := by rw [compress_family, mem_union, mem_compress_motion, mem_compress_remains] lemma compress_family_size (r : ℕ) (𝒜 : finset (finset X)) (h₁ : disjoint U V) (h₂ : U.card = V.card) (h₃ : is_layer 𝒜 r) : is_layer (CC 𝒜) r := begin intros A HA, rw mem_compress at HA, rcases HA with ⟨_, _, z₁, z₂⟩ | ⟨z₁, _⟩, rw ← z₂, rw compress_size _ _ _ h₁ h₂, all_goals {apply h₃ _ z₁} end lemma compress_family_idempotent (𝒜 : finset (finset X)) : CC (CC 𝒜) = CC 𝒜 := begin have: ∀ A ∈ compress_family U V 𝒜, compress U V A ∈ compress_family U V 𝒜, intros A HA, rw mem_compress at HA ⊢, rw [compress_idem, and_self], rcases HA with ⟨_, B, _, cB_eq_A⟩ | ⟨_, _⟩, left, rw ← cB_eq_A, refine ⟨_, B, ‹_›, _⟩; rw compress_idem, rwa cB_eq_A, right, assumption, have: filter (λ A, compress U V A ∉ compress_family U V 𝒜) (compress_family U V 𝒜) = ∅, rw ← filter_false (compress_family U V 𝒜), apply filter_congr, simpa, rw [compress_family, compress_remains, this, image_empty, union_comm, compress_motion, ← this], apply filter_union_filter_neg_eq (compress_family U V 𝒜) end lemma compress_disjoint (U V : finset X) : disjoint (compress_remains U V 𝒜) (compress_motion U V 𝒜) := begin rw disjoint_left, intros A HA HB, rw mem_compress_motion at HB, rw mem_compress_remains at HA, exact HA.1 HB.1 end lemma inj_ish {U V : finset X} (A B : finset X) (hA : disjoint U A ∧ V ⊆ A) (hB : disjoint U B ∧ V ⊆ B) (Z : (A ∪ U) \ V = (B ∪ U) \ V) : A = B := begin ext x, split, all_goals { intro p, by_cases h₁: (x ∈ V), { exact hB.2 h₁ <|> exact hA.2 h₁ }, have := mem_sdiff.2 ⟨mem_union_left U ‹_›, h₁⟩, rw Z at this <|> rw ← Z at this, rw [mem_sdiff, mem_union] at this, suffices: x ∉ U, tauto, apply disjoint_right.1 _ p, tauto } end lemma compressed_size : (CC 𝒜).card = 𝒜.card := begin rw [compress_family, card_disjoint_union (compress_disjoint _ _), card_image_of_inj_on], rw [← card_disjoint_union, union_comm, filter_union_filter_neg_eq], rw [disjoint_iff_inter_eq_empty, inter_comm], apply filter_inter_filter_neg_eq, intros A HX Y HY Z, rw mem_filter at HX HY, rw compress at HX Z, split_ifs at HX Z, rw compress at HY Z, split_ifs at HY Z, refine inj_ish A Y h h_1 Z, tauto, tauto end lemma compress_held {U V : finset X} {A : finset X} (h₁ : A ∈ compress_family U V 𝒜) (h₂ : V ⊆ A) (h₃ : U.card = V.card) : A ∈ 𝒜 := begin rw mem_compress at h₁, rcases h₁ with ⟨_, B, H, HB⟩ | _, rw compress at HB, split_ifs at HB, have: V = ∅, apply eq_empty_of_forall_not_mem, intros x xV, replace h₂ := h₂ xV, rw [← HB, mem_sdiff] at h₂, exact h₂.2 xV, have: U = ∅, rwa [← card_eq_zero, h₃, card_eq_zero], rw [‹U = ∅›, ‹V = ∅›, union_empty, sdiff_empty] at HB, rwa ← HB, rwa ← HB, tauto, end lemma compress_moved {U V : finset X} {A : finset X} (h₁ : A ∈ compress_family U V 𝒜) (h₂ : A ∉ 𝒜) : U ⊆ A ∧ disjoint V A ∧ (A ∪ V) \ U ∈ 𝒜 := begin rw mem_compress at h₁, rcases h₁ with ⟨_, B, H, HB⟩ | _, { rw compress at HB, split_ifs at HB, { rw ← HB at *, refine ⟨_, disjoint_sdiff, _⟩, have: disjoint U V := disjoint_of_subset_right h.2 h.1, rw union_sdiff, rw new_thing.1 this, apply subset_union_right _ _, rwa [sdiff_union_of_subset, union_sdiff_self, new_thing.1 h.1.symm], apply trans h.2 (subset_union_left _ _)}, { rw HB at *, tauto } }, tauto end lemma uncompressed_was_already_there {U V : finset X} {A : finset X} (h₁ : A ∈ compress_family U V 𝒜) (h₂ : V ⊆ A) (h₃ : disjoint U A) : (A ∪ U) \ V ∈ 𝒜 := begin rw mem_compress at h₁, have: disjoint U A ∧ V ⊆ A := ⟨h₃, h₂⟩, rcases h₁ with ⟨_, B, B_in_A, cB_eq_A⟩ | ⟨_, cA_in_A⟩, { by_cases a: (A ∪ U) \ V = A, have: U \ V = U := new_thing.1 (disjoint_of_subset_right h₂ h₃), have: U = ∅, rw ← disjoint_self_iff_empty, suffices: disjoint U (U \ V), rw ‹U \ V = U› at this, assumption, apply disjoint_of_subset_right (subset_union_right (A\V) _), rwa [← union_sdiff, a], have: V = ∅, rw ← disjoint_self_iff_empty, apply disjoint_of_subset_right h₂, rw ← a, apply disjoint_sdiff, simpa [a, cB_eq_A.symm, compress, ‹U = ∅›, ‹V = ∅›], have: compress U V A = (A ∪ U) \ V, rw compress, split_ifs, refl, exfalso, apply a, rw [← this, ← cB_eq_A, compress_idem] }, { rw compress at cA_in_A, split_ifs at cA_in_A, assumption } end lemma compression_reduces_shadow (h₁ : ∀ x ∈ U, ∃ y ∈ V, is_compressed (erase U x) (erase V y) 𝒜) (h₂ : U.card = V.card) : (∂ CC 𝒜).card ≤ (∂𝒜).card := begin set 𝒜' := CC 𝒜, suffices: (∂𝒜' \ ∂𝒜).card ≤ (∂𝒜 \ ∂𝒜').card, suffices z: card (∂𝒜' \ ∂𝒜 ∪ ∂𝒜' ∩ ∂𝒜) ≤ card (∂𝒜 \ ∂𝒜' ∪ ∂𝒜 ∩ ∂𝒜'), rwa [sdiff_union_inter, sdiff_union_inter] at z, rw [card_disjoint_union, card_disjoint_union, inter_comm], apply add_le_add_right ‹_›, any_goals { apply sdiff_inter_inter }, have q₁: ∀ B ∈ ∂𝒜' \ ∂𝒜, U ⊆ B ∧ disjoint V B ∧ (B ∪ V) \ U ∈ ∂𝒜 \ ∂𝒜', intros B HB, obtain ⟨k, k'⟩: B ∈ ∂𝒜' ∧ B ∉ ∂𝒜 := mem_sdiff.1 HB, have m: ∀ y ∉ B, insert y B ∉ 𝒜 := λ y H a, k' (mem_shadow'.2 ⟨y, H, a⟩), rcases mem_shadow'.1 k with ⟨x, _, _⟩, have q := compress_moved ‹insert x B ∈ 𝒜'› (m _ ‹x ∉ B›), have: disjoint V B := (disjoint_insert_right.1 q.2.1).2, have: disjoint V U := disjoint_of_subset_right q.1 q.2.1, have: V \ U = V, rwa ← new_thing, have: x ∉ U, intro a, rcases h₁ x ‹x ∈ U› with ⟨y, Hy, xy_comp⟩, apply m y (disjoint_left.1 ‹disjoint V B› Hy), rw is_compressed at xy_comp, have: (insert x B ∪ V) \ U ∈ compress_family (erase U x) (erase V y) 𝒜, rw xy_comp, exact q.2.2, have: ((insert x B ∪ V) \ U ∪ erase U x) \ erase V y ∈ 𝒜, apply uncompressed_was_already_there this _ (disjoint_of_subset_left (erase_subset _ _) disjoint_sdiff), rw [union_sdiff, ‹V \ U = V›], apply subset.trans (erase_subset _ _) (subset_union_right _ _), suffices: ((insert x B ∪ V) \ U ∪ erase U x) \ erase V y = insert y B, rwa ← this, by calc (((insert x B ∪ V) \ U) ∪ erase U x) \ erase V y = (((insert x B ∪ V) \ finset.singleton x ∪ erase U x) ∩ ((insert x B ∪ V) \ erase U x ∪ erase U x)) \ erase V y : by rw [← union_distrib_right, ← sdiff_union, union_singleton_eq_insert, insert_erase a] ... = (erase (insert x (B ∪ V)) x ∪ erase U x) ∩ (insert x B ∪ V) \ erase V y : by rw sdiff_union_of_subset (trans (erase_subset _ _) (trans q.1 (subset_union_left _ _))); rw insert_union; rw sdiff_singleton_eq_erase ... = (B ∪ erase U x ∪ V) ∩ (insert x B ∪ V) \ erase V y : begin rw erase_insert, rw union_right_comm, rw mem_union, exact (λ a_1, disjoint_left.1 ‹disjoint V U› (or.resolve_left a_1 ‹x ∉ B›) ‹x ∈ U›) end ... = (B ∪ V) \ erase V y : by rw ← union_distrib_right; congr; rw [not_sure (subset_insert_iff.1 q.1), inter_insert_of_not_mem ‹x ∉ B›, inter_self] ... = (insert y B ∪ erase V y) \ erase V y : by rw [← union_singleton_eq_insert, union_comm _ B, union_assoc, union_singleton_eq_insert, insert_erase ‹y ∈ V›] ... = insert y B : begin rw [union_sdiff_self, ← new_thing, disjoint_insert_left], refine ⟨not_mem_erase _ _, disjoint_of_subset_right (erase_subset _ _) ‹disjoint V B›.symm⟩ end, have: U ⊆ B, rw [← erase_eq_of_not_mem ‹x ∉ U›, ← subset_insert_iff], exact q.1, refine ⟨‹_›, ‹_›, _⟩, rw mem_sdiff, have: x ∉ V := disjoint_right.1 q.2.1 (mem_insert_self _ _), split, rw mem_shadow', refine ⟨x, _, _⟩, { simp [mem_sdiff, mem_union], safe }, have: insert x ((B ∪ V) \ U) = (insert x B ∪ V) \ U, simp [ext, mem_sdiff, mem_union, mem_insert], intro a, split; intro p, cases p, rw p at *, tauto, tauto, tauto, rw this, tauto, rw mem_shadow', rintro ⟨w, _, _⟩, by_cases (w ∈ U), rcases h₁ w ‹w ∈ U› with ⟨z, Hz, xy_comp⟩, apply m z (disjoint_left.1 ‹disjoint V B› Hz), have: insert w ((B ∪ V) \ U) ∈ 𝒜, { apply compress_held a_h_h _ h₂, apply subset.trans _ (subset_insert _ _), rw union_sdiff, rw ‹V \ U = V›, apply subset_union_right }, have: (insert w ((B ∪ V) \ U) ∪ erase U w) \ erase V z ∈ 𝒜, refine uncompressed_was_already_there _ _ _, rw is_compressed at xy_comp, rwa xy_comp, apply subset.trans (erase_subset _ _), apply subset.trans _ (subset_insert _ _), rw union_sdiff, rw ‹V \ U = V›, apply subset_union_right, rw disjoint_insert_right, split, apply not_mem_erase, apply disjoint_of_subset_left (erase_subset _ _), apply disjoint_sdiff, have: (insert w ((B ∪ V) \ U) ∪ erase U w) \ erase V z = insert z B, by calc (insert w ((B ∪ V) \ U) ∪ erase U w) \ erase V z = (finset.singleton w ∪ ((B ∪ V) \ U) ∪ erase U w) \ erase V z : begin congr, end ... = (((B ∪ V) \ U) ∪ (finset.singleton w ∪ erase U w)) \ erase V z : begin rw [union_left_comm, union_assoc] end ... = (((B ∪ V) \ U) ∪ U) \ erase V z : begin congr, rw union_singleton_eq_insert, rw insert_erase h end ... = (B ∪ V) \ erase V z : begin rw sdiff_union_of_subset, apply subset.trans ‹U ⊆ B› (subset_union_left _ _) end ... = B \ erase V z ∪ V \ erase V z : begin rw union_sdiff end ... = B ∪ V \ erase V z : begin congr, rw ← new_thing, apply disjoint_of_subset_right (erase_subset _ _) ‹disjoint V B›.symm end ... = B ∪ finset.singleton z : begin congr, ext, simp, split, intro p, by_contra, exact p.2 ‹_› p.1, intro p, rw p, tauto end ... = insert z B : begin rw [union_comm, union_singleton_eq_insert] end, rwa ← this, have: w ∉ V, intro, have: w ∈ B ∪ V := mem_union_right _ ‹_›, exact a_h_w (mem_sdiff.2 ⟨‹_›, ‹_›⟩), have: w ∉ B, intro, have: w ∈ B ∪ V := mem_union_left _ ‹_›, exact a_h_w (mem_sdiff.2 ⟨‹_›, ‹_›⟩), apply m w this, have: (insert w ((B ∪ V) \ U) ∪ U) \ V ∈ 𝒜, refine uncompressed_was_already_there ‹insert w ((B ∪ V) \ U) ∈ 𝒜'› (trans _ (subset_insert _ _)) _, rw union_sdiff, rw ‹V \ U = V›, apply subset_union_right, rw disjoint_insert_right, exact ⟨‹_›, disjoint_sdiff⟩, suffices: insert w B = (insert w ((B ∪ V) \ U) ∪ U) \ V, rwa this, rw insert_union, rw sdiff_union_of_subset (trans ‹U ⊆ B› (subset_union_left _ _)), rw ← insert_union, rw union_sdiff_self, conv {to_lhs, rw ← sdiff_union_inter (insert w B) V}, suffices: insert w B ∩ V = ∅, rw this, rw union_empty, rw ← disjoint_iff_inter_eq_empty, rw disjoint_insert_left, split, assumption, rwa disjoint.comm, set f := (λ B, (B ∪ V) \ U), apply card_le_card_of_inj_on f (λ B HB, (q₁ B HB).2.2), intros B₁ HB₁ B₂ HB₂ k, exact inj_ish B₁ B₂ ⟨(q₁ B₁ HB₁).2.1, (q₁ B₁ HB₁).1⟩ ⟨(q₁ B₂ HB₂).2.1, (q₁ B₂ HB₂).1⟩ k end def bin_measure (A : finset X) : ℕ := A.sum (λ x, pow 2 x.val) lemma binary_sum (k : ℕ) (A : finset ℕ) (h₁ : ∀ x ∈ A, x < k) : A.sum (pow 2) < 2^k := begin apply lt_of_le_of_lt (sum_le_sum_of_subset (λ t th, mem_range.2 (h₁ t th))), have z := geom_sum_mul_add 1 k, rw [geom_series, mul_one] at z, simp only [nat.pow_eq_pow] at z, rw ← z, apply nat.lt_succ_self end lemma binary_sum' (k : ℕ) (A : finset X) (h₁ : ∀ (x : X), x ∈ A → x.val < k) : bin_measure A < 2^k := begin suffices: bin_measure A = (A.image (λ (x : X), x.val)).sum (pow 2), rw this, apply binary_sum, intros t th, rw mem_image at th, rcases th with ⟨_, _, _⟩, rw ← th_h_h, apply h₁ _ th_h_w, rw [bin_measure, sum_image], intros x _ y _, exact fin.eq_of_veq, end lemma bin_lt_of_maxdiff (A B : finset X) : (∃ (k : X), k ∉ A ∧ k ∈ B ∧ (∀ (x : X), x > k → (x ∈ A ↔ x ∈ B))) → bin_measure A < bin_measure B := begin rintro ⟨k, notinA, inB, maxi⟩, have AeqB: A.filter (λ x, ¬(x ≤ k)) = B.filter (λ x, ¬(x ≤ k)), { ext t, rw [mem_filter, mem_filter], by_cases h: (t > k); simp [h], apply maxi, exact h }, { have Alt: (A.filter (λ x, x ≤ k)).sum (λ x, pow 2 x.val) < pow 2 k.1, rw ← bin_measure, apply binary_sum', intro t, rw mem_filter, intro b, cases lt_or_eq_of_le b.2, exact h, rw h at b, exfalso, exact notinA b.1, have leB: pow 2 k.1 ≤ (B.filter (λ x, x ≤ k)).sum (λ x, pow 2 x.val), apply @single_le_sum _ _ (B.filter (λ x, x ≤ k)) (λ (x : fin n), 2 ^ x.val) _ _ (λ x _, zero_le _) k, rw mem_filter, exact ⟨inB, le_refl _⟩, have AltB: (A.filter (λ x, x ≤ k)).sum (λ x, pow 2 x.val) < (B.filter (λ x, x ≤ k)).sum (λ x, pow 2 x.val) := lt_of_lt_of_le Alt leB, have := nat.add_lt_add_right AltB (sum (filter (λ (x : fin n), ¬(x ≤ k)) A) (λ (x : fin n), 2 ^ x.val)), rwa [← sum_union, filter_union_filter_neg_eq, AeqB, ← sum_union, filter_union_filter_neg_eq, ← bin_measure, ← bin_measure] at this, rw disjoint_iff_inter_eq_empty, apply filter_inter_filter_neg_eq, rw disjoint_iff_inter_eq_empty, apply filter_inter_filter_neg_eq } end lemma bin_iff (A B : finset X) : bin_measure A < bin_measure B ↔ ∃ (k : X), k ∉ A ∧ k ∈ B ∧ (∀ (x : X), x > k → (x ∈ A ↔ x ∈ B)) := begin split, intro p, set differ := (elems X).filter (λ x, ¬ (x ∈ A ↔ x ∈ B)), have h: differ ≠ ∅, intro q, suffices: A = B, rw this at p, exact irrefl _ p, ext a, by_contra z, have: differ ≠ ∅ := ne_empty_of_mem (mem_filter.2 ⟨complete _, z⟩), exact this q, set k := max' differ h, use k, have z: ∀ (x : fin n), x > k → (x ∈ A ↔ x ∈ B), intros t th, by_contra, apply not_le_of_gt th, apply le_max', simpa [complete], rw ← and.rotate, refine ⟨z, _⟩, have el: (k ∈ A ∧ k ∉ B) ∨ (k ∉ A ∧ k ∈ B), have := max'_mem differ h, rw mem_filter at this, tauto, apply or.resolve_left el, intro, apply not_lt_of_gt p (bin_lt_of_maxdiff B A ⟨k, a.2, a.1, λ x xh, (z x xh).symm⟩), exact bin_lt_of_maxdiff _ _, end -- here lemma bin_measure_inj (A B : finset X) : bin_measure A = bin_measure B → A = B := begin intro p, set differ := (elems X).filter (λ x, ¬ (x ∈ A ↔ x ∈ B)), by_cases h: (differ = ∅), ext a, by_contra z, have: differ ≠ ∅ := ne_empty_of_mem (mem_filter.2 ⟨complete _, z⟩), exact this h, set k := max' differ h, have el: (k ∈ A ∧ k ∉ B) ∨ (k ∉ A ∧ k ∈ B), have := max'_mem differ h, rw mem_filter at this, tauto, exfalso, cases el, apply not_le_of_gt ((bin_iff B A).2 ⟨k, el.2, el.1, _⟩) (le_of_eq p), swap, apply not_le_of_gt ((bin_iff A B).2 ⟨k, el.1, el.2, _⟩) (ge_of_eq p), all_goals { intros x xh, by_contra, apply not_le_of_gt xh, apply le_max', simp only [complete, true_and, mem_filter], tauto }, end def c_measure (𝒜 : finset (finset X)) : ℕ := 𝒜.sum bin_measure lemma compression_reduces_bin_measure {U V : finset X} (hU : U ≠ ∅) (hV : V ≠ ∅) (A : finset X) (h : max' U hU < max' V hV) : compress U V A ≠ A → bin_measure (compress U V A) < bin_measure A := begin intro a, rw compress at a ⊢, split_ifs at a ⊢, { rw bin_measure, rw bin_measure, rw ← add_lt_add_iff_right, have q : V ⊆ (A ∪ U) := trans h_1.2 (subset_union_left _ _), rw sum_sdiff q, rw [sum_union h_1.1.symm, add_lt_add_iff_left], set kV := (max' V hV).1, set kU := (max' U hU).1, have a3: 2^kV ≤ sum V (λ (x : fin n), pow 2 x.val) := @single_le_sum _ _ V (λ x, pow 2 x.val) _ _ (λ t _, zero_le _) _ (max'_mem V hV), have a1: sum U (λ (x : fin n), 2 ^ x.val) < 2^(kU+1), { rw ← bin_measure, apply binary_sum', intros x hx, rw nat.lt_succ_iff, apply le_max' U _ _ hx }, have a2: kU + 1 ≤ kV, exact h, apply lt_of_lt_of_le a1, transitivity (2^kV), rwa nat.pow_le_iff_le_right (le_refl 2), assumption }, { exfalso, apply a, refl } end def compression_reduces_measure (U V : finset X) (hU : U ≠ ∅) (hV : V ≠ ∅) (h : max' U hU < max' V hV) (𝒜 : finset (finset X)) : compress_family U V 𝒜 ≠ 𝒜 → c_measure (compress_family U V 𝒜) < c_measure 𝒜 := begin rw [compress_family], intro, rw [c_measure, c_measure, sum_union (compress_disjoint U V)], conv {to_rhs, rw ← @filter_union_filter_neg_eq _ (λ A, C A ∈ 𝒜) _ _ 𝒜, rw sum_union (disjoint_iff_inter_eq_empty.2 (filter_inter_filter_neg_eq _)) }, rw [add_comm, add_lt_add_iff_left, sum_image], apply sum_lt_sum, { intro a₁, rw [compress_remains, compress_motion, a₁, image_empty, empty_union] at a, apply a, conv_rhs {rw ← @filter_union_filter_neg_eq _ (λ A, C A ∈ 𝒜) _ _ 𝒜}, conv {to_lhs, rw ← union_empty (filter _ 𝒜)}, symmetry, rw ← a₁ }, intros A HA, apply compression_reduces_bin_measure _ _ _ h, intro a₁, rw [mem_filter, a₁] at HA, tauto, intros x Hx y Hy k, rw mem_filter at Hx Hy, have cx: compress U V x ≠ x, intro b, rw b at Hx, tauto, have cy: compress U V y ≠ y, intro b, rw b at Hy, tauto, rw compress at k Hx cx, split_ifs at k Hx cx, rw compress at k Hy cy, split_ifs at k Hy cy, apply inj_ish x y h_1 h_2 k, tauto, tauto, end def gamma : rel (finset X) (finset X) := (λ U V, ∃ (HU : U ≠ ∅), ∃ (HV : V ≠ ∅), disjoint U V ∧ finset.card U = finset.card V ∧ max' U HU < max' V HV) lemma compression_improved {r : ℕ} (U V : finset X) (𝒜 : finset (finset X)) (h : is_layer 𝒜 r) (h₁ : gamma U V) (h₂ : ∀ U₁ V₁, gamma U₁ V₁ ∧ U₁.card < U.card → is_compressed U₁ V₁ 𝒜) (h₃ : ¬ is_compressed U V 𝒜): c_measure (compress_family U V 𝒜) < c_measure 𝒜 ∧ (compress_family U V 𝒜).card = 𝒜.card ∧ is_layer (compress_family U V 𝒜) r ∧ (∂ compress_family U V 𝒜).card ≤ (∂𝒜).card := begin rcases h₁ with ⟨Uh, Vh, UVd, same_size, max_lt⟩, refine ⟨compression_reduces_measure U V Uh Vh max_lt _ h₃, compressed_size _ _, _, _⟩, apply' compress_family_size _ _ _ _ UVd same_size h, apply compression_reduces_shadow U V _ same_size, intros x Hx, refine ⟨min' V Vh, min'_mem _ _, _⟩, by_cases p: (2 ≤ U.card), { apply h₂, refine ⟨⟨_, _, _, _, _⟩, card_erase_lt_of_mem Hx⟩, { rwa [← card_pos, card_erase_of_mem Hx, nat.lt_pred_iff] }, { rwa [← card_pos, card_erase_of_mem (min'_mem _ _), ← same_size, nat.lt_pred_iff] }, { apply disjoint_of_subset_left (erase_subset _ _), apply disjoint_of_subset_right (erase_subset _ _), assumption }, { rw [card_erase_of_mem (min'_mem _ _), card_erase_of_mem Hx, same_size] }, { have: max' (erase U _) _ ≤ max' U Uh := max'_le _ _ _ (λ y Hy, le_max' _ Uh _ (mem_of_mem_erase Hy)), apply lt_of_le_of_lt this, apply lt_of_lt_of_le max_lt, apply le_max', rw mem_erase, refine ⟨_, max'_mem _ _⟩, intro, rw same_size at p, apply not_le_of_gt p, apply le_of_eq, rw card_eq_one, use max' V Vh, rw eq_singleton_iff_unique_mem, refine ⟨max'_mem _ _, λ t Ht, _⟩, apply le_antisymm, apply le_max' _ _ _ Ht, rw a, apply min'_le _ _ _ Ht } }, rw ← card_pos at Uh, replace p: card U = 1 := le_antisymm (le_of_not_gt p) Uh, rw p at same_size, have: erase U x = ∅, rw [← card_eq_zero, card_erase_of_mem Hx, p], refl, have: erase V (min' V Vh) = ∅, rw [← card_eq_zero, card_erase_of_mem (min'_mem _ _), ← same_size], refl, rw [‹erase U x = ∅›, ‹erase V (min' V Vh) = ∅›], apply is_compressed_empty end instance thing (U V : finset X) : decidable (gamma U V) := by rw gamma; apply_instance instance thing2 (U V : finset X) (A : finset (finset X)) : decidable (is_compressed U V A) := by rw is_compressed; apply_instance lemma kruskal_katona_helper (r : ℕ) (𝒜 : finset (finset X)) (h : is_layer 𝒜 r) : ∃ (ℬ : finset (finset X)), (∂ℬ).card ≤ (∂𝒜).card ∧ 𝒜.card = ℬ.card ∧ is_layer ℬ r ∧ (∀ U V, gamma U V → is_compressed U V ℬ) := begin refine @well_founded.recursion _ _ (measure_wf c_measure) (λ (A : finset (finset X)), is_layer A r → ∃ B, (∂B).card ≤ (∂A).card ∧ A.card = B.card ∧ is_layer B r ∧ ∀ (U V : finset X), gamma U V → is_compressed U V B) _ _ h, intros A ih z, set usable: finset (finset X × finset X) := filter (λ t, gamma t.1 t.2 ∧ ¬ is_compressed t.1 t.2 A) ((powerset (elems X)).product (powerset (elems X))), by_cases (usable = ∅), refine ⟨A, le_refl _, rfl, z, _⟩, intros U V k, rw eq_empty_iff_forall_not_mem at h, by_contra, apply h ⟨U,V⟩, simp [a, k], exact ⟨subset_univ _, subset_univ _⟩, rcases exists_min usable (λ t, t.1.card) ((nonempty_iff_ne_empty _).2 h) with ⟨⟨U,V⟩, uvh, t⟩, rw mem_filter at uvh, have h₂: ∀ U₁ V₁, gamma U₁ V₁ ∧ U₁.card < U.card → is_compressed U₁ V₁ A, intros U₁ V₁ h, by_contra, apply not_le_of_gt h.2 (t ⟨U₁, V₁⟩ _), simp [h, a], exact ⟨subset_univ _, subset_univ _⟩, obtain ⟨small_measure, p2, layered, p1⟩ := compression_improved U V A z uvh.2.1 h₂ uvh.2.2, rw [measure, inv_image] at ih, rcases ih (compress_family U V A) small_measure layered with ⟨B, q1, q2, q3, q4⟩, exact ⟨B, trans q1 p1, trans p2.symm q2, q3, q4⟩ end def binary : finset X → finset X → Prop := inv_image (<) bin_measure local infix ` ≺ `:50 := binary instance : is_trichotomous (finset X) binary := ⟨ begin intros A B, rcases lt_trichotomy (bin_measure A) (bin_measure B) with lt|eq|gt, { left, exact lt }, { right, left, exact bin_measure_inj A B eq }, { right, right, exact gt } end ⟩ def is_init_seg_of_colex (𝒜 : finset (finset X)) (r : ℕ) : Prop := is_layer 𝒜 r ∧ (∀ A ∈ 𝒜, ∀ B, B ≺ A ∧ B.card = r → B ∈ 𝒜) lemma init_seg_total (𝒜₁ 𝒜₂ : finset (finset X)) (r : ℕ) (h₁ : is_init_seg_of_colex 𝒜₁ r) (h₂ : is_init_seg_of_colex 𝒜₂ r) : 𝒜₁ ⊆ 𝒜₂ ∨ 𝒜₂ ⊆ 𝒜₁ := begin rw ← sdiff_eq_empty_iff_subset, rw ← sdiff_eq_empty_iff_subset, by_contra a, rw not_or_distrib at a, simp [exists_mem_iff_ne_empty.symm, exists_mem_iff_ne_empty.symm] at a, rcases a with ⟨⟨A, Ah₁, Ah₂⟩, ⟨B, Bh₁, Bh₂⟩⟩, rcases trichotomous_of binary A B with lt | eq | gt, { exact Ah₂ (h₂.2 B Bh₁ A ⟨lt, h₁.1 A Ah₁⟩) }, { rw eq at Ah₁, exact Bh₂ Ah₁ }, { exact Bh₂ (h₁.2 A Ah₁ B ⟨gt, h₂.1 B Bh₁⟩) }, end lemma init_seg_of_compressed (ℬ : finset (finset X)) (r : ℕ) (h₁ : is_layer ℬ r) (h₂ : ∀ U V, gamma U V → is_compressed U V ℬ): is_init_seg_of_colex ℬ r := begin refine ⟨h₁, _⟩, rintros B Bh A ⟨A_lt_B, sizeA⟩, by_contra a, set U := A \ B, set V := B \ A, have: A ≠ B, intro t, rw t at a, exact a Bh, have: disjoint U B ∧ V ⊆ B := ⟨sdiff_disjoint, sdiff_subset_left _ _⟩, have: disjoint V A ∧ U ⊆ A := ⟨sdiff_disjoint, sdiff_subset_left _ _⟩, have cB_eq_A: compress U V B = A, { rw compress, split_ifs, rw [union_sdiff_self_eq_union, union_sdiff, new_thing.1 disjoint_sdiff, union_comm], apply not_sure, intro t, simp only [and_imp, not_and, mem_sdiff, not_not], exact (λ x y, y x) }, have cA_eq_B: compress V U A = B, { rw compress, split_ifs, rw [union_sdiff_self_eq_union, union_sdiff, new_thing.1 disjoint_sdiff, union_comm], apply not_sure, intro t, simp only [and_imp, not_and, mem_sdiff, not_not], exact (λ x y, y x) }, have: card A = card B := trans sizeA (h₁ B Bh).symm, have hU: U ≠ ∅, { intro t, rw sdiff_eq_empty_iff_subset at t, have: A = B := eq_of_subset_of_card_le t (ge_of_eq ‹_›), rw this at a, exact a Bh }, have hV: V ≠ ∅, { intro t, rw sdiff_eq_empty_iff_subset at t, have: B = A := eq_of_subset_of_card_le t (le_of_eq ‹_›), rw ← this at a, exact a Bh }, have disj: disjoint U V, { exact disjoint_of_subset_left (sdiff_subset_left _ _) disjoint_sdiff }, have smaller: max' U hU < max' V hV, { rcases lt_trichotomy (max' U hU) (max' V hV) with lt | eq | gt, { assumption }, { exfalso, have: max' U hU ∈ U := max'_mem _ _, apply disjoint_left.1 disj this, rw eq, exact max'_mem _ _ }, { exfalso, have z := compression_reduces_bin_measure hV hU A gt, rw cA_eq_B at z, apply irrefl (bin_measure B) (trans (z ‹A ≠ B›.symm) A_lt_B) }, }, have: gamma U V, { refine ⟨hU, hV, disj, _, smaller⟩, have: card (A \ B ∪ A ∩ B) = card (B \ A ∪ B ∩ A), rwa [sdiff_union_inter, sdiff_union_inter], rwa [card_disjoint_union (sdiff_inter_inter _ _), card_disjoint_union (sdiff_inter_inter _ _), inter_comm, add_right_inj] at this }, have Bcomp := h₂ U V this, rw is_compressed at Bcomp, suffices: compress U V B ∈ compress_family U V ℬ, rw [Bcomp, cB_eq_A] at this, exact a this, rw mem_compress, left, refine ⟨_, B, Bh, rfl⟩, rwa cB_eq_A, end lemma exists_max {α β : Type*} [decidable_linear_order α] (s : finset β) (f : β → α) (h : s ≠ ∅) : ∃ x ∈ s, ∀ x' ∈ s, f x' ≤ f x := begin have : s.image f ≠ ∅, rwa [ne, image_eq_empty, ← ne.def], cases max_of_ne_empty this with y hy, rcases mem_image.mp (mem_of_max hy) with ⟨x, hx, rfl⟩, exact ⟨x, hx, λ x' hx', le_max_of_mem (mem_image_of_mem f hx') hy⟩, end def everything_up_to (A : finset X) : finset (finset X) := filter (λ (B : finset X), A.card = B.card ∧ bin_measure B ≤ bin_measure A) (powerset (elems X)) lemma IS_iff_le_max (𝒜 : finset (finset X)) (r : ℕ) : 𝒜 ≠ ∅ ∧ is_init_seg_of_colex 𝒜 r ↔ ∃ (A : finset X), A ∈ 𝒜 ∧ A.card = r ∧ 𝒜 = everything_up_to A := begin rw is_init_seg_of_colex, split, { rintro ⟨ne, layer, IS⟩, rcases exists_max 𝒜 bin_measure ne with ⟨A, Ah, Ap⟩, refine ⟨A, Ah, layer A Ah, _⟩, ext B, rw [everything_up_to, mem_filter, mem_powerset], split; intro p, refine ⟨subset_univ _, _, _⟩, convert layer A Ah, apply layer B p, apply Ap _ p, cases lt_or_eq_of_le p.2.2 with h h, apply IS A Ah B ⟨h, trans p.2.1.symm (layer A Ah)⟩, rwa (bin_measure_inj _ _ h), }, { rintro ⟨A, Ah, Ac, Ap⟩, refine ⟨ne_empty_of_mem Ah, _, _⟩, intros B Bh, rw [Ap, everything_up_to, mem_filter] at Bh, exact (trans Bh.2.1.symm Ac), intros B₁ Bh₁ B₂ Bh₂, rw [Ap, everything_up_to, mem_filter, mem_powerset], refine ⟨_, _, _⟩, { apply subset_univ }, { exact (trans Ac Bh₂.2.symm) }, { rw [binary, inv_image] at Bh₂, transitivity, apply le_of_lt Bh₂.1, rw [Ap, everything_up_to, mem_filter] at Bh₁, exact Bh₁.2.2 } } end lemma up_to_is_IS (A : finset X) {r : ℕ} (h₁ : A.card = r) : is_init_seg_of_colex (everything_up_to A) r := and.right $ (IS_iff_le_max _ _).2 (by refine ⟨A, _, h₁, rfl⟩; rw [everything_up_to, mem_filter, mem_powerset]; refine ⟨subset_univ _, rfl, le_refl _⟩) lemma shadow_of_everything_up_to (A : finset X) (hA : A ≠ ∅) : ∂ (everything_up_to A) = everything_up_to (erase A (min' A hA)) := begin ext B, split, rw [mem_shadow', everything_up_to, everything_up_to, mem_filter, mem_powerset], rintro ⟨i, ih, p⟩, rw [mem_filter, card_insert_of_not_mem ih] at p, have cards: card (erase A (min' A hA)) = card B, rw [card_erase_of_mem (min'_mem _ _), p.2.1], refl, refine ⟨subset_univ _, cards, _⟩, cases lt_or_eq_of_le p.2.2 with h h, { rw bin_iff at h, rcases h with ⟨k, knotin, kin, h⟩, have: k ≠ i, rw mem_insert at knotin, tauto, cases lt_or_gt_of_ne this with h₁ h₁, have q: i ∈ A := (h _ h₁).1 (mem_insert_self _ _), apply le_of_lt, rw bin_iff, refine ⟨i, ih, _, _⟩, apply mem_erase_of_ne_of_mem _ q, apply ne_of_gt, apply lt_of_le_of_lt _ h₁, apply min'_le _ _ _ kin, intros x hx, have z := trans hx h₁, have := h _ z, simp at this ⊢, have a1: ¬x = min' A hA := ne_of_gt (lt_of_le_of_lt (min'_le _ hA _ q) hx), have a2: ¬x = i := ne_of_gt hx, tauto, cases lt_or_eq_of_le (min'_le _ hA _ kin), apply le_of_lt, rw bin_iff, refine ⟨k, mt mem_insert_of_mem knotin, mem_erase_of_ne_of_mem (ne_of_gt h_1) kin, _⟩, intros x hx, have := h _ hx, simp at this ⊢, have a1: ¬x = min' A hA := ne_of_gt (lt_of_le_of_lt (min'_le _ hA _ kin) hx), have a2: ¬x = i := ne_of_gt (trans hx h₁), tauto, apply le_of_eq, congr, have: erase A (min' A hA) ⊆ B, intros t th, rw mem_erase at th, have: t > k := h_1 ▸ (lt_of_le_of_ne (min'_le _ _ _ th.2) th.1.symm), apply mem_of_mem_insert_of_ne ((h t this).2 th.2) (ne_of_gt (trans this h₁)), symmetry, apply eq_of_subset_of_card_le this (le_of_eq cards.symm) }, { replace h := bin_measure_inj _ _ h, have z: i ∈ A, rw ← h, exact mem_insert_self _ _, rw [bin_measure, bin_measure, ← sdiff_singleton_eq_erase], rw ← add_le_add_iff_right (sum (finset.singleton i) (λ (x : fin n), 2 ^ x.val)), rw [← sum_union (disjoint_singleton.2 ih), union_comm, union_singleton_eq_insert, h], rw ← sum_sdiff (show finset.singleton (min' A hA) ⊆ A, by intro t; simp; intro th; rw th; exact min'_mem _ _), rw [add_le_add_iff_left, sum_singleton, sum_singleton], apply nat.pow_le_pow_of_le_right zero_lt_two, exact min'_le _ _ _ z }, intro p, rw [everything_up_to, mem_filter, mem_powerset] at p, simp only [mem_shadow', everything_up_to, mem_filter, mem_powerset], cases eq_or_lt_of_le p.2.2, have: B = erase A (min' A hA) := bin_measure_inj _ _ h, { rw this, refine ⟨min' A hA, not_mem_erase _ _, _⟩, rw insert_erase (min'_mem _ _), simp [le_refl], apply subset_univ }, rw bin_iff at h, rcases h with ⟨k, knotin, kin, h⟩, have kincomp := mem_sdiff.2 ⟨mem_univ _, knotin⟩, have jex: univ \ B ≠ ∅ := ne_empty_of_mem (mem_sdiff.2 ⟨mem_univ _, knotin⟩), set j := min' (univ \ B) jex, have jnotin: j ∉ B, have: j ∈ univ \ B := min'_mem _ _, rw mem_sdiff at this, tauto, have cards: card A = card (insert j B), { rw [card_insert_of_not_mem jnotin, ← p.2.1, card_erase_of_mem (min'_mem _ _), nat.pred_eq_sub_one, nat.sub_add_cancel], apply nat.pos_of_ne_zero, rw ne, rw card_eq_zero, exact hA }, refine ⟨j, jnotin, subset_univ _, cards, _⟩, cases eq_or_lt_of_le (min'_le _ jex _ kincomp) with h₁ h_1, { have: j = k, rw ← h₁, rw this at *, clear jnotin this j, suffices: insert k B = A, apply le_of_eq, rw this, symmetry, apply eq_of_subset_of_card_le, { intros t th, rcases lt_trichotomy t k with lt | rfl | gt, { apply mem_insert_of_mem, by_contra, have: t ∈ univ \ B, simpa, apply not_le_of_lt lt, rw ← h₁, apply min'_le _ _ _ this }, { apply mem_insert_self }, { apply mem_insert_of_mem, rw (h t gt), rw mem_erase, refine ⟨_, th⟩, apply ne_of_gt, apply lt_of_le_of_lt _ gt, apply min'_le, apply mem_of_mem_erase kin } }, { apply le_of_eq cards.symm } }, { apply le_of_lt, rw bin_iff, refine ⟨k, _, _, _⟩, { rw [mem_insert], have: j ≠ k := ne_of_lt h_1, tauto }, exact mem_of_mem_erase kin, intros x xh, have use := h x xh, have: x ≠ min' A hA := ne_of_gt (lt_of_le_of_lt (min'_le _ _ _ (mem_of_mem_erase kin)) xh), have: x ≠ j := ne_of_gt (trans xh h_1), simp at use ⊢, tauto } end -- kill the condition lemma shadow_of_IS {𝒜 : finset (finset X)} (r : ℕ) (h₁ : is_init_seg_of_colex 𝒜 r) : is_init_seg_of_colex (∂𝒜) (r - 1) := begin cases nat.eq_zero_or_pos r with h0 hr, have: 𝒜 ⊆ finset.singleton ∅, intros A hA, rw mem_singleton, rw ← card_eq_zero, rw ← h0, apply h₁.1 A hA, rw h0, simp, have := bind_sub_bind_of_sub_left this, rw [← shadow, singleton_bind, all_removals, image_empty, subset_empty] at this, rw this, split, rw [is_layer, forall_mem_empty_iff], trivial, rw forall_mem_empty_iff, trivial, by_cases h₂: 𝒜 = ∅, rw h₂, rw shadow, rw bind_empty, rw is_init_seg_of_colex, rw is_layer, rw forall_mem_empty_iff, rw forall_mem_empty_iff, simp, replace h₁ := and.intro h₂ h₁, rw IS_iff_le_max at h₁, rcases h₁ with ⟨B, _, Bcard, rfl⟩, rw shadow_of_everything_up_to, apply up_to_is_IS, rw card_erase_of_mem, rw Bcard, refl, apply min'_mem, rw ← card_pos, rw Bcard, exact hr end end end UV lemma killing {α : Type*} [decidable_eq α] (A : finset α) (i k : ℕ) (h₁ : card A = i + k) : ∃ (B : finset α), B ⊆ A ∧ card B = i := begin revert A, induction k with k ih, simp, intros A hA, use A, exact ⟨subset.refl _, hA⟩, intros A hA, have: ∃ i, i ∈ A, rw exists_mem_iff_ne_empty, rw ← ne, rw ← card_pos, rw hA, rw nat.add_succ, apply nat.succ_pos, rcases this with ⟨a, ha⟩, set A' := erase A a, have z: card A' = i + k, rw card_erase_of_mem ha, rw hA, rw nat.add_succ, rw nat.pred_succ, rcases ih A' z with ⟨B, hB, cardB⟩, refine ⟨B, _, cardB⟩, apply trans hB _, apply erase_subset end lemma killing2 {α : Type*} [decidable_eq α] (A B : finset α) (i k : ℕ) (h₁ : card A = i + k + card B) (h₂ : B ⊆ A) : ∃ (C : finset α), B ⊆ C ∧ C ⊆ A ∧ card C = i + card B := begin revert A, induction k with k ih, simp, intros A cards BsubA, refine ⟨A, BsubA, subset.refl _, cards⟩, intros A cards BsubA, have: ∃ i, i ∈ A \ B, rw exists_mem_iff_ne_empty, rw [← ne, ← card_pos, card_sdiff BsubA, cards, nat.add_sub_cancel, nat.add_succ], apply nat.succ_pos, rcases this with ⟨a, ha⟩, set A' := erase A a, have z: card A' = i + k + card B, rw card_erase_of_mem, rw cards, rw nat.add_succ, rw nat.succ_add, rw nat.pred_succ, rw mem_sdiff at ha, exact ha.1, rcases ih A' z _ with ⟨B', hB', B'subA', cards⟩, refine ⟨B', hB', trans B'subA' (erase_subset _ _), cards⟩, intros t th, apply mem_erase_of_ne_of_mem, intro, rw mem_sdiff at ha, rw a_1 at th, exact ha.2 th, exact BsubA th, end lemma killing2_sets {α : Type*} [decidable_eq α] (A B : finset α) (i : ℕ) (h₁ : card A ≥ i + card B) (h₂ : B ⊆ A) : ∃ (C : finset α), B ⊆ C ∧ C ⊆ A ∧ card C = i + card B := begin rcases nat.le.dest h₁, rw add_right_comm at h, apply killing2 A B i w h.symm h₂, end lemma kill_sets {α : Type*} [decidable_eq α] (A : finset α) (i : ℕ) (h₁ : card A ≥ i) : ∃ (B : finset α), B ⊆ A ∧ card B = i := begin rcases nat.le.dest h₁, apply killing A i w h.symm, end section KK theorem kruskal_katona (r : ℕ) (𝒜 𝒞 : finset (finset X)) : is_layer 𝒜 r ∧ is_layer 𝒞 r ∧ 𝒜.card = 𝒞.card ∧ UV.is_init_seg_of_colex 𝒞 r → (∂𝒞).card ≤ (∂𝒜).card := begin rintros ⟨layerA, layerC, h₃, h₄⟩, rcases UV.kruskal_katona_helper r 𝒜 layerA with ⟨ℬ, _, t, layerB, fully_comp⟩, have: UV.is_init_seg_of_colex ℬ r := UV.init_seg_of_compressed ℬ r layerB fully_comp, suffices: 𝒞 = ℬ, rwa this at *, have z: card ℬ = card 𝒞 := t.symm.trans h₃, cases UV.init_seg_total ℬ 𝒞 r this h₄ with BC CB, symmetry, apply eq_of_subset_of_card_le BC (ge_of_eq z), apply eq_of_subset_of_card_le CB (le_of_eq z) end theorem strengthened (r : ℕ) (𝒜 𝒞 : finset (finset X)) : is_layer 𝒜 r ∧ is_layer 𝒞 r ∧ 𝒞.card ≤ 𝒜.card ∧ UV.is_init_seg_of_colex 𝒞 r → (∂𝒞).card ≤ (∂𝒜).card := begin rintros ⟨Ar, Cr, cards, colex⟩, rcases kill_sets 𝒜 𝒞.card cards with ⟨𝒜', prop, size⟩, have := kruskal_katona r 𝒜' 𝒞 ⟨λ A hA, Ar _ (prop hA), Cr, size, colex⟩, transitivity, exact this, apply card_le_of_subset, rw [shadow, shadow], apply bind_sub_bind_of_sub_left prop end theorem lovasz_form {r k : ℕ} {𝒜 : finset (finset X)} (hr1 : r ≥ 1) (hkn : k ≤ n) (hrk : r ≤ k) (h₁ : is_layer 𝒜 r) (h₂ : 𝒜.card ≥ nat.choose k r) : (∂𝒜).card ≥ nat.choose k (r-1) := begin set range'k : finset X := attach_fin (range k) (λ m, by rw mem_range; apply forall_lt_iff_le.2 hkn), set 𝒞 : finset (finset X) := powerset_len r (range'k), have Ccard: 𝒞.card = nat.choose k r, rw [card_powerset_len, card_attach_fin, card_range], have: is_layer 𝒞 r, intros A HA, rw mem_powerset_len at HA, exact HA.2, suffices this: (∂𝒞).card = nat.choose k (r-1), { rw ← this, apply strengthened r _ _ ⟨h₁, ‹is_layer 𝒞 r›, _, _⟩, rwa Ccard, refine ⟨‹_›, _⟩, rintros A HA B ⟨HB₁, HB₂⟩, rw mem_powerset_len, refine ⟨_, ‹_›⟩, intros t th, rw mem_attach_fin, rw mem_range, by_contra, simp at a, rw [UV.binary, inv_image] at HB₁, apply not_le_of_gt HB₁, transitivity 2^k, apply le_of_lt, apply UV.binary_sum', intros x hx, rw mem_powerset_len at HA, exact mem_range.1 ((mem_attach_fin _).1 (HA.1 hx)), have: (λ (x : X), 2^x.val) t ≤ _ := single_le_sum _ th, transitivity, apply nat.pow_le_pow_of_le_right zero_lt_two a, rwa UV.bin_measure, intros _ _, apply zero_le }, suffices: ∂𝒞 = powerset_len (r-1) (range'k), rw [this, card_powerset_len, card_attach_fin, card_range], ext A, rw mem_powerset_len, split, rw mem_shadow, rintro ⟨B, Bh, i, ih, BA⟩, refine ⟨_, _⟩; rw ← BA; rw mem_powerset_len at Bh, intro j, rw mem_erase, intro a, exact Bh.1 a.2, rw [card_erase_of_mem ih, Bh.2], refl, rintro ⟨_, _⟩, rw mem_shadow', suffices: ∃ j, j ∈ range'k \ A, rcases this with ⟨j,jp⟩, rw mem_sdiff at jp, use j, use jp.2, rw mem_powerset_len, split, intros t th, rw mem_insert at th, cases th, rw th, exact jp.1, exact a_left th, rw [card_insert_of_not_mem jp.2, a_right, nat.sub_add_cancel hr1], apply exists_mem_of_ne_empty, rw ← card_pos, rw card_sdiff a_left, rw card_attach_fin, apply nat.lt_sub_left_of_add_lt, rw [card_range, a_right, add_zero], rw nat.sub_lt_right_iff_lt_add hr1, apply nat.lt_succ_of_le hrk, end theorem iterated (r k : ℕ) (𝒜 𝒞 : finset (finset X)) : is_layer 𝒜 r ∧ is_layer 𝒞 r ∧ 𝒞.card ≤ 𝒜.card ∧ UV.is_init_seg_of_colex 𝒞 r → (nat.iterate shadow k 𝒞).card ≤ (nat.iterate shadow k 𝒜).card := begin revert r 𝒜 𝒞, induction k, intros, simp, exact a.2.2.1, rintros r A C ⟨z₁, z₂, z₃, z₄⟩, simp, apply k_ih (r-1), refine ⟨shadow_layer z₁, shadow_layer z₂, _, _⟩, apply strengthened r _ _ ⟨z₁, z₂, z₃, z₄⟩, apply UV.shadow_of_IS _ z₄ end theorem lovasz_form_iterate {r k i : ℕ} {𝒜 : finset (finset X)} (hi1 : i ≥ 1) (hir : i < r) (hkn : k ≤ n) (hrk : r ≤ k) (h₁ : is_layer 𝒜 r) (h₂ : 𝒜.card ≥ nat.choose k r) : (nat.iterate shadow i 𝒜).card ≥ nat.choose k (r-i) := begin set range'k : finset X := attach_fin (range k) (λ m, by rw mem_range; apply forall_lt_iff_le.2 hkn), set 𝒞 : finset (finset X) := powerset_len r (range'k), have Ccard: 𝒞.card = nat.choose k r, rw [card_powerset_len, card_attach_fin, card_range], have: is_layer 𝒞 r, intros A HA, rw mem_powerset_len at HA, exact HA.2, suffices this: (nat.iterate shadow i 𝒞).card = nat.choose k (r-i), { rw ← this, apply iterated r _ _ _ ⟨h₁, ‹is_layer 𝒞 r›, _, _⟩, rwa Ccard, refine ⟨‹_›, _⟩, rintros A HA B ⟨HB₁, HB₂⟩, rw mem_powerset_len, refine ⟨_, ‹_›⟩, intros t th, rw mem_attach_fin, rw mem_range, by_contra, simp at a, rw [UV.binary, inv_image] at HB₁, apply not_le_of_gt HB₁, transitivity 2^k, apply le_of_lt, apply UV.binary_sum', intros x hx, rw mem_powerset_len at HA, exact mem_range.1 ((mem_attach_fin _).1 (HA.1 hx)), have: (λ (x : X), 2^x.val) t ≤ _ := single_le_sum _ th, transitivity, apply nat.pow_le_pow_of_le_right zero_lt_two a, rwa UV.bin_measure, intros _ _, apply zero_le }, suffices: nat.iterate shadow i 𝒞 = powerset_len (r-i) range'k, -- sub_iff_shadow_iter rw [this, card_powerset_len, card_attach_fin, card_range], ext B, rw mem_powerset_len, rw sub_iff_shadow_iter, split, rintro ⟨A, Ah, BsubA, card_sdiff_i⟩, rw mem_powerset_len at Ah, refine ⟨trans BsubA Ah.1, _⟩, symmetry, rw nat.sub_eq_iff_eq_add, rw ← Ah.2, rw ← card_sdiff_i, rw ← card_disjoint_union, rw union_sdiff_of_subset BsubA, apply disjoint_sdiff, apply le_of_lt hir, rintro ⟨_, _⟩, rcases killing2_sets _ _ i _ a_left with ⟨C, BsubC, Csubrange, cards⟩, rw [a_right, ← nat.add_sub_assoc (le_of_lt hir), nat.add_sub_cancel_left] at cards, refine ⟨C, _, BsubC, _⟩, rw mem_powerset_len, exact ⟨Csubrange, cards⟩, rw card_sdiff BsubC, rw cards, rw a_right, rw nat.sub_sub_self (le_of_lt hir), rw a_right, rw card_attach_fin, rw card_range, rw ← nat.add_sub_assoc (le_of_lt hir), rwa nat.add_sub_cancel_left, end end KK def intersecting (𝒜 : finset (finset X)) : Prop := ∀ A ∈ 𝒜, ∀ B ∈ 𝒜, ¬ disjoint A B theorem intersecting_all (h : intersecting 𝒜) : 𝒜.card ≤ 2^(n-1) := begin cases lt_or_le n 1 with b hn, have: n = 0, apply nat.eq_zero_of_le_zero (nat.pred_le_pred b), suffices: finset.card 𝒜 = 0, rw this, apply nat.zero_le, rw [card_eq_zero, eq_empty_iff_forall_not_mem], intros A HA, apply h A HA A HA, rw disjoint_self_iff_empty, apply eq_empty_of_forall_not_mem, intro x, rw this at x, exact (fin.elim0 ‹_›), set f : finset X → finset (finset X) := λ A, insert (univ \ A) (finset.singleton A), have disjs: ∀ x ∈ 𝒜, ∀ y ∈ 𝒜, x ≠ y → disjoint (f x) (f y), intros A hA B hB k, simp [not_or_distrib, and_assoc], refine ⟨_, _, _, _⟩, { intro z, apply k, ext a, simp [ext] at z, replace z := z a, tauto }, intro a, rw ← a at hA, apply h _ hB _ hA disjoint_sdiff, intro a, rw ← a at hB, apply h _ hB _ hA sdiff_disjoint, exact k.symm, have: 𝒜.bind f ⊆ powerset univ, intros A hA, rw mem_powerset, apply subset_univ, have q := card_le_of_subset this, rw [card_powerset, card_univ, card_fin] at q, rw card_bind disjs at q, dsimp at q, have: (λ (u : finset X), card (f u)) = (λ _, 2), funext, rw card_insert_of_not_mem, rw card_singleton, rw mem_singleton, intro, simp [ext] at a, apply a, exact ⟨0, hn⟩, rw this at q, rw sum_const at q, rw nat.smul_eq_mul at q, rw ← nat.le_div_iff_mul_le' zero_lt_two at q, conv_rhs at q {rw ← nat.sub_add_cancel hn}, rw nat.pow_add at q, simp at q, assumption, end @[reducible] def extremal_intersecting (hn : n ≥ 1) : finset (finset X) := (powerset univ).filter (λ A, (⟨0, hn⟩: X) ∈ A) lemma thing {hn : n ≥ 1} : intersecting (extremal_intersecting hn) := by intros A HA B HB k; rw [mem_filter] at HA HB; exact disjoint_left.1 k HA.2 HB.2 #print thing
532556c6cb3288a7fa48f6c3c2d8a0161402e4cd
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/assertAfterBug.lean
b84f7a8df5e9efc15816e8d445acd156a56a813d
[ "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
2,034
lean
inductive Expr where | var (i : Nat) | op (lhs rhs : Expr) deriving Inhabited, Repr def List.getIdx : List α → Nat → α → α | [], i, u => u | a::as, 0, u => a | a::as, i+1, u => getIdx as i u structure Context (α : Type u) where op : α → α → α unit : α assoc : (a b c : α) → op (op a b) c = op a (op b c) comm : (a b : α) → op a b = op b a vars : List α theorem Context.left_comm (ctx : Context α) (a b c : α) : ctx.op a (ctx.op b c) = ctx.op b (ctx.op a c) := by rw [← ctx.assoc, ctx.comm a b, ctx.assoc] def Expr.denote (ctx : Context α) : Expr → α | Expr.op a b => ctx.op (denote ctx a) (denote ctx b) | Expr.var i => ctx.vars.getIdx i ctx.unit theorem Expr.denote_op (ctx : Context α) (a b : Expr) : denote ctx (Expr.op a b) = ctx.op (denote ctx a) (denote ctx b) := rfl def Expr.length : Expr → Nat | op a b => 1 + b.length | _ => 1 def Expr.sort (e : Expr) : Expr := loop e.length e where loop : Nat → Expr → Expr | fuel+1, Expr.op a e => let (e₁, e₂) := swap a e Expr.op e₁ (loop fuel e₂) | _, e => e swap : Expr → Expr → Expr × Expr | Expr.var i, Expr.op (Expr.var j) e => if i > j then let (e₁, e₂) := swap (Expr.var j) e (e₁, Expr.op (Expr.var i) e₂) else let (e₁, e₂) := swap (Expr.var i) e (e₁, Expr.op (Expr.var j) e₂) | Expr.var i, Expr.var j => if i > j then (Expr.var j, Expr.var i) else (Expr.var i, Expr.var j) | e₁, e₂ => (e₁, e₂) theorem Expr.denote_swap (ctx : Context α) (e₁ e₂ : Expr) : denote ctx (Expr.op (sort.swap e₁ e₂).1 (sort.swap e₁ e₂).2) = denote ctx (Expr.op e₁ e₂) := by induction e₂ generalizing e₁ with | op a b ih' ih => cases e₁ with | var i => have ih' := ih (var i) match h:sort.swap (var i) b with | (r₁, r₂) => rw [denote_op _ (var i)] at ih' admit | _ => admit | _ => admit
509616ceee1bf8b49c9cb8ff488ec4257be11104
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/Elab/Tactic/Injection.lean
3eb666ad08f8850b7c84caa1dae592b02724f28f
[ "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
1,406
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.Meta.Tactic.Injection import Lean.Elab.Tactic.ElabTerm namespace Lean.Elab.Tactic -- optional (" with " >> many1 ident') private def getInjectionNewIds (stx : Syntax) : List Name := if stx.isNone then [] else stx[1].getArgs.toList.map getNameOfIdent' private def checkUnusedIds (mvarId : MVarId) (unusedIds : List Name) : MetaM Unit := unless unusedIds.isEmpty do Meta.throwTacticEx `injection mvarId m!"too many identifiers provided, unused: {unusedIds}" @[builtinTactic «injection»] def evalInjection : Tactic := fun stx => do -- leading_parser nonReservedSymbol "injection " >> termParser >> withIds let fvarId ← elabAsFVar stx[1] let ids := getInjectionNewIds stx[2] liftMetaTactic fun mvarId => do match (← Meta.injection mvarId fvarId ids) with | Meta.InjectionResult.solved => checkUnusedIds mvarId ids; return [] | Meta.InjectionResult.subgoal mvarId' _ unusedIds => checkUnusedIds mvarId unusedIds; return [mvarId'] @[builtinTactic «injections»] def evalInjections : Tactic := fun _ => do liftMetaTactic fun mvarId => do match (← Meta.injections mvarId) with | none => return [] | some mvarId => return [mvarId] end Lean.Elab.Tactic
66ee43b0ffa0d9d018fb7a3873d5e31b0037ec15
ce89339993655da64b6ccb555c837ce6c10f9ef4
/bluejam/chap4_exercise5.lean
b3a209f061cf8d7e9d3d1273298931e7248c1cde
[]
no_license
zeptometer/LearnLean
ef32dc36a22119f18d843f548d0bb42f907bff5d
bb84d5dbe521127ba134d4dbf9559b294a80b9f7
refs/heads/master
1,625,710,824,322
1,601,382,570,000
1,601,382,570,000
195,228,870
2
0
null
null
null
null
UTF-8
Lean
false
false
6,415
lean
open classical variables (α : Type) (p q : α → Prop) variable a : α variable r : Prop example : (∃ x : α, r) → r := assume h: ∃ x: α, r, exists.elim h ( assume w: α, assume hw: r, hw ) example : r → (∃ x : α, r) := assume h: r, exists.intro a h example : (∃ x, p x ∧ r) ↔ (∃ x, p x) ∧ r := iff.intro ( assume h: ∃ x, p x ∧ r, exists.elim h ( assume w: α, assume hw: p w ∧ r, and.intro (exists.intro w hw.left) hw.right ) ) ( assume h: (∃ x, p x) ∧ r, exists.elim h.left ( assume w: α, assume hw: p w, ⟨ w, (and.intro hw h.right)⟩ ) ) example : (∃ x, p x ∨ q x) ↔ (∃ x, p x) ∨ (∃ x, q x) := iff.intro ( assume h: ∃ x, p x ∨ q x, exists.elim h ( assume w: α, assume hw: p w ∨ q w, or.elim hw ( assume hwl: p w, have ∃ x, p x, from exists.intro w hwl, or.intro_left (∃ x, q x) this ) ( assume hwr: q w, have ∃ x, q x, from exists.intro w hwr, or.intro_right (∃ x, p x) this ) ) ) ( assume h: (∃ x, p x) ∨ (∃ x, q x), or.elim h ( assume hl: ∃ x, p x, exists.elim hl ( assume w: α, assume he: p w, ⟨ w, or.intro_left (q w) he ⟩ ) ) ( assume hr: ∃ x, q x, exists.elim hr ( assume w: α, assume he: q w, ⟨ w, or.intro_right (p w) he ⟩ ) ) ) -- right-to-left requires classical logic? example : (∀ x, p x) ↔ ¬ (∃ x, ¬ p x) := iff.intro ( assume h: ∀ x, p x, assume hn: ∃ x, ¬ p x, match hn with ⟨ w, hnw ⟩ := absurd (h w) hnw end ) ( assume h: ¬ (∃ x, ¬ p x), assume y: α, show p y, from ( by_contradiction ( assume hy: ¬ p y, have ∃ x, ¬ p x, from exists.intro y hy, absurd this h ) ) ) -- right-to-left requires classical logic? example : (∃ x, p x) ↔ ¬ (∀ x, ¬ p x) := iff.intro ( assume h: ∃ x, p x, assume hq: ∀ x, ¬ p x, match h with ⟨w, hw⟩ := absurd hw (hq w) end ) ( assume h: ¬ (∀ x, ¬ p x), by_contradiction ( assume hnp: ¬ (∃ x, p x), have ∀ x, ¬ p x, from ( assume y: α, show ¬ p y, from ( assume hy: p y, absurd (exists.intro y hy) hnp ) ), absurd this h ) ) example : (¬ ∃ x, p x) ↔ (∀ x, ¬ p x) := iff.intro ( assume h: ¬ ∃ x, p x, assume y: α, assume hpy: p y, have ∃ x, p x, from exists.intro y hpy, absurd this h ) ( assume h: ∀ x, ¬ p x, assume he: ∃ x, p x, match he with ⟨w, hw⟩ := absurd hw (h w) end ) -- left to right uses classical logic. But, it could be better...? theorem not_forall_exists_not : (¬ ∀ x, p x) ↔ (∃ x, ¬ p x) := iff.intro ( assume h: ¬ ∀ x, p x, by_contradiction ( assume hn: ¬ ∃ x, ¬ p x, have ∀ x, p x, from ( assume y: α, show p y, from by_contradiction ( assume hp: ¬ p y, have ∃ x, ¬ p x, from exists.intro y hp, absurd this hn ) ), absurd this h ) ) ( assume h: ∃ x, ¬ p x, assume hp: ∀ x, p x, match h with ⟨w, hw⟩ := absurd (hp w) hw end ) example : (∀ x, p x → r) ↔ (∃ x, p x) → r := iff.intro ( assume h: ∀ x, p x → r, assume he: ∃ x, p x, match he with ⟨w, hw⟩ := h w hw end ) ( assume h: (∃ x, p x) → r, assume y: α, assume hpy: p y, show r, from h (exists.intro y hpy) ) -- right-to-left requires classical logic? example : (∃ x, p x → r) ↔ (∀ x, p x) → r := iff.intro ( assume h1: ∃ x, p x → r, assume h2: ∀ x, p x, match h1 with ⟨w, hw⟩ := hw (h2 w) end ) ( assume h: (∀ x, p x) → r, by_cases ( assume hp: ∀ x, p x, have r, from h hp, have p a → r, from (assume hp: p a, ‹ r › ), exists.intro a this ) ( assume hnp: ¬ ∀ x, p x, have ∃ x, ¬ p x, from (not_forall_exists_not α p).mp hnp, match this with ⟨w, hnw⟩ := have p w → r, from ( assume hw: p w, absurd hw hnw ), exists.intro w this end ) ) -- right-to-left requires classical logic? example : (∃ x, r → p x) ↔ (r → ∃ x, p x) := iff.intro ( assume h: ∃ x, r → p x, assume hr: r, match h with ⟨w, hw⟩ := exists.intro w (hw hr) end ) ( assume h: (r → ∃ x, p x), by_cases ( assume hr: r, have ∃ x, p x, from h hr, match this with ⟨ w, hw ⟩ := exists.intro w ( assume hr2: r, show p w, from hw ) end ) ( assume hnr: ¬ r, have r → p a, from ( assume hr: r, absurd hr hnr ), exists.intro a this ) )
f0894b7893364794efc74f2921e0a26f8d8a3869
9ad8d18fbe5f120c22b5e035bc240f711d2cbd7e
/src/data/unique_element.lean
b1a92eec8c99c2f19503e5a3f78d995e3f051053
[]
no_license
agusakov/lean_lib
c0e9cc29fc7d2518004e224376adeb5e69b5cc1a
f88d162da2f990b87c4d34f5f46bbca2bbc5948e
refs/heads/master
1,642,141,461,087
1,557,395,798,000
1,557,395,798,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,846
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Neil Strickland In classical mathematics, if we prove that there is a unique element x with a certain property p x, then we can treat that as a valid definition of x and use x as a known entity in further developments. This does not work in quite the same way in Lean (unless we import classical logic.) The point is basically that Lean implements proof irrelevance, and so erases all details of the proof of unique existence of x, making the definition of x inaccessible to computation. However, if we have strong enough assumptions about finiteness and decidability, then these issues go away. The point of this file is to set up a framework for dealing with this kind of thing. In more detail, at the bottom of this file we will define a function fintype.witness. This accepts a decidable predicate p defined on a finite type α with decidable equality, together with a proof of (∃! x : α, p x), and it returns the relevant value of x, packaged together with a proof that it has the expected property. In building up to the definition of fintype.witness, we will define a number of other functions that play similar roles in various other contexts. -/ import data.nat.basic import data.list data.multiset data.finset data.fintype data.equiv.encodable universe u variables {α : Type u} namespace option /- Recall that a term xo of type (option α) is either (none), or (some x) for some x in α. This function accepts xo together with a proof that xo ≠ none. It returns the value x such that xo = (some x), packaged together with a proof of that property. Note that we have defined this function in the option namespace, so its full global name is option.unique_element. Later in this file we will define several other functions called unique_element, but they will all be in different namespaces, so their full global names will be list.unique_element, multiset.unique_element and so on. -/ def unique_element (xo : option α) (xo_some : xo ≠ none) : { x : α // xo = some x } := begin rcases xo with _ | x, exact false.elim (xo_some rfl), exact ⟨ x, rfl ⟩ end end option /- -------------------------------------------------------- -/ namespace list /- This function accepts a list xs of elements of α. If the list has length one, so it contains a unique element x, then this function returns the term (some x) of type (option α). In all other cases, it returns the term (none) of type (option α). -/ def maybe_unique_element (xs : list α) : (option α) := begin rcases xs with _ | ⟨ x , _ | ⟨ y, zs ⟩⟩, exact none, exact some x, exact none end /- A basic lemma saying that maybe_unique_element behaves as expected. -/ lemma maybe_unique_element_prop (xs : list α) (a : α) (e : maybe_unique_element xs = some a) : xs = [a] := begin rcases xs with _ | ⟨ x , _ | ⟨ y, zs ⟩⟩; try {dsimp[maybe_unique_element]}; try {dsimp[maybe_unique_element] at e}; injection e with e1; simp[e1] end /- Given that a list has length one, return its unique element, packaged with a proof of a key property. -/ def unique_element (xs : list α) (xs_length : xs.length = 1) : { x : α // xs = [x]} := begin rcases xs with _ | ⟨ x,ys ⟩, {simp at xs_length,exact false.elim xs_length}, { simp at xs_length, rw[nat.add_comm] at xs_length, have ys_length : ys.length = 0 := nat.succ_inj xs_length, have ys_nil : ys = [] := list.length_eq_zero.mp ys_length, simp[ys_nil], exact ⟨ x, rfl ⟩ } end /- Another basic lemma saying that maybe_unique_element behaves as expected. -/ lemma some_unique_element (xs : list α) : maybe_unique_element xs = none ↔ xs.length ≠ 1 := begin rcases xs with _ | ⟨ x , _ | ⟨ y, zs ⟩⟩; simp; dsimp[maybe_unique_element], refl, {intro h,injection h}, split, { intros u v, have Q : ∀ (k : ℕ ) , ¬1 + (1 + k) = 1 := begin intros k e, simp at e, injection e with e1,injection e1 end, exact Q zs.length v }, {intro,refl} end /- A list with no duplicates and a unique element has length one. -/ lemma length_one_of_prop (xs : list α) (nd : nodup xs) (u : ∃! a, a ∈ xs) : xs.length = 1 := begin rcases u with ⟨ a , a_in_xs , a_unique ⟩, rcases xs with _ | ⟨ x , _ | ⟨y , zs⟩⟩, {exact false.elim (list.ne_nil_of_mem a_in_xs rfl)}, {simp}, { have x_mem : x ∈ list.cons x (list.cons y zs) := or.inl rfl, have y_mem : y ∈ list.cons x (list.cons y zs) := or.inr (or.inl rfl), have x_eq_a : x = a := a_unique x x_mem, have y_eq_a : y = a := a_unique y y_mem, have x_eq_y : x = y := x_eq_a.trans y_eq_a.symm, have x_in_y_zs : x ∈ list.cons y zs := eq.subst x_eq_y (or.inl rfl), exact false.elim ((list.nodup_cons.mp nd).1 x_in_y_zs) } end /- Let as and bs be lists of elements of type α. The proposition (perm as bs) is defined inductively in mathlib in data.list.perm.lean; it means that bs is a permutation of as. If so, then maybe_unique_element takes the same values on as and bs, as we prove here. -/ lemma maybe_unique_element_perm (as bs : list α) (p : perm as bs) : (maybe_unique_element as) = (maybe_unique_element bs) := begin induction p, case list.perm.nil : {simp}, case list.perm.skip : x as1 bs1 q ih { rcases as1 with _ | ⟨ a1, as2 ⟩ , {have bs1_nil : bs1 = [] := list.eq_nil_of_perm_nil q, rw[bs1_nil]},{ rcases bs1 with _ | ⟨ b1, bs2 ⟩ , rcases list.eq_nil_of_perm_nil q.symm, dsimp[maybe_unique_element], refl } }, case list.perm.swap : x y cs { dsimp[maybe_unique_element],refl }, case list.perm.trans : cs ds es p_cd p_de ih_cd ih_de { exact eq.trans ih_cd ih_de } end end list /- -------------------------------------------------------- -/ namespace multiset /- A multiset is (by definition) a permutation-equivalence class of lists. Above we defined a function maybe_unique_element in the list namespace. We have now closed that namespace, so we need to use the name list.maybe_unique_element. We proved that that function is permutation invariant, so now we can define an induced function on multisets. We call the new function maybe_unique_element again, but now we are in the multiset namespace, so the full global name will be multiset.maybe_unique_element. -/ def maybe_unique_element : (multiset α) → (option α) := quotient.lift list.maybe_unique_element (@list.maybe_unique_element_perm α) /- We now prove compatibility with list.maybe_unique_element -/ lemma maybe_unique_element_of_list (l : list α) : maybe_unique_element ↑l = list.maybe_unique_element l := @quotient.lift_beta (list α) _ _ list.maybe_unique_element (@list.maybe_unique_element_perm α) l /- We now have two basic lemmas saying that the multiset version of maybe_unique_element behaves as expected. -/ lemma maybe_unique_element_prop (m : multiset α) (a : α) (e : maybe_unique_element m = some a) : m = [a] := begin rcases quotient.exists_rep m with ⟨ xs, xs_eq_m ⟩, have h : maybe_unique_element ⟦xs⟧ = list.maybe_unique_element xs := maybe_unique_element_of_list xs, rw[xs_eq_m,e] at h, have xs_eq_a : xs = [a] := list.maybe_unique_element_prop xs a h.symm, simp[xs_eq_a.symm], exact xs_eq_m.symm end lemma some_unique_element (m : multiset α) : maybe_unique_element m = none ↔ card m ≠ 1 := begin rcases quotient.exists_rep m with ⟨ as,e ⟩, rw[← e], simp[maybe_unique_element_of_list as], exact as.some_unique_element end /- Recall that the cardinality of any multiset is by definition the length of any representing list. Thus, we have the following obvious fact about multisets of cardinality one. -/ lemma eq_singleton (m : multiset α) (x : α) : m = [x] ↔ (m.card = 1 ∧ x ∈ m) := begin split, {intro m_eq_x,simp[m_eq_x]}, {intro e, rcases (exists_cons_of_mem e.2) with ⟨ t, m_eq_xt⟩ , have h : 1 = t.card + 1 := calc 1 = m.card : e.1.symm ... = (x :: t).card : by rw[m_eq_xt] ... = t.card + 1 : by simp, have t_eq_0 : t = 0 := card_eq_zero.mp (nat.succ_inj h).symm, simp[t_eq_0] at m_eq_xt, exact m_eq_xt } end /- This function extracts the unique element of any multiset of cardinality one, packaged together with a proof of its key property. -/ def unique_element (m : multiset α) (m_card : m.card = 1) : {x : α // m = [x]} := begin let xo := maybe_unique_element m, have xo_some : xo ≠ none := begin intro xo_none, exact (some_unique_element m).mp xo_none m_card end, rcases option.unique_element xo xo_some with ⟨ x, xox ⟩, have mx : m = [x] := maybe_unique_element_prop m x xox, exact ⟨ x , mx ⟩ end /- A multiset has cardinality one iff it has no duplicates and a unique element. -/ lemma card_one_of_prop (m : multiset α) (nd : nodup m) (u : ∃! a, a ∈ m) : m.card = 1 := begin rcases u with ⟨ a , a_in_m , a_unique_in_m ⟩, rcases quotient.exists_rep m with ⟨ xs, xs_eq_m ⟩, rw[← xs_eq_m] at a_in_m a_unique_in_m nd ⊢, simp, have xs_nd : list.nodup xs := coe_nodup.mp nd, have a_in_xs : a ∈ xs := mem_coe.mpr a_in_m, have a_unique_in_xs : ∀ x : α, ∀ (x_in_xs : x ∈ xs), x = a := begin intros, exact a_unique_in_m x (mem_coe.mp x_in_xs) end, exact list.length_one_of_prop xs xs_nd ⟨ a , a_in_xs , a_unique_in_xs ⟩ end end multiset /- -------------------------------------------------------- -/ namespace finset /- A finset is a multiset with no duplicates. We can restrict all our definitions and results for multisets, to get versions for finsets. -/ def maybe_unique_element (s : finset α) : (option α) := multiset.maybe_unique_element s.val lemma maybe_unique_element_prop (s : finset α) (a : α) (e : maybe_unique_element s = some a) : s = singleton a := begin apply finset.eq_of_veq, simp,dsimp[maybe_unique_element] at e, exact multiset.maybe_unique_element_prop s.val a e end lemma some_unique_element (s : finset α) : maybe_unique_element s = none ↔ s.card ≠ 1 := begin dsimp[maybe_unique_element,card], apply multiset.some_unique_element end lemma eq_singleton (s : finset α) (a : α) : s = singleton a ↔ (s.card = 1 ∧ a ∈ s) := begin split;intro e, {dsimp[card], let e1 := congr_arg finset.val e, simp at e1, simp[e1,e] },{ dsimp[card] at e, apply eq_of_veq, exact (multiset.eq_singleton s.val a).mpr ⟨ e.1 , finset.mem_def.mp e.2⟩, } end def unique_element (s : finset α) (s_card : s.card = 1) : {x : α // s = singleton x} := begin dsimp[card] at s_card, rcases (multiset.unique_element s.val s_card) with ⟨ x , e ⟩, have e1 : s = singleton x := eq_of_veq e, exact ⟨ x , e1 ⟩ end lemma card_one_of_prop (s : finset α) (h : ∃! x, x ∈ s) : s.card = 1 := begin dsimp[card], exact multiset.card_one_of_prop s.val s.nodup h end /- Suppose that we have a finset s and a decidable predicate p; we can then define a finset (s.filter p) consisting of elements of s where p is satisfied. The following function just applies our previous constructions to a finset of the form (s.filter p) and does a little associated bookkeeping. -/ def witness (s : finset α) (p : α → Prop) [decidable_pred p] (h : ∃! x, x ∈ s ∧ p x) : { a : α // s.filter p = singleton a} := begin let s1 := s.filter p, have h1 : ∃! x, x ∈ s1 := begin rcases h with ⟨ x , ⟨ x_in_s , p_x ⟩ , x_unique⟩, have x_in_s1 : x ∈ s1 := mem_filter.mpr ⟨ x_in_s , p_x ⟩, have x_unique_alt : ∀ y, y ∈ s1 → y = x := begin intros y y_in_s1, exact x_unique y (mem_filter.mp y_in_s1), end, exact ⟨ x , x_in_s1, x_unique_alt⟩ end, have s1_card : s1.card = 1 := card_one_of_prop s1 h1, exact unique_element s1 s1_card end end finset /- -------------------------------------------------------- -/ namespace fintype /- Recall that a fintype structure on α is a finset containing every element of α, and thus proving that α is finite. In this section we do some obvious adaptation of our results for general finsets, to put them in a more convenient form for use with fintypes. -/ open finset fintype variables (α) [fintype α] def maybe_unique_element : (option α) := finset.maybe_unique_element univ lemma maybe_unique_element_prop (a : α) (e : maybe_unique_element α = some a) : univ = finset.singleton a := maybe_unique_element_prop univ a e lemma some_unique_element : maybe_unique_element α = none ↔ card α ≠ 1 := finset.some_unique_element univ lemma eq_singleton (a : α) : univ = finset.singleton a ↔ (card α = 1) := begin dsimp[card], let e := finset.eq_singleton univ a, split, {intro u,exact (e.mp u).1}, {intro v,exact e.mpr ⟨ v , mem_univ a ⟩} end lemma card_one_of_prop (h : ∃ x : α, ∀ y : α, y = x) : card α = 1 := begin dsimp[card], have h1 : (∃! x : α , x ∈ (@univ α _)) := begin rcases h with ⟨ x , x_unique ⟩, let x_in_univ := @mem_univ α _ x, have x_unique_alt : ∀ y : α, y ∈ (@univ α _) → y = x := begin intros y y_in_univ, exact x_unique y end, exact ⟨ x , x_in_univ , x_unique_alt ⟩ end, exact finset.card_one_of_prop univ h1 end def witness (p : α → Prop) [decidable_pred p] (h : ∃! x, p x) : { a : α // univ.filter p = singleton a} := begin have h1 : ∃! x, x ∈ (@univ α _) ∧ p x := begin rcases h with ⟨ x , p_x , x_unique⟩, have x_prop : x ∈ univ ∧ p x := ⟨ mem_univ x , p_x ⟩, have x_unique_alt : ∀ y, y ∈ univ ∧ p y → y = x := λ y y_prop, x_unique y y_prop.2, exact ⟨ x , x_prop , x_unique_alt ⟩ end, exact finset.witness univ p h1, end end fintype
9c405d7c6f6b3fdcbcba4170b128a267fc29dc15
4b846d8dabdc64e7ea03552bad8f7fa74763fc67
/library/init/relator.lean
806bf5fa9b5770b0852d6855f0c4b49fc06a7b19
[ "Apache-2.0" ]
permissive
pacchiano/lean
9324b33f3ac3b5c5647285160f9f6ea8d0d767dc
fdadada3a970377a6df8afcd629a6f2eab6e84e8
refs/heads/master
1,611,357,380,399
1,489,870,101,000
1,489,870,101,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,159
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 Relator for functions, pairs, sums, and lists. -/ prelude import init.core init.data.basic namespace relator universe variables u₁ u₂ v₁ v₂ reserve infixr ` ⇒ `:40 /- TODO(johoelzl): * should we introduce relators of datatypes as recursive function or as inductive predicate? For now we stick to the recursor approach. * relation lift for datatypes, Π, Σ, set, and subtype types * proof composition and identity laws * implement method to derive relators from datatype -/ section variables {α : Type u₁} {β : Type u₂} {γ : Type v₁} {δ : Type v₂} variables (R : α → β → Prop) (S : γ → δ → Prop) def lift_fun (f : α → γ) (g : β → δ) : Prop := ∀{a b}, R a b → S (f a) (g b) infixr ⇒ := lift_fun end section variables {α : Type u₁} {β : out_param (Type u₂)} (R : out_param (α → β → Prop)) @[class] def right_total := ∀b, ∃a, R a b @[class] def left_total := ∀a, ∃b, R a b @[class] def bi_total := left_total R ∧ right_total R end section variables {α : Type u₁} {β : Type u₂} (R : α → β → Prop) @[class] def left_unique := ∀{a b c}, R a b → R c b → a = c @[class] def right_unique := ∀{a b c}, R a b → R a c → b = c lemma rel_forall_of_total [t : bi_total R] : ((R ⇒ iff) ⇒ iff) (λp, ∀i, p i) (λq, ∀i, q i) := take p q Hrel, ⟨take H b, exists.elim (t^.right b) (take a Rab, (Hrel Rab)^.mp (H _)), take H a, exists.elim (t^.left a) (take b Rab, (Hrel Rab)^.mpr (H _))⟩ lemma left_unique_of_rel_eq {eq' : β → β → Prop} (he : (R ⇒ (R ⇒ iff)) eq eq') : left_unique R | a b c (ab : R a b) (cb : R c b) := have eq' b b, from iff.mp (he ab ab) rfl, iff.mpr (he ab cb) this end lemma rel_imp : (iff ⇒ (iff ⇒ iff)) implies implies := take p q h r s l, imp_congr h l lemma rel_not : (iff ⇒ iff) not not := take p q h, not_congr h instance bi_total_eq {α : Type u₁} : relator.bi_total (@eq α) := ⟨take a, ⟨a, rfl⟩, take a, ⟨a, rfl⟩⟩ end relator
b9c20585dc25875456725b196af98d2179d37d86
9dc8cecdf3c4634764a18254e94d43da07142918
/src/algebra/star/pointwise.lean
15a65ea50044ad488c64d2fd42e8f548dc95a8df
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
4,237
lean
/- Copyright (c) 2022 Jireh Loreaux. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jireh Loreaux -/ import algebra.star.basic import data.set.pointwise /-! # Pointwise star operation on sets This file defines the star operation pointwise on sets and provides the basic API. Besides basic facts about about how the star operation acts on sets (e.g., `(s ∩ t)⋆ = s⋆ ∩ t⋆`), if `s t : set α`, then under suitable assumption on `α`, it is shown * `(s + t)⋆ = s⋆ + t⋆` * `(s * t)⋆ = t⋆ + s⋆` * `(s⁻¹)⋆ = (s⋆)⁻¹` -/ namespace set open_locale pointwise local postfix `⋆`:std.prec.max_plus := star variables {α : Type*} {s t : set α} {a : α} /-- The set `(star s : set α)` is defined as `{x | star x ∈ s}` in locale `pointwise`. In the usual case where `star` is involutive, it is equal to `{star s | x ∈ s}`, see `set.image_star`. -/ protected def has_star [has_star α] : has_star (set α) := ⟨preimage has_star.star⟩ localized "attribute [instance] set.has_star" in pointwise @[simp] lemma star_empty [has_star α] : (∅ : set α)⋆ = ∅ := rfl @[simp] lemma star_univ [has_star α] : (univ : set α)⋆ = univ := rfl @[simp] lemma nonempty_star [has_involutive_star α] {s : set α} : (s⋆).nonempty ↔ s.nonempty := star_involutive.surjective.nonempty_preimage lemma nonempty.star [has_involutive_star α] {s : set α} (h : s.nonempty) : (s⋆).nonempty := nonempty_star.2 h @[simp] lemma mem_star [has_star α] : a ∈ s⋆ ↔ a⋆ ∈ s := iff.rfl lemma star_mem_star [has_involutive_star α] : a⋆ ∈ s⋆ ↔ a ∈ s := by simp only [mem_star, star_star] @[simp] lemma star_preimage [has_star α] : has_star.star ⁻¹' s = s⋆ := rfl @[simp] lemma image_star [has_involutive_star α] : has_star.star '' s = s⋆ := by { simp only [← star_preimage], rw [image_eq_preimage_of_inverse]; intro; simp only [star_star] } @[simp] lemma inter_star [has_star α] : (s ∩ t)⋆ = s⋆ ∩ t⋆ := preimage_inter @[simp] lemma union_star [has_star α] : (s ∪ t)⋆ = s⋆ ∪ t⋆ := preimage_union @[simp] lemma Inter_star {ι : Sort*} [has_star α] (s : ι → set α) : (⋂ i, s i)⋆ = ⋂ i, (s i)⋆ := preimage_Inter @[simp] lemma Union_star {ι : Sort*} [has_star α] (s : ι → set α) : (⋃ i, s i)⋆ = ⋃ i, (s i)⋆ := preimage_Union @[simp] lemma compl_star [has_star α] : (sᶜ)⋆ = (s⋆)ᶜ := preimage_compl @[simp] instance [has_involutive_star α] : has_involutive_star (set α) := { star := has_star.star, star_involutive := λ s, by { simp only [← star_preimage, preimage_preimage, star_star, preimage_id'] } } @[simp] lemma star_subset_star [has_involutive_star α] {s t : set α} : s⋆ ⊆ t⋆ ↔ s ⊆ t := equiv.star.surjective.preimage_subset_preimage_iff lemma star_subset [has_involutive_star α] {s t : set α} : s⋆ ⊆ t ↔ s ⊆ t⋆ := by { rw [← star_subset_star, star_star] } lemma finite.star [has_involutive_star α] {s : set α} (hs : s.finite) : s⋆.finite := hs.preimage $ star_injective.inj_on _ lemma star_singleton {β : Type*} [has_involutive_star β] (x : β) : ({x} : set β)⋆ = {x⋆} := by { ext1 y, rw [mem_star, mem_singleton_iff, mem_singleton_iff, star_eq_iff_star_eq, eq_comm], } protected lemma star_mul [monoid α] [star_semigroup α] (s t : set α) : (s * t)⋆ = t⋆ * s⋆ := by simp_rw [←image_star, ←image2_mul, image_image2, image2_image_left, image2_image_right, star_mul, image2_swap _ s t] protected lemma star_add [add_monoid α] [star_add_monoid α] (s t : set α) : (s + t)⋆ = s⋆ + t⋆ := by simp_rw [←image_star, ←image2_add, image_image2, image2_image_left, image2_image_right, star_add] @[simp] instance [has_star α] [has_trivial_star α] : has_trivial_star (set α) := { star_trivial := λ s, by { rw [←star_preimage], ext1, simp [star_trivial] } } protected lemma star_inv [group α] [star_semigroup α] (s : set α) : (s⁻¹)⋆ = (s⋆)⁻¹ := by { ext, simp only [mem_star, mem_inv, star_inv] } protected lemma star_inv' [division_ring α] [star_ring α] (s : set α) : (s⁻¹)⋆ = (s⋆)⁻¹ := by { ext, simp only [mem_star, mem_inv, star_inv'] } end set
868d2d9d417a570f9b8e1a37afac32d37c7ee7e4
0d4c30038160d9c35586ce4dace36fe26a35023b
/src/data/fin.lean
80adb5f7613dfbe4e0cdb2ad4a539c4539cd21da
[ "Apache-2.0" ]
permissive
b-mehta/mathlib
b0c8ec929ec638447e4262f7071570d23db52e14
ce72cde867feabe5bb908cf9e895acc0e11bf1eb
refs/heads/master
1,599,457,264,781
1,586,969,260,000
1,586,969,260,000
220,672,634
0
0
Apache-2.0
1,583,944,480,000
1,573,317,991,000
Lean
UTF-8
Lean
false
false
28,029
lean
/- Copyright (c) 2017 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis, Keeley Hoek -/ import data.nat.basic /-! # The finite type with `n` elements `fin n` is the type whose elements are natural numbers smaller than `n`. This file expands on the development in the core library. ## Main definitions ### Induction principles * `fin_zero.elim` : Elimination principle for the empty set `fin 0`, generalizes `fin.elim0`. * `fin.succ_rec` : Define `C n i` by induction on `i : fin n` interpreted as `(0 : fin (n - i)).succ.succ…`. This function has two arguments: `H0 n` defines `0`-th element `C (n+1) 0` of an `(n+1)`-tuple, and `Hs n i` defines `(i+1)`-st element of `(n+1)`-tuple based on `n`, `i`, and `i`-th element of `n`-tuple. * `fin.succ_rec_on` : same as `fin.succ_rec` but `i : fin n` is the first argument; ### Casts * `cast_lt i h` : embed `i` into a `fin` where `h` proves it belongs into; * `cast_le h` : embed `fin n` into `fin m`, `h : n ≤ m`; * `cast eq` : embed `fin n` into `fin m`, `eq : n = m`; * `cast_add m` : embed `fin n` into `fin (n+m)`; * `cast_succ` : embed `fin n` into `fin (n+1)`; * `succ_above p` : embed `fin n` into `fin (n + 1)` with a hole around `p`; * `pred_above p i h` : embed `i : fin (n+1)` into `fin n` by ignoring `p`; * `sub_nat i h` : subtract `m` from `i ≥ m`, generalizes `fin.pred`; * `add_nat i h` : add `m` on `i` on the right, generalizes `fin.succ`; * `nat_add i h` adds `n` on `i` on the left; * `clamp n m` : `min n m` as an element of `fin (m + 1)`; ### Operation on tuples We interpret maps `Π i : fin n, α i` as tuples `(α 0, …, α (n-1))`. If `α i` is a constant map, then tuples are isomorphic (but not definitionally equal) to `vector`s. We define the following operations: * `tail` : the tail of an `n+1` tuple, i.e., its last `n` entries; * `cons` : adding an element at the beginning of an `n`-tuple, to get an `n+1`-tuple; * `init` : the beginning of an `n+1` tuple, i.e., its first `n` entries; * `snoc` : adding an element at the end of an `n`-tuple, to get an `n+1`-tuple. The name `snoc` comes from `cons` (i.e., adding an element to the left of a tuple) read in reverse order. * `find p` : returns the first index `n` where `p n` is satisfied, and `none` if it is never satisfied. ### Misc definitions * `fin.last n` : The greatest value of `fin (n+1)`. -/ universe u open fin nat function /-- Elimination principle for the empty set `fin 0`, dependent version. -/ def fin_zero_elim {α : fin 0 → Sort u} (x : fin 0) : α x := x.elim0 namespace fin variables {n m : ℕ} {a b : fin n} @[simp] protected lemma eta (a : fin n) (h : a.1 < n) : (⟨a.1, h⟩ : fin n) = a := by cases a; refl attribute [ext] eq_of_veq protected lemma ext_iff (a b : fin n) : a = b ↔ a.val = b.val := iff.intro (congr_arg _) fin.eq_of_veq lemma injective_val {n : ℕ} : injective (val : fin n → ℕ) := λ _ _, fin.eq_of_veq lemma eq_iff_veq (a b : fin n) : a = b ↔ a.1 = b.1 := ⟨veq_of_eq, eq_of_veq⟩ @[simp] protected lemma mk.inj_iff {n a b : ℕ} {ha : a < n} {hb : b < n} : fin.mk a ha = fin.mk b hb ↔ a = b := ⟨fin.mk.inj, λ h, by subst h⟩ instance fin_to_nat (n : ℕ) : has_coe (fin n) nat := ⟨fin.val⟩ lemma mk_val {m n : ℕ} (h : m < n) : (⟨m, h⟩ : fin n).val = m := rfl @[simp, elim_cast] lemma coe_mk {m n : ℕ} (h : m < n) : ((⟨m, h⟩ : fin n) : ℕ) = m := rfl lemma coe_eq_val (a : fin n) : (a : ℕ) = a.val := rfl attribute [simp] val_zero @[simp] lemma val_one {n : ℕ} : (1 : fin (n+2)).val = 1 := rfl @[simp] lemma val_two {n : ℕ} : (2 : fin (n+3)).val = 2 := rfl @[simp] lemma coe_zero {n : ℕ} : ((0 : fin (n+1)) : ℕ) = 0 := rfl @[simp] lemma coe_one {n : ℕ} : ((1 : fin (n+2)) : ℕ) = 1 := rfl @[simp] lemma coe_two {n : ℕ} : ((2 : fin (n+3)) : ℕ) = 2 := rfl /-- Assume `k = l`. If two functions defined on `fin k` and `fin l` are equal on each element, then they coincide (in the heq sense). -/ protected lemma heq_fun_iff {α : Type*} {k l : ℕ} (h : k = l) {f : fin k → α} {g : fin l → α} : f == g ↔ (∀ (i : fin k), f i = g ⟨i.val, h ▸ i.2⟩) := by { induction h, simp [heq_iff_eq, function.funext_iff] } protected lemma heq_ext_iff {k l : ℕ} (h : k = l) {i : fin k} {j : fin l} : i == j ↔ i.val = j.val := by { induction h, simp [fin.ext_iff] } instance {n : ℕ} : decidable_linear_order (fin n) := decidable_linear_order.lift fin.val (@fin.eq_of_veq _) (by apply_instance) lemma exists_iff {p : fin n → Prop} : (∃ i, p i) ↔ ∃ i h, p ⟨i, h⟩ := ⟨λ h, exists.elim h (λ ⟨i, hi⟩ hpi, ⟨i, hi, hpi⟩), λ h, exists.elim h (λ i hi, ⟨⟨i, hi.fst⟩, hi.snd⟩)⟩ lemma forall_iff {p : fin n → Prop} : (∀ i, p i) ↔ ∀ i h, p ⟨i, h⟩ := ⟨λ h i hi, h ⟨i, hi⟩, λ h ⟨i, hi⟩, h i hi⟩ lemma zero_le (a : fin (n + 1)) : 0 ≤ a := zero_le a.1 lemma lt_iff_val_lt_val : a < b ↔ a.val < b.val := iff.rfl lemma le_iff_val_le_val : a ≤ b ↔ a.val ≤ b.val := iff.rfl @[simp] lemma succ_val (j : fin n) : j.succ.val = j.val.succ := by cases j; simp [fin.succ] protected theorem succ.inj (p : fin.succ a = fin.succ b) : a = b := by cases a; cases b; exact eq_of_veq (nat.succ.inj (veq_of_eq p)) @[simp] lemma succ_inj {a b : fin n} : a.succ = b.succ ↔ a = b := ⟨λh, succ.inj h, λh, by rw h⟩ lemma injective_succ (n : ℕ) : injective (@fin.succ n) := λa b, succ.inj lemma succ_ne_zero {n} : ∀ k : fin n, fin.succ k ≠ 0 | ⟨k, hk⟩ heq := nat.succ_ne_zero k $ (fin.ext_iff _ _).1 heq @[simp] lemma pred_val (j : fin (n+1)) (h : j ≠ 0) : (j.pred h).val = j.val.pred := by cases j; simp [fin.pred] @[simp] lemma succ_pred : ∀(i : fin (n+1)) (h : i ≠ 0), (i.pred h).succ = i | ⟨0, h⟩ hi := by contradiction | ⟨n + 1, h⟩ hi := rfl @[simp] lemma pred_succ (i : fin n) {h : i.succ ≠ 0} : i.succ.pred h = i := by cases i; refl @[simp] lemma pred_inj : ∀ {a b : fin (n + 1)} {ha : a ≠ 0} {hb : b ≠ 0}, a.pred ha = b.pred hb ↔ a = b | ⟨0, _⟩ b ha hb := by contradiction | ⟨i+1, _⟩ ⟨0, _⟩ ha hb := by contradiction | ⟨i+1, hi⟩ ⟨j+1, hj⟩ ha hb := by simp [fin.eq_iff_veq] /-- The greatest value of `fin (n+1)` -/ def last (n : ℕ) : fin (n+1) := ⟨_, n.lt_succ_self⟩ /-- `cast_lt i h` embeds `i` into a `fin` where `h` proves it belongs into. -/ def cast_lt (i : fin m) (h : i.1 < n) : fin n := ⟨i.1, h⟩ /-- `cast_le h i` embeds `i` into a larger `fin` type. -/ def cast_le (h : n ≤ m) (a : fin n) : fin m := cast_lt a (lt_of_lt_of_le a.2 h) /-- `cast eq i` embeds `i` into a equal `fin` type. -/ def cast (eq : n = m) : fin n → fin m := cast_le $ le_of_eq eq /-- `cast_add m i` embeds `i : fin n` in `fin (n+m)`. -/ def cast_add (m) : fin n → fin (n + m) := cast_le $ le_add_right n m /-- `cast_succ i` embeds `i : fin n` in `fin (n+1)`. -/ def cast_succ : fin n → fin (n + 1) := cast_add 1 /-- `succ_above p i` embeds `fin n` into `fin (n + 1)` with a hole around `p`. -/ def succ_above (p : fin (n+1)) (i : fin n) : fin (n+1) := if i.1 < p.1 then i.cast_succ else i.succ /-- `pred_above p i h` embeds `i : fin (n+1)` into `fin n` by ignoring `p`. -/ def pred_above (p : fin (n+1)) (i : fin (n+1)) (hi : i ≠ p) : fin n := if h : i < p then i.cast_lt (lt_of_lt_of_le h $ nat.le_of_lt_succ p.2) else i.pred $ have p < i, from lt_of_le_of_ne (le_of_not_gt h) hi.symm, ne_of_gt (lt_of_le_of_lt (zero_le p) this) /-- `sub_nat i h` subtracts `m` from `i`, generalizes `fin.pred`. -/ def sub_nat (m) (i : fin (n + m)) (h : m ≤ i.val) : fin n := ⟨i.val - m, by simp [nat.sub_lt_right_iff_lt_add h, i.is_lt]⟩ /-- `add_nat i h` adds `m` on `i`, generalizes `fin.succ`. -/ def add_nat (m) (i : fin n) : fin (n + m) := ⟨i.1 + m, add_lt_add_right i.2 _⟩ /-- `nat_add i h` adds `n` on `i` -/ def nat_add (n) {m} (i : fin m) : fin (n + m) := ⟨n + i.1, add_lt_add_left i.2 _⟩ theorem le_last (i : fin (n+1)) : i ≤ last n := le_of_lt_succ i.is_lt @[simp] lemma cast_val (k : fin n) (h : n = m) : (fin.cast h k).val = k.val := rfl @[simp] lemma cast_succ_val (k : fin n) : k.cast_succ.val = k.val := rfl @[simp] lemma cast_lt_val (k : fin m) (h : k.1 < n) : (k.cast_lt h).val = k.val := rfl @[simp] lemma cast_le_val (k : fin m) (h : m ≤ n) : (k.cast_le h).val = k.val := rfl @[simp] lemma cast_add_val (k : fin m) : (k.cast_add n).val = k.val := rfl @[simp] lemma last_val (n : ℕ) : (last n).val = n := rfl @[simp, elim_cast] lemma coe_last {n : ℕ} : (last n : ℕ) = n := rfl @[simp] lemma succ_last (n : ℕ) : (last n).succ = last (n.succ) := rfl @[simp] lemma cast_succ_cast_lt (i : fin (n + 1)) (h : i.val < n) : cast_succ (cast_lt i h) = i := fin.eq_of_veq rfl @[simp] lemma cast_lt_cast_succ {n : ℕ} (a : fin n) (h : a.1 < n) : cast_lt (cast_succ a) h = a := by cases a; refl @[simp] lemma sub_nat_val (i : fin (n + m)) (h : m ≤ i.val) : (i.sub_nat m h).val = i.val - m := rfl @[simp] lemma add_nat_val (i : fin (n + m)) (h : m ≤ i.val) : (i.add_nat m).val = i.val + m := rfl @[simp] lemma cast_succ_inj {a b : fin n} : a.cast_succ = b.cast_succ ↔ a = b := by simp [eq_iff_veq] lemma cast_succ_ne_last (a : fin n) : cast_succ a ≠ last n := by simp [eq_iff_veq, ne_of_lt a.2] lemma eq_last_of_not_lt {i : fin (n+1)} (h : ¬ i.val < n) : i = last n := le_antisymm (le_last i) (not_lt.1 h) lemma cast_succ_fin_succ (n : ℕ) (j : fin n) : cast_succ (fin.succ j) = fin.succ (cast_succ j) := by simp [fin.ext_iff] /-- `min n m` as an element of `fin (m + 1)` -/ def clamp (n m : ℕ) : fin (m + 1) := fin.of_nat $ min n m @[simp] lemma clamp_val (n m : ℕ) : (clamp n m).val = min n m := nat.mod_eq_of_lt $ nat.lt_succ_iff.mpr $ min_le_right _ _ lemma injective_cast_le {n₁ n₂ : ℕ} (h : n₁ ≤ n₂) : injective (fin.cast_le h) | ⟨i₁, h₁⟩ ⟨i₂, h₂⟩ eq := fin.eq_of_veq $ show i₁ = i₂, from fin.veq_of_eq eq lemma injective_cast_succ (n : ℕ) : injective (@fin.cast_succ n) := injective_cast_le (le_add_right n 1) theorem succ_above_ne (p : fin (n+1)) (i : fin n) : p.succ_above i ≠ p := begin assume eq, unfold fin.succ_above at eq, split_ifs at eq with h; simpa [lt_irrefl, nat.lt_succ_self, eq.symm] using h end @[simp] lemma succ_above_descend : ∀(p i : fin (n+1)) (h : i ≠ p), p.succ_above (p.pred_above i h) = i | ⟨p, hp⟩ ⟨0, hi⟩ h := fin.eq_of_veq $ by simp [succ_above, pred_above]; split_ifs; simp * at * | ⟨p, hp⟩ ⟨i+1, hi⟩ h := fin.eq_of_veq begin have : i + 1 ≠ p, by rwa [(≠), fin.ext_iff] at h, unfold succ_above pred_above, split_ifs with h1 h2; simp only [fin.cast_succ_cast_lt, add_right_inj, pred_val, ne.def, cast_succ_val, nat.pred_succ, fin.succ_pred, add_right_inj] at *, exact (this (le_antisymm h2 (le_of_not_gt h1))).elim end @[simp] lemma pred_above_succ_above (p : fin (n+1)) (i : fin n) (h : p.succ_above i ≠ p) : p.pred_above (p.succ_above i) h = i := begin unfold fin.succ_above, apply eq_of_veq, split_ifs with h₀, { simp [pred_above, h₀, lt_iff_val_lt_val], }, { unfold pred_above, split_ifs with h₁, { exfalso, rw [lt_iff_val_lt_val, succ_val] at h₁, exact h₀ (lt_trans (nat.lt_succ_self _) h₁) }, { rw [pred_succ] } } end /-- A function `f` on `fin n` is strictly monotone if and only if `f i < f (i+1)` for all `i`. -/ lemma strict_mono_iff_lt_succ {α : Type*} [preorder α] {f : fin n → α} : strict_mono f ↔ ∀ i (h : i + 1 < n), f ⟨i, lt_of_le_of_lt (nat.le_succ i) h⟩ < f ⟨i+1, h⟩ := begin split, { assume H i hi, apply H, exact nat.lt_succ_self _ }, { assume H, have A : ∀ i j (h : i < j) (h' : j < n), f ⟨i, lt_trans h h'⟩ < f ⟨j, h'⟩, { assume i j h h', induction h with k h IH, { exact H _ _ }, { exact lt_trans (IH (nat.lt_of_succ_lt h')) (H _ _) } }, assume i j hij, convert A (i : ℕ) (j : ℕ) hij j.2; simp [fin.ext_iff, fin.coe_eq_val] } end section rec /-- Define `C n i` by induction on `i : fin n` interpreted as `(0 : fin (n - i)).succ.succ…`. This function has two arguments: `H0 n` defines `0`-th element `C (n+1) 0` of an `(n+1)`-tuple, and `Hs n i` defines `(i+1)`-st element of `(n+1)`-tuple based on `n`, `i`, and `i`-th element of `n`-tuple. -/ @[elab_as_eliminator] def succ_rec {C : Π n, fin n → Sort*} (H0 : Π n, C (succ n) 0) (Hs : Π n i, C n i → C (succ n) i.succ) : Π {n : ℕ} (i : fin n), C n i | 0 i := i.elim0 | (succ n) ⟨0, _⟩ := H0 _ | (succ n) ⟨succ i, h⟩ := Hs _ _ (succ_rec ⟨i, lt_of_succ_lt_succ h⟩) /-- Define `C n i` by induction on `i : fin n` interpreted as `(0 : fin (n - i)).succ.succ…`. This function has two arguments: `H0 n` defines `0`-th element `C (n+1) 0` of an `(n+1)`-tuple, and `Hs n i` defines `(i+1)`-st element of `(n+1)`-tuple based on `n`, `i`, and `i`-th element of `n`-tuple. A version of `fin.succ_rec` taking `i : fin n` as the first argument. -/ @[elab_as_eliminator] def succ_rec_on {n : ℕ} (i : fin n) {C : Π n, fin n → Sort*} (H0 : Π n, C (succ n) 0) (Hs : Π n i, C n i → C (succ n) i.succ) : C n i := i.succ_rec H0 Hs @[simp] theorem succ_rec_on_zero {C : ∀ n, fin n → Sort*} {H0 Hs} (n) : @fin.succ_rec_on (succ n) 0 C H0 Hs = H0 n := rfl @[simp] theorem succ_rec_on_succ {C : ∀ n, fin n → Sort*} {H0 Hs} {n} (i : fin n) : @fin.succ_rec_on (succ n) i.succ C H0 Hs = Hs n i (fin.succ_rec_on i H0 Hs) := by cases i; refl /-- Define `f : Π i : fin n.succ, C i` by separately handling the cases `i = 0` and `i = j.succ`, `j : fin n`. -/ @[elab_as_eliminator] def cases {C : fin (succ n) → Sort*} (H0 : C 0) (Hs : Π i : fin n, C (i.succ)) : Π (i : fin (succ n)), C i | ⟨0, h⟩ := H0 | ⟨succ i, h⟩ := Hs ⟨i, lt_of_succ_lt_succ h⟩ @[simp] theorem cases_zero {n} {C : fin (succ n) → Sort*} {H0 Hs} : @fin.cases n C H0 Hs 0 = H0 := rfl @[simp] theorem cases_succ {n} {C : fin (succ n) → Sort*} {H0 Hs} (i : fin n) : @fin.cases n C H0 Hs i.succ = Hs i := by cases i; refl lemma forall_fin_succ {P : fin (n+1) → Prop} : (∀ i, P i) ↔ P 0 ∧ (∀ i:fin n, P i.succ) := ⟨λ H, ⟨H 0, λ i, H _⟩, λ ⟨H0, H1⟩ i, fin.cases H0 H1 i⟩ lemma exists_fin_succ {P : fin (n+1) → Prop} : (∃ i, P i) ↔ P 0 ∨ (∃i:fin n, P i.succ) := ⟨λ ⟨i, h⟩, fin.cases or.inl (λ i hi, or.inr ⟨i, hi⟩) i h, λ h, or.elim h (λ h, ⟨0, h⟩) $ λ⟨i, hi⟩, ⟨i.succ, hi⟩⟩ end rec section tuple /-! ### Tuples We can think of the type `Π(i : fin n), α i` as `n`-tuples of elements of possibly varying type `α i`. A particular case is `fin n → α` of elements with all the same type. Here are some relevant operations, first about adding or removing elements at the beginning of a tuple. -/ /-- There is exactly one tuple of size zero. -/ instance tuple0_unique (α : fin 0 → Type u) : unique (Π i : fin 0, α i) := { default := fin_zero_elim, uniq := λ x, funext fin_zero_elim } variables {α : fin (n+1) → Type u} (x : α 0) (q : Πi, α i) (p : Π(i : fin n), α (i.succ)) (i : fin n) (y : α i.succ) (z : α 0) /-- The tail of an `n+1` tuple, i.e., its last `n` entries -/ def tail (q : Πi, α i) : (Π(i : fin n), α (i.succ)) := λ i, q i.succ /-- Adding an element at the beginning of an `n`-tuple, to get an `n+1`-tuple -/ def cons (x : α 0) (p : Π(i : fin n), α (i.succ)) : Πi, α i := λ j, fin.cases x p j @[simp] lemma tail_cons : tail (cons x p) = p := by simp [tail, cons] @[simp] lemma cons_succ : cons x p i.succ = p i := by simp [cons] @[simp] lemma cons_zero : cons x p 0 = x := by simp [cons] /-- Updating a tuple and adding an element at the beginning commute. -/ @[simp] lemma cons_update : cons x (update p i y) = update (cons x p) i.succ y := begin ext j, by_cases h : j = 0, { rw h, simp [ne.symm (succ_ne_zero i)] }, { let j' := pred j h, have : j'.succ = j := succ_pred j h, rw [← this, cons_succ], by_cases h' : j' = i, { rw h', simp }, { have : j'.succ ≠ i.succ, by rwa [ne.def, succ_inj], rw [update_noteq h', update_noteq this, cons_succ] } } end /-- Adding an element at the beginning of a tuple and then updating it amounts to adding it directly. -/ lemma update_cons_zero : update (cons x p) 0 z = cons z p := begin ext j, by_cases h : j = 0, { rw h, simp }, { simp only [h, update_noteq, ne.def, not_false_iff], let j' := pred j h, have : j'.succ = j := succ_pred j h, rw [← this, cons_succ, cons_succ] } end /-- Concatenating the first element of a tuple with its tail gives back the original tuple -/ @[simp] lemma cons_self_tail : cons (q 0) (tail q) = q := begin ext j, by_cases h : j = 0, { rw h, simp }, { let j' := pred j h, have : j'.succ = j := succ_pred j h, rw [← this, tail, cons_succ] } end /-- Updating the first element of a tuple does not change the tail. -/ @[simp] lemma tail_update_zero : tail (update q 0 z) = tail q := by { ext j, simp [tail, fin.succ_ne_zero] } /-- Updating a nonzero element and taking the tail commute. -/ @[simp] lemma tail_update_succ : tail (update q i.succ y) = update (tail q) i y := begin ext j, by_cases h : j = i, { rw h, simp [tail] }, { simp [tail, (fin.injective_succ n).ne h, h] } end lemma comp_cons {α : Type*} {β : Type*} (g : α → β) (y : α) (q : fin n → α) : g ∘ (cons y q) = cons (g y) (g ∘ q) := begin ext j, by_cases h : j = 0, { rw h, refl }, { let j' := pred j h, have : j'.succ = j := succ_pred j h, rw [← this, cons_succ, comp_app, cons_succ] } end lemma comp_tail {α : Type*} {β : Type*} (g : α → β) (q : fin n.succ → α) : g ∘ (tail q) = tail (g ∘ q) := by { ext j, simp [tail] } end tuple section tuple_right /-! In the previous section, we have discussed inserting or removing elements on the left of a tuple. In this section, we do the same on the right. A difference is that `fin (n+1)` is constructed inductively from `fin n` starting from the left, not from the right. This implies that Lean needs more help to realize that elements belong to the right types, i.e., we need to insert casts at several places. -/ variables {α : fin (n+1) → Type u} (x : α (last n)) (q : Πi, α i) (p : Π(i : fin n), α i.cast_succ) (i : fin n) (y : α i.cast_succ) (z : α (last n)) /-- The beginning of an `n+1` tuple, i.e., its first `n` entries -/ def init (q : Πi, α i) (i : fin n) : α i.cast_succ := q i.cast_succ /-- Adding an element at the end of an `n`-tuple, to get an `n+1`-tuple. The name `snoc` comes from `cons` (i.e., adding an element to the left of a tuple) read in reverse order. -/ def snoc (p : Π(i : fin n), α i.cast_succ) (x : α (last n)) (i : fin (n+1)) : α i := if h : i.val < n then _root_.cast (by rw fin.cast_succ_cast_lt i h) (p (cast_lt i h)) else _root_.cast (by rw eq_last_of_not_lt h) x @[simp] lemma init_snoc : init (snoc p x) = p := begin ext i, have h' := fin.cast_lt_cast_succ i i.is_lt, simp [init, snoc, i.is_lt, h'], convert cast_eq rfl (p i) end @[simp] lemma snoc_cast_succ : snoc p x i.cast_succ = p i := begin have : i.cast_succ.val < n := i.is_lt, have h' := fin.cast_lt_cast_succ i i.is_lt, simp [snoc, this, h'], convert cast_eq rfl (p i) end @[simp] lemma snoc_last : snoc p x (last n) = x := by { simp [snoc], refl } /-- Updating a tuple and adding an element at the end commute. -/ @[simp] lemma snoc_update : snoc (update p i y) x = update (snoc p x) i.cast_succ y := begin ext j, by_cases h : j.val < n, { simp only [snoc, h, dif_pos], by_cases h' : j = cast_succ i, { have C1 : α i.cast_succ = α j, by rw h', have E1 : update (snoc p x) i.cast_succ y j = _root_.cast C1 y, { have : update (snoc p x) j (_root_.cast C1 y) j = _root_.cast C1 y, by simp, convert this, { exact h'.symm }, { exact heq_of_eq_mp (congr_arg α (eq.symm h')) rfl } }, have C2 : α i.cast_succ = α (cast_succ (cast_lt j h)), by rw [cast_succ_cast_lt, h'], have E2 : update p i y (cast_lt j h) = _root_.cast C2 y, { have : update p (cast_lt j h) (_root_.cast C2 y) (cast_lt j h) = _root_.cast C2 y, by simp, convert this, { simp [h, h'] }, { exact heq_of_eq_mp C2 rfl } }, rw [E1, E2], exact eq_rec_compose _ _ _ }, { have : ¬(cast_lt j h = i), by { assume E, apply h', rw [← E, cast_succ_cast_lt] }, simp [h', this, snoc, h] } }, { rw eq_last_of_not_lt h, simp [ne.symm (cast_succ_ne_last i)] } end /-- Adding an element at the beginning of a tuple and then updating it amounts to adding it directly. -/ lemma update_snoc_last : update (snoc p x) (last n) z = snoc p z := begin ext j, by_cases h : j.val < n, { have : j ≠ last n := ne_of_lt h, simp [h, update_noteq, this, snoc] }, { rw eq_last_of_not_lt h, simp } end /-- Concatenating the first element of a tuple with its tail gives back the original tuple -/ @[simp] lemma snoc_init_self : snoc (init q) (q (last n)) = q := begin ext j, by_cases h : j.val < n, { have : j ≠ last n := ne_of_lt h, simp [h, update_noteq, this, snoc, init, cast_succ_cast_lt], have A : cast_succ (cast_lt j h) = j := cast_succ_cast_lt _ _, rw ← cast_eq rfl (q j), congr' 1; rw A }, { rw eq_last_of_not_lt h, simp } end /-- Updating the last element of a tuple does not change the beginning. -/ @[simp] lemma init_update_last : init (update q (last n) z) = init q := by { ext j, simp [init, cast_succ_ne_last] } /-- Updating an element and taking the beginning commute. -/ @[simp] lemma init_update_cast_succ : init (update q i.cast_succ y) = update (init q) i y := begin ext j, by_cases h : j = i, { rw h, simp [init] }, { simp [init, h] } end /-- `tail` and `init` commute. We state this lemma in a non-dependent setting, as otherwise it would involve a cast to convince Lean that the two types are equal, making it harder to use. -/ lemma tail_init_eq_init_tail {β : Type*} (q : fin (n+2) → β) : tail (init q) = init (tail q) := by { ext i, simp [tail, init, cast_succ_fin_succ] } /-- `cons` and `snoc` commute. We state this lemma in a non-dependent setting, as otherwise it would involve a cast to convince Lean that the two types are equal, making it harder to use. -/ lemma cons_snoc_eq_snoc_cons {β : Type*} (a : β) (q : fin n → β) (b : β) : @cons n.succ (λ i, β) a (snoc q b) = snoc (cons a q) b := begin ext i, by_cases h : i = 0, { rw h, refl }, set j := pred i h with ji, have : i = j.succ, by rw [ji, succ_pred], rw [this, cons_succ], by_cases h' : j.val < n, { set k := cast_lt j h' with jk, have : j = k.cast_succ, by rw [jk, cast_succ_cast_lt], rw [this, ← cast_succ_fin_succ], simp }, rw [eq_last_of_not_lt h', succ_last], simp end lemma comp_snoc {α : Type*} {β : Type*} (g : α → β) (q : fin n → α) (y : α) : g ∘ (snoc q y) = snoc (g ∘ q) (g y) := begin ext j, by_cases h : j.val < n, { have : j ≠ last n := ne_of_lt h, simp [h, this, snoc, cast_succ_cast_lt], refl }, { rw eq_last_of_not_lt h, simp } end lemma comp_init {α : Type*} {β : Type*} (g : α → β) (q : fin n.succ → α) : g ∘ (init q) = init (g ∘ q) := by { ext j, simp [init] } end tuple_right section find /-- `find p` returns the first index `n` where `p n` is satisfied, and `none` if it is never satisfied. -/ def find : Π {n : ℕ} (p : fin n → Prop) [decidable_pred p], option (fin n) | 0 p _ := none | (n+1) p _ := by resetI; exact option.cases_on (@find n (λ i, p (i.cast_lt (nat.lt_succ_of_lt i.2))) _) (if h : p (fin.last n) then some (fin.last n) else none) (λ i, some (i.cast_lt (nat.lt_succ_of_lt i.2))) /-- If `find p = some i`, then `p i` holds -/ lemma find_spec : Π {n : ℕ} (p : fin n → Prop) [decidable_pred p] {i : fin n} (hi : i ∈ by exactI fin.find p), p i | 0 p I i hi := option.no_confusion hi | (n+1) p I i hi := begin dsimp [find] at hi, resetI, cases h : find (λ i : fin n, (p (i.cast_lt (nat.lt_succ_of_lt i.2)))) with j, { rw h at hi, dsimp at hi, split_ifs at hi with hl hl, { exact option.some_inj.1 hi ▸ hl }, { exact option.no_confusion hi } }, { rw h at hi, rw [← option.some_inj.1 hi], exact find_spec _ h } end /-- `find p` does not return `none` if and only if `p i` holds at some index `i`. -/ lemma is_some_find_iff : Π {n : ℕ} {p : fin n → Prop} [decidable_pred p], by exactI (find p).is_some ↔ ∃ i, p i | 0 p _ := iff_of_false (λ h, bool.no_confusion h) (λ ⟨i, _⟩, fin.elim0 i) | (n+1) p _ := ⟨λ h, begin resetI, rw [option.is_some_iff_exists] at h, cases h with i hi, exact ⟨i, find_spec _ hi⟩ end, λ ⟨⟨i, hin⟩, hi⟩, begin resetI, dsimp [find], cases h : find (λ i : fin n, (p (i.cast_lt (nat.lt_succ_of_lt i.2)))) with j, { split_ifs with hl hl, { exact option.is_some_some }, { have := (@is_some_find_iff n (λ x, p (x.cast_lt (nat.lt_succ_of_lt x.2))) _).2 ⟨⟨i, lt_of_le_of_ne (nat.le_of_lt_succ hin) (λ h, by clear_aux_decl; subst h; exact hl hi)⟩, hi⟩, rw h at this, exact this } }, { simp } end⟩ /-- `find p` returns `none` if and only if `p i` never holds. -/ lemma find_eq_none_iff {n : ℕ} {p : fin n → Prop} [decidable_pred p] : find p = none ↔ ∀ i, ¬ p i := by rw [← not_exists, ← is_some_find_iff]; cases (find p); simp /-- If `find p` returns `some i`, then `p j` does not hold for `j < i`, i.e., `i` is minimal among the indices where `p` holds. -/ lemma find_min : Π {n : ℕ} {p : fin n → Prop} [decidable_pred p] {i : fin n} (hi : i ∈ by exactI fin.find p) {j : fin n} (hj : j < i), ¬ p j | 0 p _ i hi j hj hpj := option.no_confusion hi | (n+1) p _ i hi ⟨j, hjn⟩ hj hpj := begin resetI, dsimp [find] at hi, cases h : find (λ i : fin n, (p (i.cast_lt (nat.lt_succ_of_lt i.2)))) with k, { rw [h] at hi, split_ifs at hi with hl hl, { have := option.some_inj.1 hi, subst this, rw [find_eq_none_iff] at h, exact h ⟨j, hj⟩ hpj }, { exact option.no_confusion hi } }, { rw h at hi, dsimp at hi, have := option.some_inj.1 hi, subst this, exact find_min h (show (⟨j, lt_trans hj k.2⟩ : fin n) < k, from hj) hpj } end lemma find_min' {p : fin n → Prop} [decidable_pred p] {i : fin n} (h : i ∈ fin.find p) {j : fin n} (hj : p j) : i ≤ j := le_of_not_gt (λ hij, find_min h hij hj) lemma nat_find_mem_find {p : fin n → Prop} [decidable_pred p] (h : ∃ i, ∃ hin : i < n, p ⟨i, hin⟩) : (⟨nat.find h, (nat.find_spec h).fst⟩ : fin n) ∈ find p := let ⟨i, hin, hi⟩ := h in begin cases hf : find p with f, { rw [find_eq_none_iff] at hf, exact (hf ⟨i, hin⟩ hi).elim }, { refine option.some_inj.2 (le_antisymm _ _), { exact find_min' hf (nat.find_spec h).snd }, { exact nat.find_min' _ ⟨f.2, by convert find_spec p hf; exact fin.eta _ _⟩ } } end lemma mem_find_iff {p : fin n → Prop} [decidable_pred p] {i : fin n} : i ∈ fin.find p ↔ p i ∧ ∀ j, p j → i ≤ j := ⟨λ hi, ⟨find_spec _ hi, λ _, find_min' hi⟩, begin rintros ⟨hpi, hj⟩, cases hfp : fin.find p, { rw [find_eq_none_iff] at hfp, exact (hfp _ hpi).elim }, { exact option.some_inj.2 (le_antisymm (find_min' hfp hpi) (hj _ (find_spec _ hfp))) } end⟩ lemma find_eq_some_iff {p : fin n → Prop} [decidable_pred p] {i : fin n} : fin.find p = some i ↔ p i ∧ ∀ j, p j → i ≤ j := mem_find_iff lemma mem_find_of_unique {p : fin n → Prop} [decidable_pred p] (h : ∀ i j, p i → p j → i = j) {i : fin n} (hi : p i) : i ∈ fin.find p := mem_find_iff.2 ⟨hi, λ j hj, le_of_eq $ h i j hi hj⟩ end find end fin
b81ded0c628f115ebde82c74774c95ba34083e17
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/with_local_reducibility_auto.lean
864ae09396fb02348e6b380d3a258f27b0b3864e
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
1,158
lean
/- Copyright (c) 2020 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.core import Mathlib.PostPort universes l namespace Mathlib /-! # `with_local_reducibility` Run a tactic in an environment with a temporarily modified reducibility attribute for a specified declaration. -/ namespace tactic /-- Possible reducibility attributes for a declaration: reducible, semireducible (the default), irreducible. -/ inductive decl_reducibility where | reducible : decl_reducibility | semireducible : decl_reducibility | irreducible : decl_reducibility /-- Satisfy the inhabited linter -/ protected instance decl_reducibility.inhabited : Inhabited decl_reducibility := { default := decl_reducibility.semireducible } /-- Get the reducibility attribute of a declaration. Fails if the name does not refer to an existing declaration. -/ /-- Return the attribute (as a `name`) corresponding to a reducibility level. -/ def decl_reducibility.to_attribute : decl_reducibility → name := sorry end Mathlib
536838d8992f711a0556a725e633fe8bd86a6ae1
5756a081670ba9c1d1d3fca7bd47cb4e31beae66
/Oneshot/lean3-in/other.lean
6e18ea929929ce7c4540674a6b0c18f2e35de6ac
[ "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
15
lean
def other := 1
8d36842bb585cc8eefe8e3f353217a1f59343411
94e33a31faa76775069b071adea97e86e218a8ee
/src/ring_theory/local_properties.lean
a76ad1b435a1ed6cd6e41c5bd315456cc3735954
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
27,444
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 group_theory.submonoid.pointwise import logic.equiv.transfer_instance import ring_theory.finiteness import ring_theory.localization.at_prime import ring_theory.localization.away import ring_theory.localization.integer import ring_theory.localization.submodule import ring_theory.nilpotent import ring_theory.ring_hom_properties /-! # Local properties of commutative rings In this file, we provide the proofs of various local properties. ## Naming Conventions * `localization_P` : `P` holds for `S⁻¹R` if `P` holds for `R`. * `P_of_localization_maximal` : `P` holds for `R` if `P` holds for `Rₘ` for all maximal `m`. * `P_of_localization_prime` : `P` holds for `R` if `P` holds for `Rₘ` for all prime `m`. * `P_of_localization_span` : `P` holds for `R` if given a spanning set `{fᵢ}`, `P` holds for all `R_{fᵢ}`. ## Main results The following properties are covered: * The triviality of an ideal or an element: `ideal_eq_zero_of_localization`, `eq_zero_of_localization` * `is_reduced` : `localization_is_reduced`, `is_reduced_of_localization_maximal`. * `finite`: `localization_finite`, `finite_of_localization_span` * `finite_type`: `localization_finite_type`, `finite_type_of_localization_span` -/ open_locale pointwise classical big_operators universe u variables {R S : Type u} [comm_ring R] [comm_ring S] (M : submonoid R) variables (N : submonoid S) (R' S' : Type u) [comm_ring R'] [comm_ring S'] (f : R →+* S) variables [algebra R R'] [algebra S S'] section properties section comm_ring variable (P : ∀ (R : Type u) [comm_ring R], Prop) include P /-- A property `P` of comm rings is said to be preserved by localization if `P` holds for `M⁻¹R` whenever `P` holds for `R`. -/ def localization_preserves : Prop := ∀ {R : Type u} [hR : comm_ring R] (M : by exactI submonoid R) (S : Type u) [hS : comm_ring S] [by exactI algebra R S] [by exactI is_localization M S], @P R hR → @P S hS /-- A property `P` of comm rings satisfies `of_localization_maximal` if if `P` holds for `R` whenever `P` holds for `Rₘ` for all maximal ideal `m`. -/ def of_localization_maximal : Prop := ∀ (R : Type u) [comm_ring R], by exactI (∀ (J : ideal R) (hJ : J.is_maximal), by exactI P (localization.at_prime J)) → P R end comm_ring section ring_hom variable (P : ∀ {R S : Type u} [comm_ring R] [comm_ring S] (f : by exactI R →+* S), Prop) include P /-- A property `P` of ring homs is said to be preserved by localization if `P` holds for `M⁻¹R →+* M⁻¹S` whenever `P` holds for `R →+* S`. -/ def ring_hom.localization_preserves := ∀ ⦃R S : Type u⦄ [comm_ring R] [comm_ring S] (f : by exactI R →+* S) (M : by exactI submonoid R) (R' S' : Type u) [comm_ring R'] [comm_ring S'] [by exactI algebra R R'] [by exactI algebra S S'] [by exactI is_localization M R'] [by exactI is_localization (M.map f) S'], by exactI (P f → P (is_localization.map S' f (submonoid.le_comap_map M) : R' →+* S')) /-- A property `P` of ring homs satisfies `ring_hom.of_localization_finite_span` if `P` holds for `R →+* S` whenever there exists a finite set `{ r }` that spans `R` such that `P` holds for `Rᵣ →+* Sᵣ`. Note that this is equivalent to `ring_hom.of_localization_span` via `ring_hom.of_localization_span_iff_finite`, but this is easier to prove. -/ def ring_hom.of_localization_finite_span := ∀ ⦃R S : Type u⦄ [comm_ring R] [comm_ring S] (f : by exactI R →+* S) (s : finset R) (hs : by exactI ideal.span (s : set R) = ⊤) (H : by exactI (∀ (r : s), P (localization.away_map f r))), by exactI P f /-- A property `P` of ring homs satisfies `ring_hom.of_localization_finite_span` if `P` holds for `R →+* S` whenever there exists a set `{ r }` that spans `R` such that `P` holds for `Rᵣ →+* Sᵣ`. Note that this is equivalent to `ring_hom.of_localization_finite_span` via `ring_hom.of_localization_span_iff_finite`, but this has less restrictions when applying. -/ def ring_hom.of_localization_span := ∀ ⦃R S : Type u⦄ [comm_ring R] [comm_ring S] (f : by exactI R →+* S) (s : set R) (hs : by exactI ideal.span s = ⊤) (H : by exactI (∀ (r : s), P (localization.away_map f r))), by exactI P f /-- A property `P` of ring homs satisfies `ring_hom.holds_for_localization_away` if `P` holds for each localization map `R →+* Rᵣ`. -/ def ring_hom.holds_for_localization_away : Prop := ∀ ⦃R : Type u⦄ (S : Type u) [comm_ring R] [comm_ring S] [by exactI algebra R S] (r : R) [by exactI is_localization.away r S], by exactI P (algebra_map R S) /-- A property `P` of ring homs satisfies `ring_hom.of_localization_span_target` if `P` holds for `R →+* S` whenever there exists a finite set `{ r }` that spans `S` such that `P` holds for `R →+* Sᵣ`. -/ def ring_hom.of_localization_span_target : Prop := ∀ ⦃R S : Type u⦄ [comm_ring R] [comm_ring S] (f : by exactI R →+* S) (s : set S) (hs : by exactI ideal.span s = ⊤) (H : by exactI (∀ (r : s), P ((algebra_map S (localization.away (r : S))).comp f))), by exactI P f /-- A property `P` of ring homs satisfies `of_localization_prime` if if `P` holds for `R` whenever `P` holds for `Rₘ` for all prime ideals `p`. -/ def ring_hom.of_localization_prime : Prop := ∀ ⦃R S : Type u⦄ [comm_ring R] [comm_ring S] (f : by exactI R →+* S), by exactI (∀ (J : ideal S) (hJ : J.is_prime), by exactI P (localization.local_ring_hom _ J f rfl)) → P f /-- A property of ring homs is local if it is preserved by localizations and compositions, and for each `{ r }` that spans `S`, we have `P (R →+* S) ↔ ∀ r, P (R →+* Sᵣ)`. -/ structure ring_hom.property_is_local : Prop := (localization_preserves : ring_hom.localization_preserves @P) (of_localization_span_target : ring_hom.of_localization_span_target @P) (stable_under_composition : ring_hom.stable_under_composition @P) (holds_for_localization_away : ring_hom.holds_for_localization_away @P) lemma ring_hom.of_localization_span_iff_finite : ring_hom.of_localization_span @P ↔ ring_hom.of_localization_finite_span @P := begin delta ring_hom.of_localization_span ring_hom.of_localization_finite_span, apply forall₅_congr, -- TODO: Using `refine` here breaks `resetI`. introsI, split, { intros h s, exact h s }, { intros h s hs hs', obtain ⟨s', h₁, h₂⟩ := (ideal.span_eq_top_iff_finite s).mp hs, exact h s' h₂ (λ x, hs' ⟨_, h₁ x.prop⟩) } end variables {P f R' S'} lemma _root_.ring_hom.property_is_local.respects_iso (hP : ring_hom.property_is_local @P) : ring_hom.respects_iso @P := begin apply hP.stable_under_composition.respects_iso, introv, resetI, letI := e.to_ring_hom.to_algebra, apply_with hP.holds_for_localization_away { instances := ff }, apply is_localization.away_of_is_unit_of_bijective _ is_unit_one, exact e.bijective end -- Almost all arguments are implicit since this is not intended to use mid-proof. lemma ring_hom.localization_preserves.away (H : ring_hom.localization_preserves @P) (r : R) [is_localization.away r R'] [is_localization.away (f r) S'] (hf : P f) : P (by exactI is_localization.away.map R' S' f r) := begin resetI, haveI : is_localization ((submonoid.powers r).map f) S', { rw submonoid.map_powers, assumption }, exact H f (submonoid.powers r) R' S' hf, end lemma ring_hom.property_is_local.of_localization_span (hP : ring_hom.property_is_local @P) : ring_hom.of_localization_span @P := begin introv R hs hs', resetI, apply_fun (ideal.map f) at hs, rw [ideal.map_span, ideal.map_top] at hs, apply hP.of_localization_span_target _ _ hs, rintro ⟨_, r, hr, rfl⟩, have := hs' ⟨r, hr⟩, convert hP.stable_under_composition _ _ (hP.holds_for_localization_away (localization.away r) r) (hs' ⟨r, hr⟩) using 1, exact (is_localization.map_comp _).symm end end ring_hom end properties section ideal -- This proof should work for all modules, but we do not know how to localize a module yet. /-- An ideal is trivial if its localization at every maximal ideal is trivial. -/ lemma ideal_eq_zero_of_localization (I : ideal R) (h : ∀ (J : ideal R) (hJ : J.is_maximal), by exactI is_localization.coe_submodule (localization.at_prime J) I = 0) : I = 0 := begin by_contradiction hI, change I ≠ ⊥ at hI, obtain ⟨x, hx, hx'⟩ := set_like.exists_of_lt hI.bot_lt, rw [submodule.mem_bot] at hx', have H : (ideal.span ({x} : set R)).annihilator ≠ ⊤, { rw [ne.def, submodule.annihilator_eq_top_iff], by_contra, apply hx', rw [← set.mem_singleton_iff, ← @submodule.bot_coe R, ← h], exact ideal.subset_span (set.mem_singleton x) }, obtain ⟨p, hp₁, hp₂⟩ := ideal.exists_le_maximal _ H, resetI, specialize h p hp₁, have : algebra_map R (localization.at_prime p) x = 0, { rw ← set.mem_singleton_iff, change algebra_map R (localization.at_prime p) x ∈ (0 : submodule R (localization.at_prime p)), rw ← h, exact submodule.mem_map_of_mem hx }, rw is_localization.map_eq_zero_iff p.prime_compl at this, obtain ⟨m, hm⟩ := this, apply m.prop, refine hp₂ _, erw submodule.mem_annihilator_span_singleton, rwa mul_comm at hm, end lemma eq_zero_of_localization (r : R) (h : ∀ (J : ideal R) (hJ : J.is_maximal), by exactI algebra_map R (localization.at_prime J) r = 0) : r = 0 := begin rw ← ideal.span_singleton_eq_bot, apply ideal_eq_zero_of_localization, intros J hJ, delta is_localization.coe_submodule, erw [submodule.map_span, submodule.span_eq_bot], rintro _ ⟨_, h', rfl⟩, cases set.mem_singleton_iff.mpr h', exact h J hJ, end end ideal section reduced lemma localization_is_reduced : localization_preserves (λ R hR, by exactI is_reduced R) := begin introv R _ _, resetI, constructor, rintro x ⟨(_|n), e⟩, { simpa using congr_arg (*x) e }, obtain ⟨⟨y, m⟩, hx⟩ := is_localization.surj M x, dsimp only at hx, let hx' := congr_arg (^ n.succ) hx, simp only [mul_pow, e, zero_mul, ← ring_hom.map_pow] at hx', rw [← (algebra_map R S).map_zero] at hx', obtain ⟨m', hm'⟩ := (is_localization.eq_iff_exists M S).mp hx', apply_fun (*m'^n) at hm', simp only [mul_assoc, zero_mul] at hm', rw [mul_comm, ← pow_succ, ← mul_pow] at hm', replace hm' := is_nilpotent.eq_zero ⟨_, hm'.symm⟩, rw [← (is_localization.map_units S m).mul_left_inj, hx, zero_mul, is_localization.map_eq_zero_iff M], exact ⟨m', by rw [← hm', mul_comm]⟩ end instance [is_reduced R] : is_reduced (localization M) := localization_is_reduced M _ infer_instance lemma is_reduced_of_localization_maximal : of_localization_maximal (λ R hR, by exactI is_reduced R) := begin introv R h, constructor, intros x hx, apply eq_zero_of_localization, intros J hJ, specialize h J hJ, resetI, exact (hx.map $ algebra_map R $ localization.at_prime J).eq_zero, end end reduced section surjective lemma localization_preserves_surjective : ring_hom.localization_preserves (λ R S _ _ f, function.surjective f) := begin introv R H x, resetI, obtain ⟨x, ⟨_, s, hs, rfl⟩, rfl⟩ := is_localization.mk'_surjective (M.map f) x, obtain ⟨y, rfl⟩ := H x, use is_localization.mk' R' y ⟨s, hs⟩, rw is_localization.map_mk', refl, end lemma surjective_of_localization_span : ring_hom.of_localization_span (λ R S _ _ f, function.surjective f) := begin introv R e H, rw [← set.range_iff_surjective, set.eq_univ_iff_forall], resetI, letI := f.to_algebra, intro x, apply submodule.mem_of_span_eq_top_of_smul_pow_mem (algebra.of_id R S).to_linear_map.range s e, intro r, obtain ⟨a, e'⟩ := H r (algebra_map _ _ x), obtain ⟨b, ⟨_, n, rfl⟩, rfl⟩ := is_localization.mk'_surjective (submonoid.powers (r : R)) a, erw is_localization.map_mk' at e', rw [eq_comm, is_localization.eq_mk'_iff_mul_eq, subtype.coe_mk, subtype.coe_mk, ← map_mul] at e', obtain ⟨⟨_, n', rfl⟩, e''⟩ := (is_localization.eq_iff_exists (submonoid.powers (f r)) _).mp e', rw [subtype.coe_mk, mul_assoc, ← map_pow, ← map_mul, ← map_mul, ← pow_add, mul_comm] at e'', exact ⟨n + n', _, e''.symm⟩ end end surjective section finite /-- If `S` is a finite `R`-algebra, then `S' = M⁻¹S` is a finite `R' = M⁻¹R`-algebra. -/ lemma localization_finite : ring_hom.localization_preserves @ring_hom.finite := begin introv R hf, -- Setting up the `algebra` and `is_scalar_tower` instances needed resetI, letI := f.to_algebra, letI := ((algebra_map S S').comp f).to_algebra, let f' : R' →+* S' := is_localization.map S' f (submonoid.le_comap_map M), letI := f'.to_algebra, haveI : is_scalar_tower R R' S' := is_scalar_tower.of_algebra_map_eq' (is_localization.map_comp _).symm, let fₐ : S →ₐ[R] S' := alg_hom.mk' (algebra_map S S') (λ c x, ring_hom.map_mul _ _ _), -- We claim that if `S` is generated by `T` as an `R`-module, -- then `S'` is generated by `T` as an `R'`-module. unfreezingI { obtain ⟨T, hT⟩ := hf }, use T.image (algebra_map S S'), rw eq_top_iff, rintro x -, -- By the hypotheses, for each `x : S'`, we have `x = y / (f r)` for some `y : S` and `r : M`. -- Since `S` is generated by `T`, the image of `y` should fall in the span of the image of `T`. obtain ⟨y, ⟨_, ⟨r, hr, rfl⟩⟩, rfl⟩ := is_localization.mk'_surjective (M.map f) x, rw [is_localization.mk'_eq_mul_mk'_one, mul_comm, finset.coe_image], have hy : y ∈ submodule.span R ↑T, by { rw hT, trivial }, replace hy : algebra_map S S' y ∈ submodule.map fₐ.to_linear_map (submodule.span R T) := submodule.mem_map_of_mem hy, rw submodule.map_span fₐ.to_linear_map T at hy, have H : submodule.span R ((algebra_map S S') '' T) ≤ (submodule.span R' ((algebra_map S S') '' T)).restrict_scalars R, { rw submodule.span_le, exact submodule.subset_span }, -- Now, since `y ∈ span T`, and `(f r)⁻¹ ∈ R'`, `x / (f r)` is in `span T` as well. convert (submodule.span R' ((algebra_map S S') '' T)).smul_mem (is_localization.mk' R' (1 : R) ⟨r, hr⟩) (H hy) using 1, rw algebra.smul_def, erw is_localization.map_mk', rw map_one, refl, end lemma localization_away_map_finite (r : R) [is_localization.away r R'] [is_localization.away (f r) S'] (hf : f.finite) : (is_localization.away.map R' S' f r).finite := localization_finite.away r hf /-- Let `S` be an `R`-algebra, `M` an submonoid of `R`, and `S' = M⁻¹S`. If the image of some `x : S` falls in the span of some finite `s ⊆ S'` over `R`, then there exists some `m : M` such that `m • x` falls in the span of `finset_integer_multiple _ s` over `R`. -/ lemma is_localization.smul_mem_finset_integer_multiple_span [algebra R S] [algebra R S'] [is_scalar_tower R S S'] [is_localization (M.map (algebra_map R S : R →* S)) S'] (x : S) (s : finset S') (hx : algebra_map S S' x ∈ submodule.span R (s : set S')) : ∃ m : M, m • x ∈ submodule.span R (is_localization.finset_integer_multiple (M.map (algebra_map R S : R →* S)) s : set S) := begin let g : S →ₐ[R] S' := alg_hom.mk' (algebra_map S S') (λ c x, by simp [algebra.algebra_map_eq_smul_one]), -- We first obtain the `y' ∈ M` such that `s' = y' • s` is falls in the image of `S` in `S'`. let y := is_localization.common_denom_of_finset (M.map (algebra_map R S : R →* S)) s, have hx₁ : (y : S) • ↑s = g '' _ := (is_localization.finset_integer_multiple_image _ s).symm, obtain ⟨y', hy', e : algebra_map R S y' = y⟩ := y.prop, have : algebra_map R S y' • (s : set S') = y' • s := by simp_rw [algebra.algebra_map_eq_smul_one, smul_assoc, one_smul], rw [← e, this] at hx₁, replace hx₁ := congr_arg (submodule.span R) hx₁, rw submodule.span_smul_eq at hx₁, replace hx : _ ∈ y' • submodule.span R (s : set S') := set.smul_mem_smul_set hx, rw hx₁ at hx, erw [← g.map_smul, ← submodule.map_span (g : S →ₗ[R] S')] at hx, -- Since `x` falls in the span of `s` in `S'`, `y' • x : S` falls in the span of `s'` in `S'`. -- That is, there exists some `x' : S` in the span of `s'` in `S` and `x' = y' • x` in `S'`. -- Thus `a • (y' • x) = a • x' ∈ span s'` in `S` for some `a ∈ M`. obtain ⟨x', hx', hx'' : algebra_map _ _ _ = _⟩ := hx, obtain ⟨⟨_, a, ha₁, rfl⟩, ha₂⟩ := (is_localization.eq_iff_exists (M.map (algebra_map R S : R →* S)) S').mp hx'', use (⟨a, ha₁⟩ : M) * (⟨y', hy'⟩ : M), convert (submodule.span R (is_localization.finset_integer_multiple (submonoid.map (algebra_map R S : R →* S) M) s : set S)).smul_mem a hx' using 1, convert ha₂.symm, { rw [mul_comm (y' • x), subtype.coe_mk, submonoid.smul_def, submonoid.coe_mul, ← smul_smul], exact algebra.smul_def _ _ }, { rw mul_comm, exact algebra.smul_def _ _ } end /-- If `S` is an `R' = M⁻¹R` algebra, and `x ∈ span R' s`, then `t • x ∈ span R s` for some `t : M`.-/ lemma multiple_mem_span_of_mem_localization_span [algebra R' S] [algebra R S] [is_scalar_tower R R' S] [is_localization M R'] (s : set S) (x : S) (hx : x ∈ submodule.span R' s) : ∃ t : M, t • x ∈ submodule.span R s := begin classical, obtain ⟨s', hss', hs'⟩ := submodule.mem_span_finite_of_mem_span hx, suffices : ∃ t : M, t • x ∈ submodule.span R (s' : set S), { obtain ⟨t, ht⟩ := this, exact ⟨t, submodule.span_mono hss' ht⟩ }, clear hx hss' s, revert x, apply s'.induction_on, { intros x hx, use 1, simpa using hx }, rintros a s ha hs x hx, simp only [finset.coe_insert, finset.image_insert, finset.coe_image, subtype.coe_mk, submodule.mem_span_insert] at hx ⊢, rcases hx with ⟨y, z, hz, rfl⟩, rcases is_localization.surj M y with ⟨⟨y', s'⟩, e⟩, replace e : _ * a = _ * a := (congr_arg (λ x, algebra_map R' S x * a) e : _), simp_rw [ring_hom.map_mul, ← is_scalar_tower.algebra_map_apply, mul_comm (algebra_map R' S y), mul_assoc, ← algebra.smul_def] at e, rcases hs _ hz with ⟨t, ht⟩, refine ⟨t*s', t*y', _, (submodule.span R (s : set S)).smul_mem s' ht, _⟩, rw [smul_add, ← smul_smul, mul_comm, ← smul_smul, ← smul_smul, ← e], refl, end /-- If `S` is an `R' = M⁻¹R` algebra, and `x ∈ adjoin R' s`, then `t • x ∈ adjoin R s` for some `t : M`.-/ lemma multiple_mem_adjoin_of_mem_localization_adjoin [algebra R' S] [algebra R S] [is_scalar_tower R R' S] [is_localization M R'] (s : set S) (x : S) (hx : x ∈ algebra.adjoin R' s) : ∃ t : M, t • x ∈ algebra.adjoin R s := begin change ∃ (t : M), t • x ∈ (algebra.adjoin R s).to_submodule, change x ∈ (algebra.adjoin R' s).to_submodule at hx, simp_rw [algebra.adjoin_eq_span] at hx ⊢, exact multiple_mem_span_of_mem_localization_span M R' _ _ hx end lemma finite_of_localization_span : ring_hom.of_localization_span @ring_hom.finite := begin rw ring_hom.of_localization_span_iff_finite, introv R hs H, -- We first setup the instances resetI, letI := f.to_algebra, letI := λ (r : s), (localization.away_map f r).to_algebra, haveI : ∀ r : s, is_localization ((submonoid.powers (r : R)).map (algebra_map R S : R →* S)) (localization.away (f r)), { intro r, rw submonoid.map_powers, exact localization.is_localization }, haveI : ∀ r : s, is_scalar_tower R (localization.away (r : R)) (localization.away (f r)) := λ r, is_scalar_tower.of_algebra_map_eq' (is_localization.map_comp _).symm, -- By the hypothesis, we may find a finite generating set for each `Sᵣ`. This set can then be -- lifted into `R` by multiplying a sufficiently large power of `r`. I claim that the union of -- these generates `S`. constructor, replace H := λ r, (H r).1, choose s₁ s₂ using H, let sf := λ (x : s), is_localization.finset_integer_multiple (submonoid.powers (f x)) (s₁ x), use s.attach.bUnion sf, rw [submodule.span_attach_bUnion, eq_top_iff], -- It suffices to show that `r ^ n • x ∈ span T` for each `r : s`, since `{ r ^ n }` spans `R`. -- This then follows from the fact that each `x : R` is a linear combination of the generating set -- of `Sᵣ`. By multiplying a sufficiently large power of `r`, we can cancel out the `r`s in the -- denominators of both the generating set and the coefficients. rintro x -, apply submodule.mem_of_span_eq_top_of_smul_pow_mem _ (s : set R) hs _ _, intro r, obtain ⟨⟨_, n₁, rfl⟩, hn₁⟩ := multiple_mem_span_of_mem_localization_span (submonoid.powers (r : R)) (localization.away (r : R)) (s₁ r : set (localization.away (f r))) (algebra_map S _ x) (by { rw s₂ r, trivial }), rw [submonoid.smul_def, algebra.smul_def, is_scalar_tower.algebra_map_apply R S, subtype.coe_mk, ← map_mul] at hn₁, obtain ⟨⟨_, n₂, rfl⟩, hn₂⟩ := is_localization.smul_mem_finset_integer_multiple_span (submonoid.powers (r : R)) (localization.away (f r)) _ (s₁ r) hn₁, rw [submonoid.smul_def, ← algebra.smul_def, smul_smul, subtype.coe_mk, ← pow_add] at hn₂, use n₂ + n₁, refine le_supr (λ (x : s), submodule.span R (sf x : set S)) r _, change _ ∈ submodule.span R ((is_localization.finset_integer_multiple _ (s₁ r) : finset S) : set S), convert hn₂, rw submonoid.map_powers, refl, end end finite section finite_type lemma localization_finite_type : ring_hom.localization_preserves @ring_hom.finite_type := begin introv R hf, -- mirrors the proof of `localization_map_finite` resetI, letI := f.to_algebra, letI := ((algebra_map S S').comp f).to_algebra, let f' : R' →+* S' := is_localization.map S' f (submonoid.le_comap_map M), letI := f'.to_algebra, haveI : is_scalar_tower R R' S' := is_scalar_tower.of_algebra_map_eq' (is_localization.map_comp _).symm, let fₐ : S →ₐ[R] S' := alg_hom.mk' (algebra_map S S') (λ c x, ring_hom.map_mul _ _ _), obtain ⟨T, hT⟩ := id hf, use T.image (algebra_map S S'), rw eq_top_iff, rintro x -, obtain ⟨y, ⟨_, ⟨r, hr, rfl⟩⟩, rfl⟩ := is_localization.mk'_surjective (M.map f) x, rw [is_localization.mk'_eq_mul_mk'_one, mul_comm, finset.coe_image], have hy : y ∈ algebra.adjoin R (T : set S), by { rw hT, trivial }, replace hy : algebra_map S S' y ∈ (algebra.adjoin R (T : set S)).map fₐ := subalgebra.mem_map.mpr ⟨_, hy, rfl⟩, rw fₐ.map_adjoin T at hy, have H : algebra.adjoin R ((algebra_map S S') '' T) ≤ (algebra.adjoin R' ((algebra_map S S') '' T)).restrict_scalars R, { rw algebra.adjoin_le_iff, exact algebra.subset_adjoin }, convert (algebra.adjoin R' ((algebra_map S S') '' T)).smul_mem (H hy) (is_localization.mk' R' (1 : R) ⟨r, hr⟩) using 1, rw algebra.smul_def, erw is_localization.map_mk', rw map_one, refl, end lemma localization_away_map_finite_type (r : R) [is_localization.away r R'] [is_localization.away (f r) S'] (hf : f.finite_type) : (is_localization.away.map R' S' f r).finite_type := localization_finite_type.away r hf /-- Let `S` be an `R`-algebra, `M` an submonoid of `R`, and `S' = M⁻¹S`. If the image of some `x : S` falls in the adjoin of some finite `s ⊆ S'` over `R`, then there exists some `m : M` such that `m • x` falls in the adjoin of `finset_integer_multiple _ s` over `R`. -/ lemma is_localization.lift_mem_adjoin_finset_integer_multiple [algebra R S] [algebra R S'] [is_scalar_tower R S S'] [is_localization (M.map (algebra_map R S : R →* S)) S'] (x : S) (s : finset S') (hx : algebra_map S S' x ∈ algebra.adjoin R (s : set S')) : ∃ m : M, m • x ∈ algebra.adjoin R (is_localization.finset_integer_multiple (M.map (algebra_map R S : R →* S)) s : set S) := begin -- mirrors the proof of `is_localization.smul_mem_finset_integer_multiple_span` let g : S →ₐ[R] S' := alg_hom.mk' (algebra_map S S') (λ c x, by simp [algebra.algebra_map_eq_smul_one]), let y := is_localization.common_denom_of_finset (M.map (algebra_map R S : R →* S)) s, have hx₁ : (y : S) • ↑s = g '' _ := (is_localization.finset_integer_multiple_image _ s).symm, obtain ⟨y', hy', e : algebra_map R S y' = y⟩ := y.prop, have : algebra_map R S y' • (s : set S') = y' • s := by simp_rw [algebra.algebra_map_eq_smul_one, smul_assoc, one_smul], rw [← e, this] at hx₁, replace hx₁ := congr_arg (algebra.adjoin R) hx₁, obtain ⟨n, hn⟩ := algebra.pow_smul_mem_adjoin_smul _ y' (s : set S') hx, specialize hn n (le_of_eq rfl), erw [hx₁, ← g.map_smul, ← g.map_adjoin] at hn, obtain ⟨x', hx', hx''⟩ := hn, obtain ⟨⟨_, a, ha₁, rfl⟩, ha₂⟩ := (is_localization.eq_iff_exists (M.map (algebra_map R S : R →* S)) S').mp hx'', use (⟨a, ha₁⟩ : M) * (⟨y', hy'⟩ : M) ^ n, convert (algebra.adjoin R (is_localization.finset_integer_multiple (submonoid.map (algebra_map R S : R →* S) M) s : set S)).smul_mem hx' a using 1, convert ha₂.symm, { rw [mul_comm (y' ^ n • x), subtype.coe_mk, submonoid.smul_def, submonoid.coe_mul, ← smul_smul, algebra.smul_def, submonoid_class.coe_pow], refl }, { rw mul_comm, exact algebra.smul_def _ _ } end lemma finite_type_of_localization_span : ring_hom.of_localization_span @ring_hom.finite_type := begin rw ring_hom.of_localization_span_iff_finite, introv R hs H, -- mirrors the proof of `finite_of_localization_span` resetI, letI := f.to_algebra, letI := λ (r : s), (localization.away_map f r).to_algebra, haveI : ∀ r : s, is_localization ((submonoid.powers (r : R)).map (algebra_map R S : R →* S)) (localization.away (f r)), { intro r, rw submonoid.map_powers, exact localization.is_localization }, haveI : ∀ r : s, is_scalar_tower R (localization.away (r : R)) (localization.away (f r)) := λ r, is_scalar_tower.of_algebra_map_eq' (is_localization.map_comp _).symm, constructor, replace H := λ r, (H r).1, choose s₁ s₂ using H, let sf := λ (x : s), is_localization.finset_integer_multiple (submonoid.powers (f x)) (s₁ x), use s.attach.bUnion sf, convert (algebra.adjoin_attach_bUnion sf).trans _, rw eq_top_iff, rintro x -, apply (⨆ (x : s), algebra.adjoin R (sf x : set S)).to_submodule .mem_of_span_eq_top_of_smul_pow_mem _ hs _ _, intro r, obtain ⟨⟨_, n₁, rfl⟩, hn₁⟩ := multiple_mem_adjoin_of_mem_localization_adjoin (submonoid.powers (r : R)) (localization.away (r : R)) (s₁ r : set (localization.away (f r))) (algebra_map S (localization.away (f r)) x) (by { rw s₂ r, trivial }), rw [submonoid.smul_def, algebra.smul_def, is_scalar_tower.algebra_map_apply R S, subtype.coe_mk, ← map_mul] at hn₁, obtain ⟨⟨_, n₂, rfl⟩, hn₂⟩ := is_localization.lift_mem_adjoin_finset_integer_multiple (submonoid.powers (r : R)) (localization.away (f r)) _ (s₁ r) hn₁, rw [submonoid.smul_def, ← algebra.smul_def, smul_smul, subtype.coe_mk, ← pow_add] at hn₂, use n₂ + n₁, refine le_supr (λ (x : s), algebra.adjoin R (sf x : set S)) r _, change _ ∈ algebra.adjoin R ((is_localization.finset_integer_multiple _ (s₁ r) : finset S) : set S), convert hn₂, rw submonoid.map_powers, refl, end end finite_type
9bdc6b290a7d010eb1117015554cec9e1642744e
690889011852559ee5ac4dfea77092de8c832e7e
/src/order/filter/filter_product.lean
4c2362620f73a0195454f5d50cdd096f1121ef25
[ "Apache-2.0" ]
permissive
williamdemeo/mathlib
f6df180148f8acc91de9ba5e558976ab40a872c7
1fa03c29f9f273203bbffb79d10d31f696b3d317
refs/heads/master
1,584,785,260,929
1,572,195,914,000
1,572,195,913,000
138,435,193
0
0
Apache-2.0
1,529,789,739,000
1,529,789,739,000
null
UTF-8
Lean
false
false
20,329
lean
/- Copyright (c) 2019 Abhimanyu Pallavi Sudhir. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Abhimanyu Pallavi Sudhir "Filterproducts" (ultraproducts on general filters), ultraproducts. -/ import order.filter.basic import algebra.pi_instances universes u v variables {α : Type u} (β : Type v) (φ : filter α) open_locale classical namespace filter /-- Two sequences are bigly equal iff the kernel of their difference is in φ -/ def bigly_equal : setoid (α → β) := ⟨ λ a b, {n | a n = b n} ∈ φ, λ a, by simp only [eq_self_iff_true, (set.univ_def).symm, univ_sets], λ a b ab, by simpa only [eq_comm], λ a b c ab bc, sets_of_superset φ (inter_sets φ ab bc) (λ n r, eq.trans r.1 r.2)⟩ /-- Ultraproduct, but on a general filter -/ def filterprod := quotient (bigly_equal β φ) local notation `β*` := filterprod β φ namespace filter_product variables {α β φ} include φ def of_seq : (α → β) → β* := @quotient.mk' (α → β) (bigly_equal β φ) /-- Equivalence class containing the constant sequence of a term in β -/ def of (b : β) : β* := of_seq (function.const α b) /-- Lift function to filter product -/ def lift (f : β → β) : β* → β* := λ x, quotient.lift_on' x (λ a, (of_seq $ λ n, f (a n) : β*)) $ λ a b h, quotient.sound' $ show _ ∈ _, by filter_upwards [h] λ i hi, congr_arg _ hi /-- Lift binary operation to filter product -/ def lift₂ (f : β → β → β) : β* → β* → β* := λ x y, quotient.lift_on₂' x y (λ a b, (of_seq $ λ n, f (a n) (b n) : β*)) $ λ a₁ a₂ b₁ b₂ h1 h2, quotient.sound' $ show _ ∈ _, by filter_upwards [h1, h2] λ i hi1 hi2, congr (congr_arg _ hi1) hi2 /-- Lift properties to filter product -/ def lift_rel (R : β → Prop) : β* → Prop := λ x, quotient.lift_on' x (λ a, {i : α | R (a i)} ∈ φ) $ λ a b h, propext ⟨ λ ha, by filter_upwards [h, ha] λ i hi hia, by simpa [hi.symm], λ hb, by filter_upwards [h, hb] λ i hi hib, by simpa [hi.symm.symm] ⟩ /-- Lift binary relations to filter product -/ def lift_rel₂ (R : β → β → Prop) : β* → β* → Prop := λ x y, quotient.lift_on₂' x y (λ a b, {i : α | R (a i) (b i)} ∈ φ) $ λ a₁ a₂ b₁ b₂ h₁ h₂, propext ⟨ λ ha, by filter_upwards [h₁, h₂, ha] λ i hi1 hi2 hia, by simpa [hi1.symm, hi2.symm], λ hb, by filter_upwards [h₁, h₂, hb] λ i hi1 hi2 hib, by simpa [hi1.symm.symm, hi2.symm.symm] ⟩ instance coe_filterprod : has_coe β β* := ⟨ of ⟩ instance [has_add β] : has_add β* := { add := lift₂ has_add.add } instance [has_zero β] : has_zero β* := { zero := of 0 } instance [has_neg β] : has_neg β* := { neg := lift has_neg.neg } instance [add_semigroup β] : add_semigroup β* := { add_assoc := λ x y z, quotient.induction_on₃' x y z $ λ a b c, quotient.sound' $ show {n | _ + _ + _ = _ + (_ + _)} ∈ _, by simp only [add_assoc, eq_self_iff_true]; exact φ.univ_sets, ..filter_product.has_add } instance [add_left_cancel_semigroup β] : add_left_cancel_semigroup β* := { add_left_cancel := λ x y z, quotient.induction_on₃' x y z $ λ a b c h, have h' : _ := quotient.exact' h, quotient.sound' $ by filter_upwards [h'] λ i, add_left_cancel, ..filter_product.add_semigroup } instance [add_right_cancel_semigroup β] : add_right_cancel_semigroup β* := { add_right_cancel := λ x y z, quotient.induction_on₃' x y z $ λ a b c h, have h' : _ := quotient.exact' h, quotient.sound' $ by filter_upwards [h'] λ i, add_right_cancel, ..filter_product.add_semigroup } instance [add_monoid β] : add_monoid β* := { zero_add := λ x, quotient.induction_on' x (λ a, quotient.sound'(by simp only [zero_add]; apply (setoid.iseqv _).1)), add_zero := λ x, quotient.induction_on' x (λ a, quotient.sound'(by simp only [add_zero]; apply (setoid.iseqv _).1)), ..filter_product.add_semigroup, ..filter_product.has_zero } instance [add_comm_semigroup β] : add_comm_semigroup β* := { add_comm := λ x y, quotient.induction_on₂' x y (λ a b, quotient.sound' (by simp only [add_comm]; apply (setoid.iseqv _).1)), ..filter_product.add_semigroup } instance [add_comm_monoid β] : add_comm_monoid β* := { ..filter_product.add_comm_semigroup, ..filter_product.add_monoid } instance [add_group β] : add_group β* := { add_left_neg := λ x, quotient.induction_on' x (λ a, quotient.sound' (by simp only [add_left_neg]; apply (setoid.iseqv _).1)), ..filter_product.add_monoid, ..filter_product.has_neg } instance [add_comm_group β] : add_comm_group β* := { ..filter_product.add_comm_monoid, ..filter_product.add_group } instance [has_mul β] : has_mul β* := { mul := lift₂ has_mul.mul } instance [has_one β] : has_one β* := { one := of 1 } instance [has_inv β] : has_inv β* := { inv := lift has_inv.inv } instance [semigroup β] : semigroup β* := { mul_assoc := λ x y z, quotient.induction_on₃' x y z $ λ a b c, quotient.sound' $ show {n | _ * _ * _ = _ * (_ * _)} ∈ _, by simp only [mul_assoc, eq_self_iff_true]; exact φ.univ_sets, ..filter_product.has_mul } instance [monoid β] : monoid β* := { one_mul := λ x, quotient.induction_on' x (λ a, quotient.sound' (by simp only [one_mul]; apply (setoid.iseqv _).1)), mul_one := λ x, quotient.induction_on' x (λ a, quotient.sound' (by simp only [mul_one]; apply (setoid.iseqv _).1)), ..filter_product.semigroup, ..filter_product.has_one } instance [comm_semigroup β] : comm_semigroup β* := { mul_comm := λ x y, quotient.induction_on₂' x y (λ a b, quotient.sound' (by simp only [mul_comm]; apply (setoid.iseqv _).1)), ..filter_product.semigroup } instance [comm_monoid β] : comm_monoid β* := { ..filter_product.comm_semigroup, ..filter_product.monoid } instance [group β] : group β* := { mul_left_inv := λ x, quotient.induction_on' x (λ a, quotient.sound' (by simp only [mul_left_inv]; apply (setoid.iseqv _).1)), ..filter_product.monoid, ..filter_product.has_inv } instance [comm_group β] : comm_group β* := { ..filter_product.comm_monoid, ..filter_product.group } instance [distrib β] : distrib β* := { left_distrib := λ x y z, quotient.induction_on₃' x y z (λ x y z, quotient.sound' (by simp only [left_distrib]; apply (setoid.iseqv _).1)), right_distrib := λ x y z, quotient.induction_on₃' x y z (λ x y z, quotient.sound' (by simp only [right_distrib]; apply (setoid.iseqv _).1)), ..filter_product.has_add, ..filter_product.has_mul } instance [mul_zero_class β] : mul_zero_class β* := { zero_mul := λ x, quotient.induction_on' x (λ a, quotient.sound' (by simp only [zero_mul]; apply (setoid.iseqv _).1)), mul_zero := λ x, quotient.induction_on' x (λ a, quotient.sound' (by simp only [mul_zero]; apply (setoid.iseqv _).1)), ..filter_product.has_mul, ..filter_product.has_zero } instance [semiring β] : semiring β* := { ..filter_product.add_comm_monoid, ..filter_product.monoid, ..filter_product.distrib, ..filter_product.mul_zero_class } instance [ring β] : ring β* := { ..filter_product.add_comm_group, ..filter_product.monoid, ..filter_product.distrib } instance [comm_semiring β] : comm_semiring β* := { ..filter_product.semiring, ..filter_product.comm_monoid } instance [comm_ring β] : comm_ring β* := { ..filter_product.ring, ..filter_product.comm_semigroup } instance [zero_ne_one_class β] (NT : φ ≠ ⊥) : zero_ne_one_class β* := { zero_ne_one := λ c, have c' : _ := quotient.exact' c, by { change _ ∈ _ at c', simp only [set.set_of_false, zero_ne_one, empty_in_sets_eq_bot] at c', exact NT c' }, ..filter_product.has_zero, ..filter_product.has_one } instance [division_ring β] (U : is_ultrafilter φ) : division_ring β* := { mul_inv_cancel := λ x, quotient.induction_on' x $ λ a hx, quotient.sound' $ have hx1 : _ := (not_imp_not.mpr quotient.eq'.mpr) hx, have hx2 : _ := (ultrafilter_iff_compl_mem_iff_not_mem.mp U _).mpr hx1, have h : {n : α | ¬a n = 0} ⊆ {n : α | a n * (a n)⁻¹ = 1} := by rw [set.set_of_subset_set_of]; exact λ n, division_ring.mul_inv_cancel, mem_sets_of_superset hx2 h, inv_mul_cancel := λ x, quotient.induction_on' x $ λ a hx, quotient.sound' $ have hx1 : _ := (not_imp_not.mpr quotient.eq'.mpr) hx, have hx2 : _ := (ultrafilter_iff_compl_mem_iff_not_mem.mp U _).mpr hx1, have h : {n : α | ¬a n = 0} ⊆ {n : α | (a n)⁻¹ * a n = 1} := by rw [set.set_of_subset_set_of]; exact λ n, division_ring.inv_mul_cancel, mem_sets_of_superset hx2 h, ..filter_product.ring, ..filter_product.has_inv, ..filter_product.zero_ne_one_class U.1 } instance [field β] (U : is_ultrafilter φ) : field β* := { ..filter_product.comm_ring, ..filter_product.division_ring U } noncomputable instance [discrete_field β] (U : is_ultrafilter φ) : discrete_field β* := { inv_zero := quotient.sound' $ by show _ ∈ _; simp only [inv_zero, eq_self_iff_true, (set.univ_def).symm, univ_sets], has_decidable_eq := by apply_instance, ..filter_product.field U } instance [has_le β] : has_le β* := { le := lift_rel₂ has_le.le } instance [preorder β] : preorder β* := { le_refl := λ x, quotient.induction_on' x $ λ a, show _ ∈ _, by simp only [le_refl, (set.univ_def).symm, univ_sets], le_trans := λ x y z, quotient.induction_on₃' x y z $ λ a b c hab hbc, by filter_upwards [hab, hbc] λ i, le_trans, ..filter_product.has_le} instance [partial_order β] : partial_order β* := { le_antisymm := λ x y, quotient.induction_on₂' x y $ λ a b hab hba, quotient.sound' $ have hI : {n | a n = b n} = _ ∩ _ := set.ext (λ n, le_antisymm_iff), show _ ∈ _, by rw hI; exact inter_sets _ hab hba ..filter_product.preorder } instance [linear_order β] (U : is_ultrafilter φ) : linear_order β* := { le_total := λ x y, quotient.induction_on₂' x y $ λ a b, have hS : _ ⊆ {i | b i ≤ a i} := λ i, le_of_not_le, or.cases_on (mem_or_compl_mem_of_ultrafilter U {i | a i ≤ b i}) (λ h, or.inl h) (λ h, or.inr (sets_of_superset _ h hS)) ..filter_product.partial_order } theorem of_inj (NT : φ ≠ ⊥) : function.injective (@of _ β φ) := begin intros r s rs, by_contra N, rw [of, of, of_seq, quotient.eq', bigly_equal] at rs, simp only [N, set.set_of_false, empty_in_sets_eq_bot] at rs, exact NT rs end theorem of_seq_fun (f g : α → β) (h : β → β) (H : {n : α | f n = h (g n) } ∈ φ) : of_seq f = (lift h) (@of_seq _ _ φ g) := quotient.sound' H theorem of_seq_fun₂ (f g₁ g₂ : α → β) (h : β → β → β) (H : {n : α | f n = h (g₁ n) (g₂ n) } ∈ φ) : of_seq f = (lift₂ h) (@of_seq _ _ φ g₁) (@of_seq _ _ φ g₂) := quotient.sound' H @[simp] lemma of_seq_zero [has_zero β] (f : α → β) : of_seq 0 = (0 : β*) := rfl @[simp] lemma of_seq_add [has_add β] (f g : α → β) : of_seq (f + g) = of_seq f + (of_seq g : β*) := rfl @[simp] lemma of_seq_neg [has_neg β] (f : α → β) : of_seq (-f) = - (of_seq f : β*) := rfl @[simp] lemma of_seq_one [has_one β] (f : α → β) : of_seq 1 = (1 : β*) := rfl @[simp] lemma of_seq_mul [has_mul β] (f g : α → β) : of_seq (f * g) = of_seq f * (of_seq g : β*) := rfl @[simp] lemma of_seq_inv [has_inv β] (f : α → β) : of_seq (f⁻¹) = (of_seq f : β*)⁻¹ := rfl @[simp] lemma of_eq_coe (x : β) : of x = (x : β*) := rfl lemma of_eq (x y : β) (NT : φ ≠ ⊥) : x = y ↔ of x = (of y : β*) := ⟨ λ h, by rw h, by apply of_inj NT ⟩ lemma of_ne (x y : β) (NT : φ ≠ ⊥) : x ≠ y ↔ of x ≠ (of y : β*) := by show ¬ x = y ↔ of x ≠ of y; rwa [of_eq] lemma of_eq_zero [has_zero β] (NT : φ ≠ ⊥) (x : β) : x = 0 ↔ of x = (0 : β*) := of_eq _ _ NT lemma of_ne_zero [has_zero β] (NT : φ ≠ ⊥) (x : β) : x ≠ 0 ↔ of x ≠ (0 : β*) := of_ne _ _ NT @[simp] lemma of_zero [has_zero β] : of 0 = (0 : β*) := rfl @[simp] lemma of_add [has_add β] (x y : β) : of (x + y) = of x + (of y : β*) := rfl @[simp] lemma of_neg [has_neg β] (x : β) : of (- x) = - (of x : β*) := rfl @[simp] lemma of_sub [add_group β] (x y : β) : of (x - y) = of x - (of y : β*) := rfl @[simp] lemma of_one [has_one β] : of 1 = (1 : β*) := rfl @[simp] lemma of_mul [has_mul β] (x y : β) : of (x * y) = of x * (of y : β*) := rfl @[simp] lemma of_inv [has_inv β] (x : β) : of (x⁻¹) = (of x : β*)⁻¹ := rfl @[simp] lemma of_div [division_ring β] (U : is_ultrafilter φ) (x y : β) : of (x / y) = @has_div.div _ (@has_div_of_division_ring _ (filter_product.division_ring U)) (of x) (of y) := rfl lemma of_rel_of_rel {R : β → Prop} {x : β} : R x → (lift_rel R) (of x : β*) := λ hx, by show {i | R x} ∈ _; simp only [hx]; exact univ_mem_sets lemma of_rel {R : β → Prop} {x : β} (NT: φ ≠ ⊥) : R x ↔ (lift_rel R) (of x : β*) := ⟨ of_rel_of_rel, λ hxy, by change {i | R x} ∈ _ at hxy; by_contra h; simp only [h, set.set_of_false, empty_in_sets_eq_bot] at hxy; exact NT hxy ⟩ lemma of_rel_of_rel₂ {R : β → β → Prop} {x y : β} : R x y → (lift_rel₂ R) (of x) (of y : β*) := λ hxy, by show {i | R x y} ∈ _; simp only [hxy]; exact univ_mem_sets lemma of_rel₂ {R : β → β → Prop} {x y : β} (NT: φ ≠ ⊥) : R x y ↔ (lift_rel₂ R) (of x) (of y : β*) := ⟨ of_rel_of_rel₂, λ hxy, by change {i | R x y} ∈ _ at hxy; by_contra h; simp only [h, set.set_of_false, empty_in_sets_eq_bot] at hxy; exact NT hxy ⟩ lemma of_le_of_le [has_le β] {x y : β} : x ≤ y → of x ≤ (of y : β*) := of_rel_of_rel₂ lemma of_le [has_le β] {x y : β} (NT: φ ≠ ⊥) : x ≤ y ↔ of x ≤ (of y : β*) := of_rel₂ NT lemma lt_def [K : preorder β] (U : is_ultrafilter φ) {x y : β*} : (x < y) ↔ @lift_rel₂ _ _ φ K.lt x y := ⟨ quotient.induction_on₂' x y $ λ a b ⟨hxy, hyx⟩, have hyx' : _ := (ultrafilter_iff_compl_mem_iff_not_mem.mp U _).mpr hyx, by filter_upwards [hxy, hyx'] λ i hi1 hi2, lt_iff_le_not_le.mpr ⟨hi1, hi2⟩, quotient.induction_on₂' x y $ λ a b hab, ⟨ by filter_upwards [hab] λ i, le_of_lt, λ hba, have hc : ∀ i : α, a i < b i ∧ b i ≤ a i → false := λ i ⟨h1, h2⟩, not_lt_of_le h2 h1, have h0 : ∅ = {i : α | a i < b i} ∩ {i : α | b i ≤ a i} := by simp only [set.inter_def, hc, set.set_of_false, eq_self_iff_true, set.mem_set_of_eq], U.1 $ empty_in_sets_eq_bot.mp $ by rw [h0]; exact inter_sets _ hab hba ⟩ ⟩ lemma lt_def' [K : preorder β] (U : is_ultrafilter φ) : filter_product.preorder.lt = @lift_rel₂ _ _ φ K.lt := by ext x y; exact lt_def U lemma of_lt_of_lt [preorder β] (U : is_ultrafilter φ) {x y : β} : x < y → of x < (of y : β*) := by rw lt_def U; apply of_rel_of_rel₂ lemma of_lt [preorder β] {x y : β} (U : is_ultrafilter φ) : x < y ↔ of x < (of y : β*) := by rw lt_def U; exact of_rel₂ U.1 lemma lift_id : lift id = (id : β* → β*) := funext $ λ x, quotient.induction_on' x $ by apply λ a, quotient.sound (setoid.refl _) instance [ordered_comm_group β] (U : is_ultrafilter φ) : ordered_comm_group β* := { add_le_add_left := λ x y hxy z, by revert hxy; exact quotient.induction_on₃' x y z (λ a b c hab, by filter_upwards [hab] λ i hi, by simpa), add_lt_add_left := λ x y hxy z, by revert hxy; exact quotient.induction_on₃' x y z (λ a b c hab, by rw lt_def U at hab ⊢; filter_upwards [hab] λ i hi, add_lt_add_left hi (c i)), ..filter_product.partial_order, ..filter_product.add_comm_group } instance [ordered_ring β] (U : is_ultrafilter φ) : ordered_ring β* := { mul_nonneg := λ x y, quotient.induction_on₂' x y $ λ a b ha hb, by filter_upwards [ha, hb] λ i, by simp only [set.mem_set_of_eq]; exact mul_nonneg, mul_pos := λ x y, quotient.induction_on₂' x y $ λ a b ha hb, by rw lt_def U at ha hb ⊢; filter_upwards [ha, hb] λ i, mul_pos, ..filter_product.ring, ..filter_product.ordered_comm_group U, ..filter_product.zero_ne_one_class U.1 } instance [linear_ordered_ring β] (U : is_ultrafilter φ) : linear_ordered_ring β* := { zero_lt_one := by rw lt_def U; show {i | (0 : β) < 1} ∈ _; simp only [zero_lt_one, (set.univ_def).symm, univ_sets], ..filter_product.ordered_ring U, ..filter_product.linear_order U } instance [linear_ordered_field β] (U : is_ultrafilter φ) : linear_ordered_field β* := { ..filter_product.linear_ordered_ring U, ..filter_product.field U } instance [linear_ordered_comm_ring β] (U : is_ultrafilter φ) : linear_ordered_comm_ring β* := { ..filter_product.linear_ordered_ring U, ..filter_product.comm_monoid } noncomputable instance [decidable_linear_order β] (U : is_ultrafilter φ) : decidable_linear_order β* := { decidable_le := by apply_instance, ..filter_product.linear_order U } noncomputable instance [decidable_linear_ordered_comm_group β] (U : is_ultrafilter φ) : decidable_linear_ordered_comm_group β* := { ..filter_product.ordered_comm_group U, ..filter_product.decidable_linear_order U } noncomputable instance [decidable_linear_ordered_comm_ring β] (U : is_ultrafilter φ) : decidable_linear_ordered_comm_ring β* := { ..filter_product.linear_ordered_comm_ring U, ..filter_product.decidable_linear_ordered_comm_group U } noncomputable instance [discrete_linear_ordered_field β] (U : is_ultrafilter φ) : discrete_linear_ordered_field β* := { ..filter_product.linear_ordered_field U, ..filter_product.decidable_linear_ordered_comm_ring U, ..filter_product.discrete_field U } instance [ordered_cancel_comm_monoid β] : ordered_cancel_comm_monoid β* := { add_le_add_left := λ x y hxy z, by revert hxy; exact quotient.induction_on₃' x y z (λ a b c hab, by filter_upwards [hab] λ i hi, by simpa), le_of_add_le_add_left := λ x y z, quotient.induction_on₃' x y z $ λ x y z h, by filter_upwards [h] λ i, le_of_add_le_add_left, ..filter_product.add_comm_monoid, ..filter_product.add_left_cancel_semigroup, ..filter_product.add_right_cancel_semigroup, ..filter_product.partial_order } lemma max_def [K : decidable_linear_order β] (U : is_ultrafilter φ) (x y : β*) : @max β* (filter_product.decidable_linear_order U) x y = (lift₂ max) x y := quotient.induction_on₂' x y $ λ a b, by unfold max; begin split_ifs, exact quotient.sound'(by filter_upwards [h] λ i hi, (max_eq_right hi).symm), exact quotient.sound'(by filter_upwards [@le_of_not_le _ (filter_product.linear_order U) _ _ h] λ i hi, (max_eq_left hi).symm), end lemma min_def [K : decidable_linear_order β] (U : is_ultrafilter φ) (x y : β*) : @min β* (filter_product.decidable_linear_order U) x y = (lift₂ min) x y := quotient.induction_on₂' x y $ λ a b, by unfold min; begin split_ifs, exact quotient.sound'(by filter_upwards [h] λ i hi, (min_eq_left hi).symm), exact quotient.sound'(by filter_upwards [@le_of_not_le _ (filter_product.linear_order U) _ _ h] λ i hi, (min_eq_right hi).symm), end lemma abs_def [decidable_linear_ordered_comm_group β] (U : is_ultrafilter φ) (x y : β*) : @abs _ (filter_product.decidable_linear_ordered_comm_group U) x = (lift abs) x := quotient.induction_on' x $ λ a, by unfold abs; rw max_def; exact quotient.sound' (by show {i | abs _ = _} ∈ _; simp only [eq_self_iff_true, set.univ_def.symm]; exact univ_mem_sets) @[simp] lemma of_max [decidable_linear_order β] (U : is_ultrafilter φ) (x y : β) : (of (max x y) : β*) = @max _ (filter_product.decidable_linear_order U) (of x) (of y) := begin unfold max, split_ifs, { refl }, { exact false.elim (h_1 (of_le_of_le h)) }, { exact false.elim (h ((of_le U.1).mpr h_1)) }, { refl } end @[simp] lemma of_min [decidable_linear_order β] (U : is_ultrafilter φ) (x y : β) : (of (min x y) : β*) = @min _ (filter_product.decidable_linear_order U) (of x) (of y) := begin unfold min, split_ifs, { refl }, { exact false.elim (h_1 (of_le_of_le h)) }, { exact false.elim (h ((of_le U.1).mpr h_1)) }, { refl } end @[simp] lemma of_abs [decidable_linear_ordered_comm_group β] (U : is_ultrafilter φ) (x : β) : (of (abs x) : β*) = @abs _ (filter_product.decidable_linear_ordered_comm_group U) (of x) := of_max U x (-x) end filter_product end filter
d145745a32522e58f8e7551a27605c07fee1d946
aa5a655c05e5359a70646b7154e7cac59f0b4132
/src/Lean/Elab/Declaration.lean
14a6a54aa622919cac8f83a062fe92126cf098a0
[ "Apache-2.0" ]
permissive
lambdaxymox/lean4
ae943c960a42247e06eff25c35338268d07454cb
278d47c77270664ef29715faab467feac8a0f446
refs/heads/master
1,677,891,867,340
1,612,500,005,000
1,612,500,005,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,793
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Util.CollectLevelParams import Lean.Elab.DeclUtil import Lean.Elab.DefView import Lean.Elab.Inductive import Lean.Elab.Structure import Lean.Elab.MutualDef import Lean.Elab.DeclarationRange namespace Lean.Elab.Command open Meta /- Auxiliary function for `expandDeclNamespace?` -/ def expandDeclIdNamespace? (declId : Syntax) : Option (Name × Syntax) := let (id, optUnivDeclStx) := expandDeclIdCore declId let scpView := extractMacroScopes id match scpView.name with | Name.str Name.anonymous s _ => none | Name.str pre s _ => let nameNew := { scpView with name := Name.mkSimple s }.review if declId.isIdent then some (pre, mkIdentFrom declId nameNew) else some (pre, declId.setArg 0 (mkIdentFrom declId nameNew)) | _ => none /- given declarations such as `@[...] def Foo.Bla.f ...` return `some (Foo.Bla, @[...] def f ...)` -/ def expandDeclNamespace? (stx : Syntax) : Option (Name × Syntax) := if !stx.isOfKind `Lean.Parser.Command.declaration then none else let decl := stx[1] let k := decl.getKind if k == `Lean.Parser.Command.abbrev || k == `Lean.Parser.Command.def || k == `Lean.Parser.Command.theorem || k == `Lean.Parser.Command.constant || k == `Lean.Parser.Command.axiom || k == `Lean.Parser.Command.inductive || k == `Lean.Parser.Command.classInductive || k == `Lean.Parser.Command.structure then match expandDeclIdNamespace? decl[1] with | some (ns, declId) => some (ns, stx.setArg 1 (decl.setArg 1 declId)) | none => none else if k == `Lean.Parser.Command.instance then let optDeclId := decl[3] if optDeclId.isNone then none else match expandDeclIdNamespace? optDeclId[0] with | some (ns, declId) => some (ns, stx.setArg 1 (decl.setArg 3 (optDeclId.setArg 0 declId))) | none => none else none def elabAxiom (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do -- parser! "axiom " >> declId >> declSig let declId := stx[1] let (binders, typeStx) := expandDeclSig stx[2] let scopeLevelNames ← getLevelNames let ⟨name, declName, allUserLevelNames⟩ ← expandDeclId declId modifiers addDeclarationRanges declName stx runTermElabM declName fun vars => Term.withLevelNames allUserLevelNames $ Term.elabBinders binders.getArgs fun xs => do Term.applyAttributesAt declName modifiers.attrs AttributeApplicationTime.beforeElaboration let type ← Term.elabType typeStx Term.synthesizeSyntheticMVarsNoPostponing let type ← instantiateMVars type let type ← mkForallFVars xs type let (type, _) ← mkForallUsedOnly vars type let (type, _) ← Term.levelMVarToParam type let usedParams := collectLevelParams {} type |>.params match sortDeclLevelParams scopeLevelNames allUserLevelNames usedParams with | Except.error msg => throwErrorAt stx msg | Except.ok levelParams => let decl := Declaration.axiomDecl { name := declName, levelParams := levelParams, type := type, isUnsafe := modifiers.isUnsafe } Term.ensureNoUnassignedMVars decl addDecl decl Term.applyAttributesAt declName modifiers.attrs AttributeApplicationTime.afterTypeChecking if isExtern (← getEnv) declName then compileDecl decl Term.applyAttributesAt declName modifiers.attrs AttributeApplicationTime.afterCompilation /- parser! "inductive " >> declId >> optDeclSig >> optional ":=" >> many ctor parser! atomic (group ("class " >> "inductive ")) >> declId >> optDeclSig >> optional ":=" >> many ctor >> optDeriving -/ private def inductiveSyntaxToView (modifiers : Modifiers) (decl : Syntax) : CommandElabM InductiveView := do checkValidInductiveModifier modifiers let (binders, type?) := expandOptDeclSig decl[2] let declId := decl[1] let ⟨name, declName, levelNames⟩ ← expandDeclId declId modifiers addDeclarationRanges declName decl let ctors ← decl[4].getArgs.mapM fun ctor => withRef ctor do -- def ctor := parser! " | " >> declModifiers >> ident >> optional inferMod >> optDeclSig let ctorModifiers ← elabModifiers ctor[1] if ctorModifiers.isPrivate && modifiers.isPrivate then throwError "invalid 'private' constructor in a 'private' inductive datatype" if ctorModifiers.isProtected && modifiers.isPrivate then throwError "invalid 'protected' constructor in a 'private' inductive datatype" checkValidCtorModifier ctorModifiers let ctorName := ctor.getIdAt 2 let ctorName := declName ++ ctorName let ctorName ← withRef ctor[2] $ applyVisibility ctorModifiers.visibility ctorName let inferMod := !ctor[3].isNone let (binders, type?) := expandOptDeclSig ctor[4] addDocString' ctorName ctorModifiers.docString? addAuxDeclarationRanges ctorName ctor ctor[2] pure { ref := ctor, modifiers := ctorModifiers, declName := ctorName, inferMod := inferMod, binders := binders, type? := type? : CtorView } let classes ← getOptDerivingClasses decl[5] pure { ref := decl modifiers := modifiers shortDeclName := name declName := declName levelNames := levelNames binders := binders type? := type? ctors := ctors derivingClasses := classes } private def classInductiveSyntaxToView (modifiers : Modifiers) (decl : Syntax) : CommandElabM InductiveView := inductiveSyntaxToView modifiers decl def elabInductive (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do let v ← inductiveSyntaxToView modifiers stx elabInductiveViews #[v] def elabClassInductive (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do let modifiers := modifiers.addAttribute { name := `class } let v ← classInductiveSyntaxToView modifiers stx elabInductiveViews #[v] @[builtinCommandElab declaration] def elabDeclaration : CommandElab := fun stx => match expandDeclNamespace? stx with | some (ns, newStx) => do let ns := mkIdentFrom stx ns let newStx ← `(namespace $ns:ident $newStx end $ns:ident) withMacroExpansion stx newStx $ elabCommand newStx | none => do let modifiers ← elabModifiers stx[0] let decl := stx[1] let declKind := decl.getKind if declKind == `Lean.Parser.Command.«axiom» then elabAxiom modifiers decl else if declKind == `Lean.Parser.Command.«inductive» then elabInductive modifiers decl else if declKind == `Lean.Parser.Command.classInductive then elabClassInductive modifiers decl else if declKind == `Lean.Parser.Command.«structure» then elabStructure modifiers decl else if isDefLike decl then elabMutualDef #[stx] else throwError "unexpected declaration" /- Return true if all elements of the mutual-block are inductive declarations. -/ private def isMutualInductive (stx : Syntax) : Bool := stx[1].getArgs.all fun elem => let decl := elem[1] let declKind := decl.getKind declKind == `Lean.Parser.Command.inductive private def elabMutualInductive (elems : Array Syntax) : CommandElabM Unit := do let views ← elems.mapM fun stx => do let modifiers ← elabModifiers stx[0] inductiveSyntaxToView modifiers stx[1] elabInductiveViews views /- Return true if all elements of the mutual-block are definitions/theorems/abbrevs. -/ private def isMutualDef (stx : Syntax) : Bool := stx[1].getArgs.all fun elem => let decl := elem[1] isDefLike decl private def isMutualPreambleCommand (stx : Syntax) : Bool := let k := stx.getKind k == `Lean.Parser.Command.variable || k == `Lean.Parser.Command.variables || k == `Lean.Parser.Command.universe || k == `Lean.Parser.Command.universes || k == `Lean.Parser.Command.check || k == `Lean.Parser.Command.set_option || k == `Lean.Parser.Command.open private partial def splitMutualPreamble (elems : Array Syntax) : Option (Array Syntax × Array Syntax) := let rec loop (i : Nat) : Option (Array Syntax × Array Syntax) := if h : i < elems.size then let elem := elems.get ⟨i, h⟩ if isMutualPreambleCommand elem then loop (i+1) else if i == 0 then none -- `mutual` block does not contain any preamble commands else some (elems[0:i], elems[i:elems.size]) else none -- a `mutual` block containing only preamble commands is not a valid `mutual` block loop 0 @[builtinMacro Lean.Parser.Command.mutual] def expandMutualNamespace : Macro := fun stx => do let mut ns? := none let mut elemsNew := #[] for elem in stx[1].getArgs do match ns?, expandDeclNamespace? elem with | _, none => elemsNew := elemsNew.push elem | none, some (ns, elem) => ns? := some ns; elemsNew := elemsNew.push elem | some nsCurr, some (nsNew, elem) => if nsCurr == nsNew then elemsNew := elemsNew.push elem else Macro.throwErrorAt elem s!"conflicting namespaces in mutual declaration, using namespace '{nsNew}', but used '{nsCurr}' in previous declaration" match ns? with | some ns => let ns := mkIdentFrom stx ns let stxNew := stx.setArg 1 (mkNullNode elemsNew) `(namespace $ns:ident $stxNew end $ns:ident) | none => Macro.throwUnsupported @[builtinMacro Lean.Parser.Command.mutual] def expandMutualElement : Macro := fun stx => do let mut elemsNew := #[] let mut modified := false for elem in stx[1].getArgs do match (← expandMacro? elem) with | some elemNew => elemsNew := elemsNew.push elemNew; modified := true | none => elemsNew := elemsNew.push elem if modified then pure $ stx.setArg 1 (mkNullNode elemsNew) else Macro.throwUnsupported @[builtinMacro Lean.Parser.Command.mutual] def expandMutualPreamble : Macro := fun stx => match splitMutualPreamble stx[1].getArgs with | none => Macro.throwUnsupported | some (preamble, rest) => do let secCmd ← `(section) let newMutual := stx.setArg 1 (mkNullNode rest) let endCmd ← `(end) pure $ mkNullNode (#[secCmd] ++ preamble ++ #[newMutual] ++ #[endCmd]) @[builtinCommandElab «mutual»] def elabMutual : CommandElab := fun stx => do if isMutualInductive stx then elabMutualInductive stx[1].getArgs else if isMutualDef stx then elabMutualDef stx[1].getArgs else throwError "invalid mutual block" /- parser! "attribute " >> "[" >> sepBy1 Term.attrInstance ", " >> "]" >> many1 ident -/ @[builtinCommandElab «attribute»] def elabAttr : CommandElab := fun stx => do let attrs ← elabAttrs stx[2] let idents := stx[4].getArgs for ident in idents do withRef ident $ liftTermElabM none do let declName ← resolveGlobalConstNoOverload ident.getId Term.applyAttributes declName attrs def expandInitCmd (builtin : Bool) : Macro := fun stx => let optHeader := stx[1] let doSeq := stx[2] let attrId := mkIdentFrom stx $ if builtin then `builtinInit else `init if optHeader.isNone then `(@[$attrId:ident]def initFn : IO Unit := do $doSeq) else let id := optHeader[0] let type := optHeader[1][1] `(def initFn : IO $type := do $doSeq @[$attrId:ident initFn]constant $id : $type) @[builtinMacro Lean.Parser.Command.«initialize»] def expandInitialize : Macro := expandInitCmd (builtin := false) @[builtinMacro Lean.Parser.Command.«builtin_initialize»] def expandBuiltinInitialize : Macro := expandInitCmd (builtin := true) end Lean.Elab.Command
f911bd1fb12ef950f101fca4903ad50f8f17c2ac
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/stage0/src/Lean/Meta/Tactic/Constructor.lean
14fbf517995b5d9cef2a1053d3c94572d050acc1
[ "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
1,164
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.Meta.Check import Lean.Meta.Tactic.Util import Lean.Meta.Tactic.Apply namespace Lean.Meta def existsIntro (mvarId : MVarId) (w : Expr) : MetaM MVarId := do withMVarContext mvarId do checkNotAssigned mvarId `exists let target ← getMVarType' mvarId matchConstStruct target.getAppFn (fun _ => throwTacticEx `exists mvarId "target is not an inductive datatype with one constructor") fun ival us cval => do if cval.numFields < 2 then throwTacticEx `exists mvarId "constructor must have at least two fields" let ctor := mkAppN (Lean.mkConst cval.name us) target.getAppArgs[:cval.numParams] let ctorType ← inferType ctor let (mvars, _, _) ← forallMetaTelescopeReducing ctorType (some (cval.numFields-2)) let f := mkAppN ctor mvars checkApp f w let [mvarId] ← apply mvarId <| mkApp f w | throwTacticEx `exists mvarId "unexpected number of subgoals" pure mvarId end Lean.Meta
02c32f4cbf8b41a57d596d49df6a0ae6d33acd0d
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Meta/Tactic/Replace.lean
1089cd630bc48224757ec92e3f208bf338184d9f
[ "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
8,414
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Util.ForEachExpr import Lean.Meta.AppBuilder import Lean.Meta.MatchUtil import Lean.Meta.Tactic.Util import Lean.Meta.Tactic.Revert import Lean.Meta.Tactic.Intro import Lean.Meta.Tactic.Clear import Lean.Meta.Tactic.Assert namespace Lean.Meta /-- Convert the given goal `Ctx |- target` into `Ctx |- targetNew` using an equality proof `eqProof : target = targetNew`. It assumes `eqProof` has type `target = targetNew` -/ def _root_.Lean.MVarId.replaceTargetEq (mvarId : MVarId) (targetNew : Expr) (eqProof : Expr) : MetaM MVarId := mvarId.withContext do mvarId.checkNotAssigned `replaceTarget let tag ← mvarId.getTag let mvarNew ← mkFreshExprSyntheticOpaqueMVar targetNew tag let target ← mvarId.getType let u ← getLevel target let eq ← mkEq target targetNew let newProof ← mkExpectedTypeHint eqProof eq let val := mkAppN (Lean.mkConst `Eq.mpr [u]) #[target, targetNew, newProof, mvarNew] mvarId.assign val return mvarNew.mvarId! @[deprecated MVarId.replaceTargetEq] def replaceTargetEq (mvarId : MVarId) (targetNew : Expr) (eqProof : Expr) : MetaM MVarId := mvarId.replaceTargetEq targetNew eqProof /-- Convert the given goal `Ctx |- target` into `Ctx |- targetNew`. It assumes the goals are definitionally equal. We use the proof term ``` @id target mvarNew ``` to create a checkpoint. -/ def _root_.Lean.MVarId.replaceTargetDefEq (mvarId : MVarId) (targetNew : Expr) : MetaM MVarId := mvarId.withContext do mvarId.checkNotAssigned `change let target ← mvarId.getType if target == targetNew then return mvarId else let tag ← mvarId.getTag let mvarNew ← mkFreshExprSyntheticOpaqueMVar targetNew tag let newVal ← mkExpectedTypeHint mvarNew target mvarId.assign newVal return mvarNew.mvarId! @[deprecated MVarId.replaceTargetDefEq] def replaceTargetDefEq (mvarId : MVarId) (targetNew : Expr) : MetaM MVarId := mvarId.replaceTargetDefEq targetNew private def replaceLocalDeclCore (mvarId : MVarId) (fvarId : FVarId) (typeNew : Expr) (eqProof : Expr) : MetaM AssertAfterResult := mvarId.withContext do let localDecl ← fvarId.getDecl let typeNewPr ← mkEqMP eqProof (mkFVar fvarId) -- `typeNew` may contain variables that occur after `fvarId`. -- Thus, we use the auxiliary function `findMaxFVar` to ensure `typeNew` is well-formed at the position we are inserting it. let (_, localDecl') ← findMaxFVar typeNew |>.run localDecl let result ← mvarId.assertAfter localDecl'.fvarId localDecl.userName typeNew typeNewPr (do let mvarIdNew ← result.mvarId.clear fvarId pure { result with mvarId := mvarIdNew }) <|> pure result where findMaxFVar (e : Expr) : StateRefT LocalDecl MetaM Unit := e.forEach' fun e => do if e.isFVar then let localDecl' ← e.fvarId!.getDecl modify fun localDecl => if localDecl'.index > localDecl.index then localDecl' else localDecl return false else return e.hasFVar /-- Replace type of the local declaration with id `fvarId` with one with the same user-facing name, but with type `typeNew`. This method assumes `eqProof` is a proof that type of `fvarId` is equal to `typeNew`. This tactic actually adds a new declaration and (try to) clear the old one. If the old one cannot be cleared, then at least its user-facing name becomes inaccessible. Remark: the new declaration is added immediately after `fvarId`. `typeNew` must be well-formed at `fvarId`, but `eqProof` may contain variables declared after `fvarId`. -/ abbrev _root_.Lean.MVarId.replaceLocalDecl (mvarId : MVarId) (fvarId : FVarId) (typeNew : Expr) (eqProof : Expr) : MetaM AssertAfterResult := replaceLocalDeclCore mvarId fvarId typeNew eqProof @[deprecated MVarId.replaceLocalDecl] abbrev replaceLocalDecl (mvarId : MVarId) (fvarId : FVarId) (typeNew : Expr) (eqProof : Expr) : MetaM AssertAfterResult := mvarId.replaceLocalDecl fvarId typeNew eqProof /-- Replace the type of `fvarId` at `mvarId` with `typeNew`. Remark: this method assumes that `typeNew` is definitionally equal to the current type of `fvarId`. -/ def _root_.Lean.MVarId.replaceLocalDeclDefEq (mvarId : MVarId) (fvarId : FVarId) (typeNew : Expr) : MetaM MVarId := do mvarId.withContext do if typeNew == (← fvarId.getType) then return mvarId else let mvarDecl ← mvarId.getDecl let lctxNew := (← getLCtx).modifyLocalDecl fvarId (·.setType typeNew) let mvarNew ← mkFreshExprMVarAt lctxNew (← getLocalInstances) mvarDecl.type mvarDecl.kind mvarDecl.userName mvarId.assign mvarNew return mvarNew.mvarId! @[deprecated MVarId.replaceLocalDeclDefEq] def replaceLocalDeclDefEq (mvarId : MVarId) (fvarId : FVarId) (typeNew : Expr) : MetaM MVarId := do mvarId.replaceLocalDeclDefEq fvarId typeNew /-- Replace the target type of `mvarId` with `typeNew`. If `checkDefEq = false`, this method assumes that `typeNew` is definitionally equal to the current target type. If `checkDefEq = true`, throw an error if `typeNew` is not definitionally equal to the current target type. -/ def _root_.Lean.MVarId.change (mvarId : MVarId) (targetNew : Expr) (checkDefEq := true) : MetaM MVarId := mvarId.withContext do let target ← mvarId.getType if checkDefEq then unless (← isDefEq target targetNew) do throwTacticEx `change mvarId m!"given type{indentExpr targetNew}\nis not definitionally equal to{indentExpr target}" mvarId.replaceTargetDefEq targetNew @[deprecated MVarId.change] def change (mvarId : MVarId) (targetNew : Expr) (checkDefEq := true) : MetaM MVarId := mvarId.withContext do mvarId.change targetNew checkDefEq /-- Replace the type of the free variable `fvarId` with `typeNew`. If `checkDefEq = false`, this method assumes that `typeNew` is definitionally equal to `fvarId` type. If `checkDefEq = true`, throw an error if `typeNew` is not definitionally equal to `fvarId` type. -/ def _root_.Lean.MVarId.changeLocalDecl (mvarId : MVarId) (fvarId : FVarId) (typeNew : Expr) (checkDefEq := true) : MetaM MVarId := do mvarId.checkNotAssigned `changeLocalDecl let (xs, mvarId) ← mvarId.revert #[fvarId] true mvarId.withContext do let numReverted := xs.size let target ← mvarId.getType let check (typeOld : Expr) : MetaM Unit := do if checkDefEq then unless (← isDefEq typeNew typeOld) do throwTacticEx `changeHypothesis mvarId m!"given type{indentExpr typeNew}\nis not definitionally equal to{indentExpr typeOld}" let finalize (targetNew : Expr) : MetaM MVarId := do let mvarId ← mvarId.replaceTargetDefEq targetNew let (_, mvarId) ← mvarId.introNP numReverted pure mvarId match target with | .forallE n d b c => do check d; finalize (mkForall n c typeNew b) | .letE n t v b _ => do check t; finalize (mkLet n typeNew v b) | _ => throwTacticEx `changeHypothesis mvarId "unexpected auxiliary target" @[deprecated MVarId.changeLocalDecl] def changeLocalDecl (mvarId : MVarId) (fvarId : FVarId) (typeNew : Expr) (checkDefEq := true) : MetaM MVarId := do mvarId.changeLocalDecl fvarId typeNew checkDefEq /-- Modify `mvarId` target type using `f`. -/ def _root_.Lean.MVarId.modifyTarget (mvarId : MVarId) (f : Expr → MetaM Expr) : MetaM MVarId := do mvarId.withContext do mvarId.checkNotAssigned `modifyTarget mvarId.change (← f (← mvarId.getType)) (checkDefEq := false) @[deprecated modifyTarget] def modifyTarget (mvarId : MVarId) (f : Expr → MetaM Expr) : MetaM MVarId := do mvarId.modifyTarget f /-- Modify `mvarId` target type left-hand-side using `f`. Throw an error if target type is not an equality. -/ def _root_.Lean.MVarId.modifyTargetEqLHS (mvarId : MVarId) (f : Expr → MetaM Expr) : MetaM MVarId := do mvarId.modifyTarget fun target => do if let some (_, lhs, rhs) ← matchEq? target then mkEq (← f lhs) rhs else throwTacticEx `modifyTargetEqLHS mvarId m!"equality expected{indentExpr target}" @[deprecated MVarId.modifyTargetEqLHS] def modifyTargetEqLHS (mvarId : MVarId) (f : Expr → MetaM Expr) : MetaM MVarId := do mvarId.modifyTargetEqLHS f end Lean.Meta
c945d769341c27f3af2c91481109befb3cc46588
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/calculus/fderiv_symmetric.lean
c631d08764501220499c2579a1f89a7351fe70f1
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
19,061
lean
/- Copyright (c) 2021 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.calculus.mean_value /-! # Symmetry of the second derivative > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We show that, over the reals, the second derivative is symmetric. The most precise result is `convex.second_derivative_within_at_symmetric`. It asserts that, if a function is differentiable inside a convex set `s` with nonempty interior, and has a second derivative within `s` at a point `x`, then this second derivative at `x` is symmetric. Note that this result does not require continuity of the first derivative. The following particular cases of this statement are especially relevant: `second_derivative_symmetric_of_eventually` asserts that, if a function is differentiable on a neighborhood of `x`, and has a second derivative at `x`, then this second derivative is symmetric. `second_derivative_symmetric` asserts that, if a function is differentiable, and has a second derivative at `x`, then this second derivative is symmetric. ## Implementation note For the proof, we obtain an asymptotic expansion to order two of `f (x + v + w) - f (x + v)`, by using the mean value inequality applied to a suitable function along the segment `[x + v, x + v + w]`. This expansion involves `f'' ⬝ w` as we move along a segment directed by `w` (see `convex.taylor_approx_two_segment`). Consider the alternate sum `f (x + v + w) + f x - f (x + v) - f (x + w)`, corresponding to the values of `f` along a rectangle based at `x` with sides `v` and `w`. One can write it using the two sides directed by `w`, as `(f (x + v + w) - f (x + v)) - (f (x + w) - f x)`. Together with the previous asymptotic expansion, one deduces that it equals `f'' v w + o(1)` when `v, w` tends to `0`. Exchanging the roles of `v` and `w`, one instead gets an asymptotic expansion `f'' w v`, from which the equality `f'' v w = f'' w v` follows. In our most general statement, we only assume that `f` is differentiable inside a convex set `s`, so a few modifications have to be made. Since we don't assume continuity of `f` at `x`, we consider instead the rectangle based at `x + v + w` with sides `v` and `w`, in `convex.is_o_alternate_sum_square`, but the argument is essentially the same. It only works when `v` and `w` both point towards the interior of `s`, to make sure that all the sides of the rectangle are contained in `s` by convexity. The general case follows by linearity, though. -/ open asymptotics set open_locale topology variables {E F : Type*} [normed_add_comm_group E] [normed_space ℝ E] [normed_add_comm_group F] [normed_space ℝ F] {s : set E} (s_conv : convex ℝ s) {f : E → F} {f' : E → (E →L[ℝ] F)} {f'' : E →L[ℝ] (E →L[ℝ] F)} (hf : ∀ x ∈ interior s, has_fderiv_at f (f' x) x) {x : E} (xs : x ∈ s) (hx : has_fderiv_within_at f' f'' (interior s) x) include s_conv xs hx hf /-- Assume that `f` is differentiable inside a convex set `s`, and that its derivative `f'` is differentiable at a point `x`. Then, given two vectors `v` and `w` pointing inside `s`, one can Taylor-expand to order two the function `f` on the segment `[x + h v, x + h (v + w)]`, giving a bilinear estimate for `f (x + hv + hw) - f (x + hv)` in terms of `f' w` and of `f'' ⬝ w`, up to `o(h^2)`. This is a technical statement used to show that the second derivative is symmetric. -/ lemma convex.taylor_approx_two_segment {v w : E} (hv : x + v ∈ interior s) (hw : x + v + w ∈ interior s) : (λ h : ℝ, f (x + h • v + h • w) - f (x + h • v) - h • f' x w - h^2 • f'' v w - (h^2/2) • f'' w w) =o[𝓝[>] 0] (λ h, h^2) := begin -- it suffices to check that the expression is bounded by `ε * ((‖v‖ + ‖w‖) * ‖w‖) * h^2` for -- small enough `h`, for any positive `ε`. apply is_o.trans_is_O (is_o_iff.2 (λ ε εpos, _)) (is_O_const_mul_self ((‖v‖ + ‖w‖) * ‖w‖) _ _), -- consider a ball of radius `δ` around `x` in which the Taylor approximation for `f''` is -- good up to `δ`. rw [has_fderiv_within_at, has_fderiv_at_filter, is_o_iff] at hx, rcases metric.mem_nhds_within_iff.1 (hx εpos) with ⟨δ, δpos, sδ⟩, have E1 : ∀ᶠ h in 𝓝[>] (0:ℝ), h * (‖v‖ + ‖w‖) < δ, { have : filter.tendsto (λ h, h * (‖v‖ + ‖w‖)) (𝓝[>] (0:ℝ)) (𝓝 (0 * (‖v‖ + ‖w‖))) := (continuous_id.mul continuous_const).continuous_within_at, apply (tendsto_order.1 this).2 δ, simpa only [zero_mul] using δpos }, have E2 : ∀ᶠ h in 𝓝[>] (0:ℝ), (h : ℝ) < 1 := mem_nhds_within_Ioi_iff_exists_Ioo_subset.2 ⟨(1 : ℝ), by simp only [mem_Ioi, zero_lt_one], λ x hx, hx.2⟩, filter_upwards [E1, E2, self_mem_nhds_within] with h hδ h_lt_1 hpos, -- we consider `h` small enough that all points under consideration belong to this ball, -- and also with `0 < h < 1`. replace hpos : 0 < h := hpos, have xt_mem : ∀ t ∈ Icc (0 : ℝ) 1, x + h • v + (t * h) • w ∈ interior s, { assume t ht, have : x + h • v ∈ interior s := s_conv.add_smul_mem_interior xs hv ⟨hpos, h_lt_1.le⟩, rw [← smul_smul], apply s_conv.interior.add_smul_mem this _ ht, rw add_assoc at hw, rw [add_assoc, ← smul_add], exact s_conv.add_smul_mem_interior xs hw ⟨hpos, h_lt_1.le⟩ }, -- define a function `g` on `[0,1]` (identified with `[v, v + w]`) such that `g 1 - g 0` is the -- quantity to be estimated. We will check that its derivative is given by an explicit -- expression `g'`, that we can bound. Then the desired bound for `g 1 - g 0` follows from the -- mean value inequality. let g := λ t, f (x + h • v + (t * h) • w) - (t * h) • f' x w - (t * h^2) • f'' v w - ((t * h)^2/2) • f'' w w, set g' := λ t, f' (x + h • v + (t * h) • w) (h • w) - h • f' x w - h^2 • f'' v w - (t * h^2) • f'' w w with hg', -- check that `g'` is the derivative of `g`, by a straightforward computation have g_deriv : ∀ t ∈ Icc (0 : ℝ) 1, has_deriv_within_at g (g' t) (Icc 0 1) t, { assume t ht, apply_rules [has_deriv_within_at.sub, has_deriv_within_at.add], { refine (hf _ _).comp_has_deriv_within_at _ _, { exact xt_mem t ht }, apply_rules [has_deriv_at.has_deriv_within_at, has_deriv_at.const_add, has_deriv_at.smul_const, has_deriv_at_mul_const] }, { apply_rules [has_deriv_at.has_deriv_within_at, has_deriv_at.smul_const, has_deriv_at_mul_const] }, { apply_rules [has_deriv_at.has_deriv_within_at, has_deriv_at.smul_const, has_deriv_at_mul_const] }, { suffices H : has_deriv_within_at (λ u, ((u * h) ^ 2 / 2) • f'' w w) (((((2 : ℕ) : ℝ) * (t * h) ^ (2 - 1) * (1 * h))/2) • f'' w w) (Icc 0 1) t, { convert H using 2, simp only [one_mul, nat.cast_bit0, pow_one, nat.cast_one], ring }, apply_rules [has_deriv_at.has_deriv_within_at, has_deriv_at.smul_const, has_deriv_at_id', has_deriv_at.pow, has_deriv_at.mul_const] } }, -- check that `g'` is uniformly bounded, with a suitable bound `ε * ((‖v‖ + ‖w‖) * ‖w‖) * h^2`. have g'_bound : ∀ t ∈ Ico (0 : ℝ) 1, ‖g' t‖ ≤ ε * ((‖v‖ + ‖w‖) * ‖w‖) * h^2, { assume t ht, have I : ‖h • v + (t * h) • w‖ ≤ h * (‖v‖ + ‖w‖) := calc ‖h • v + (t * h) • w‖ ≤ ‖h • v‖ + ‖(t * h) • w‖ : norm_add_le _ _ ... = h * ‖v‖ + t * (h * ‖w‖) : by simp only [norm_smul, real.norm_eq_abs, hpos.le, abs_of_nonneg, abs_mul, ht.left, mul_assoc] ... ≤ h * ‖v‖ + 1 * (h * ‖w‖) : add_le_add le_rfl (mul_le_mul_of_nonneg_right ht.2.le (mul_nonneg hpos.le (norm_nonneg _))) ... = h * (‖v‖ + ‖w‖) : by ring, calc ‖g' t‖ = ‖(f' (x + h • v + (t * h) • w) - f' x - f'' (h • v + (t * h) • w)) (h • w)‖ : begin rw hg', have : h * (t * h) = t * (h * h), by ring, simp only [continuous_linear_map.coe_sub', continuous_linear_map.map_add, pow_two, continuous_linear_map.add_apply, pi.smul_apply, smul_sub, smul_add, smul_smul, ← sub_sub, continuous_linear_map.coe_smul', pi.sub_apply, continuous_linear_map.map_smul, this] end ... ≤ ‖f' (x + h • v + (t * h) • w) - f' x - f'' (h • v + (t * h) • w)‖ * ‖h • w‖ : continuous_linear_map.le_op_norm _ _ ... ≤ (ε * ‖h • v + (t * h) • w‖) * (‖h • w‖) : begin apply mul_le_mul_of_nonneg_right _ (norm_nonneg _), have H : x + h • v + (t * h) • w ∈ metric.ball x δ ∩ interior s, { refine ⟨_, xt_mem t ⟨ht.1, ht.2.le⟩⟩, rw [add_assoc, add_mem_ball_iff_norm], exact I.trans_lt hδ }, simpa only [mem_set_of_eq, add_assoc x, add_sub_cancel'] using sδ H, end ... ≤ (ε * (‖h • v‖ + ‖h • w‖)) * (‖h • w‖) : begin apply mul_le_mul_of_nonneg_right _ (norm_nonneg _), apply mul_le_mul_of_nonneg_left _ (εpos.le), apply (norm_add_le _ _).trans, refine add_le_add le_rfl _, simp only [norm_smul, real.norm_eq_abs, abs_mul, abs_of_nonneg, ht.1, hpos.le, mul_assoc], exact mul_le_of_le_one_left (mul_nonneg hpos.le (norm_nonneg _)) ht.2.le, end ... = ε * ((‖v‖ + ‖w‖) * ‖w‖) * h^2 : by { simp only [norm_smul, real.norm_eq_abs, abs_mul, abs_of_nonneg, hpos.le], ring } }, -- conclude using the mean value inequality have I : ‖g 1 - g 0‖ ≤ ε * ((‖v‖ + ‖w‖) * ‖w‖) * h^2, by simpa only [mul_one, sub_zero] using norm_image_sub_le_of_norm_deriv_le_segment' g_deriv g'_bound 1 (right_mem_Icc.2 zero_le_one), convert I using 1, { congr' 1, dsimp only [g], simp only [nat.one_ne_zero, add_zero, one_mul, zero_div, zero_mul, sub_zero, zero_smul, ne.def, not_false_iff, bit0_eq_zero, zero_pow'], abel }, { simp only [real.norm_eq_abs, abs_mul, add_nonneg (norm_nonneg v) (norm_nonneg w), abs_of_nonneg, mul_assoc, pow_bit0_abs, norm_nonneg, abs_pow] } end /-- One can get `f'' v w` as the limit of `h ^ (-2)` times the alternate sum of the values of `f` along the vertices of a quadrilateral with sides `h v` and `h w` based at `x`. In a setting where `f` is not guaranteed to be continuous at `f`, we can still get this if we use a quadrilateral based at `h v + h w`. -/ lemma convex.is_o_alternate_sum_square {v w : E} (h4v : x + (4 : ℝ) • v ∈ interior s) (h4w : x + (4 : ℝ) • w ∈ interior s) : (λ h : ℝ, f (x + h • (2 • v + 2 • w)) + f (x + h • (v + w)) - f (x + h • (2 • v + w)) - f (x + h • (v + 2 • w)) - h^2 • f'' v w) =o[𝓝[>] 0] (λ h, h^2) := begin have A : (1 : ℝ)/2 ∈ Ioc (0 : ℝ) 1 := ⟨by norm_num, by norm_num⟩, have B : (1 : ℝ)/2 ∈ Icc (0 : ℝ) 1 := ⟨by norm_num, by norm_num⟩, have C : ∀ (w : E), (2 : ℝ) • w = 2 • w := λ w, by simp only [two_smul], have h2v2w : x + (2 : ℝ) • v + (2 : ℝ) • w ∈ interior s, { convert s_conv.interior.add_smul_sub_mem h4v h4w B using 1, simp only [smul_sub, smul_smul, one_div, add_sub_add_left_eq_sub, mul_add, add_smul], norm_num, simp only [show (4 : ℝ) = (2 : ℝ) + (2 : ℝ), by norm_num, add_smul], abel }, have h2vww : x + (2 • v + w) + w ∈ interior s, { convert h2v2w using 1, simp only [two_smul], abel }, have h2v : x + (2 : ℝ) • v ∈ interior s, { convert s_conv.add_smul_sub_mem_interior xs h4v A using 1, simp only [smul_smul, one_div, add_sub_cancel', add_right_inj], norm_num }, have h2w : x + (2 : ℝ) • w ∈ interior s, { convert s_conv.add_smul_sub_mem_interior xs h4w A using 1, simp only [smul_smul, one_div, add_sub_cancel', add_right_inj], norm_num }, have hvw : x + (v + w) ∈ interior s, { convert s_conv.add_smul_sub_mem_interior xs h2v2w A using 1, simp only [smul_smul, one_div, add_sub_cancel', add_right_inj, smul_add, smul_sub], norm_num, abel }, have h2vw : x + (2 • v + w) ∈ interior s, { convert s_conv.interior.add_smul_sub_mem h2v h2v2w B using 1, simp only [smul_add, smul_sub, smul_smul, ← C], norm_num, abel }, have hvww : x + (v + w) + w ∈ interior s, { convert s_conv.interior.add_smul_sub_mem h2w h2v2w B using 1, simp only [one_div, add_sub_cancel', inv_smul_smul₀, add_sub_add_right_eq_sub, ne.def, not_false_iff, bit0_eq_zero, one_ne_zero], rw two_smul, abel }, have TA1 := s_conv.taylor_approx_two_segment hf xs hx h2vw h2vww, have TA2 := s_conv.taylor_approx_two_segment hf xs hx hvw hvww, convert TA1.sub TA2, ext h, simp only [two_smul, smul_add, ← add_assoc, continuous_linear_map.map_add, continuous_linear_map.add_apply, pi.smul_apply, continuous_linear_map.coe_smul', continuous_linear_map.map_smul], abel, end /-- Assume that `f` is differentiable inside a convex set `s`, and that its derivative `f'` is differentiable at a point `x`. Then, given two vectors `v` and `w` pointing inside `s`, one has `f'' v w = f'' w v`. Superseded by `convex.second_derivative_within_at_symmetric`, which removes the assumption that `v` and `w` point inside `s`. -/ lemma convex.second_derivative_within_at_symmetric_of_mem_interior {v w : E} (h4v : x + (4 : ℝ) • v ∈ interior s) (h4w : x + (4 : ℝ) • w ∈ interior s) : f'' w v = f'' v w := begin have A : (λ h : ℝ, h^2 • (f'' w v- f'' v w)) =o[𝓝[>] 0] (λ h, h^2), { convert (s_conv.is_o_alternate_sum_square hf xs hx h4v h4w).sub (s_conv.is_o_alternate_sum_square hf xs hx h4w h4v), ext h, simp only [add_comm, smul_add, smul_sub], abel }, have B : (λ h : ℝ, f'' w v - f'' v w) =o[𝓝[>] 0] (λ h, (1 : ℝ)), { have : (λ h : ℝ, 1/h^2) =O[𝓝[>] 0] (λ h, 1/h^2) := is_O_refl _ _, have C := this.smul_is_o A, apply C.congr' _ _, { filter_upwards [self_mem_nhds_within], assume h hpos, rw [← one_smul ℝ (f'' w v - f'' v w), smul_smul, smul_smul], congr' 1, field_simp [has_lt.lt.ne' hpos] }, { filter_upwards [self_mem_nhds_within] with _ hpos, field_simp [has_lt.lt.ne' hpos, has_smul.smul], }, }, simpa only [sub_eq_zero] using is_o_const_const_iff.1 B, end omit s_conv xs hx hf /-- If a function is differentiable inside a convex set with nonempty interior, and has a second derivative at a point of this convex set, then this second derivative is symmetric. -/ theorem convex.second_derivative_within_at_symmetric {s : set E} (s_conv : convex ℝ s) (hne : (interior s).nonempty) {f : E → F} {f' : E → (E →L[ℝ] F)} {f'' : E →L[ℝ] (E →L[ℝ] F)} (hf : ∀ x ∈ interior s, has_fderiv_at f (f' x) x) {x : E} (xs : x ∈ s) (hx : has_fderiv_within_at f' f'' (interior s) x) (v w : E) : f'' v w = f'' w v := begin /- we work around a point `x + 4 z` in the interior of `s`. For any vector `m`, then `x + 4 (z + t m)` also belongs to the interior of `s` for small enough `t`. This means that we will be able to apply `second_derivative_within_at_symmetric_of_mem_interior` to show that `f''` is symmetric, after cancelling all the contributions due to `z`. -/ rcases hne with ⟨y, hy⟩, obtain ⟨z, hz⟩ : ∃ z, z = ((1:ℝ) / 4) • (y - x) := ⟨((1:ℝ) / 4) • (y - x), rfl⟩, have A : ∀ (m : E), filter.tendsto (λ (t : ℝ), x + (4 : ℝ) • (z + t • m)) (𝓝 0) (𝓝 y), { assume m, have : x + (4 : ℝ) • (z + (0 : ℝ) • m) = y, by simp [hz], rw ← this, refine tendsto_const_nhds.add _, refine tendsto_const_nhds.smul _, refine tendsto_const_nhds.add _, exact continuous_at_id.smul continuous_at_const }, have B : ∀ (m : E), ∀ᶠ t in 𝓝[>] (0 : ℝ), x + (4 : ℝ) • (z + t • m) ∈ interior s, { assume m, apply nhds_within_le_nhds, apply A m, rw [mem_interior_iff_mem_nhds] at hy, exact interior_mem_nhds.2 hy }, -- we choose `t m > 0` such that `x + 4 (z + (t m) m)` belongs to the interior of `s`, for any -- vector `m`. choose t ts tpos using λ m, ((B m).and self_mem_nhds_within).exists, -- applying `second_derivative_within_at_symmetric_of_mem_interior` to the vectors `z` -- and `z + (t m) m`, we deduce that `f'' m z = f'' z m` for all `m`. have C : ∀ (m : E), f'' m z = f'' z m, { assume m, have : f'' (z + t m • m) (z + t 0 • 0) = f'' (z + t 0 • 0) (z + t m • m) := s_conv.second_derivative_within_at_symmetric_of_mem_interior hf xs hx (ts 0) (ts m), simp only [continuous_linear_map.map_add, continuous_linear_map.map_smul, add_right_inj, continuous_linear_map.add_apply, pi.smul_apply, continuous_linear_map.coe_smul', add_zero, continuous_linear_map.zero_apply, smul_zero, continuous_linear_map.map_zero] at this, exact smul_right_injective F (tpos m).ne' this }, -- applying `second_derivative_within_at_symmetric_of_mem_interior` to the vectors `z + (t v) v` -- and `z + (t w) w`, we deduce that `f'' v w = f'' w v`. Cross terms involving `z` can be -- eliminated thanks to the fact proved above that `f'' m z = f'' z m`. have : f'' (z + t v • v) (z + t w • w) = f'' (z + t w • w) (z + t v • v) := s_conv.second_derivative_within_at_symmetric_of_mem_interior hf xs hx (ts w) (ts v), simp only [continuous_linear_map.map_add, continuous_linear_map.map_smul, smul_add, smul_smul, continuous_linear_map.add_apply, pi.smul_apply, continuous_linear_map.coe_smul', C] at this, rw ← sub_eq_zero at this, abel at this, simp only [one_zsmul, neg_smul, sub_eq_zero, mul_comm, ← sub_eq_add_neg] at this, apply smul_right_injective F _ this, simp [(tpos v).ne', (tpos w).ne'] end /-- If a function is differentiable around `x`, and has two derivatives at `x`, then the second derivative is symmetric. -/ theorem second_derivative_symmetric_of_eventually {f : E → F} {f' : E → (E →L[ℝ] F)} {f'' : E →L[ℝ] (E →L[ℝ] F)} (hf : ∀ᶠ y in 𝓝 x, has_fderiv_at f (f' y) y) (hx : has_fderiv_at f' f'' x) (v w : E) : f'' v w = f'' w v := begin rcases metric.mem_nhds_iff.1 hf with ⟨ε, εpos, hε⟩, have A : (interior (metric.ball x ε)).nonempty, by rwa [metric.is_open_ball.interior_eq, metric.nonempty_ball], exact convex.second_derivative_within_at_symmetric (convex_ball x ε) A (λ y hy, hε (interior_subset hy)) (metric.mem_ball_self εpos) hx.has_fderiv_within_at v w, end /-- If a function is differentiable, and has two derivatives at `x`, then the second derivative is symmetric. -/ theorem second_derivative_symmetric {f : E → F} {f' : E → (E →L[ℝ] F)} {f'' : E →L[ℝ] (E →L[ℝ] F)} (hf : ∀ y, has_fderiv_at f (f' y) y) (hx : has_fderiv_at f' f'' x) (v w : E) : f'' v w = f'' w v := second_derivative_symmetric_of_eventually (filter.eventually_of_forall hf) hx v w
ec5731d4eb30c2c837c479739c32a0c31254b35b
82e44445c70db0f03e30d7be725775f122d72f3e
/src/geometry/manifold/whitney_embedding.lean
a00275dd25aab7ee60b94a05c9ecab4765c2a97f
[ "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
5,959
lean
/- Copyright (c) 2021 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import geometry.manifold.partition_of_unity /-! # Whitney embedding theorem In this file we prove a version of the Whitney embedding theorem: for any compact real manifold `M`, for sufficiently large `n` there exists a smooth embedding `M → ℝ^n`. ## TODO * Prove the weak Whitney embedding theorem: any `σ`-compact smooth `m`-dimensional manifold can be embedded into `ℝ^(2m+1)`. This requires a version of Sard's theorem: for a locally Lipschitz continuous map `f : ℝ^m → ℝ^n`, `m < n`, the range has Hausdorff dimension at most `m`, hence it has measure zero. ## Tags partition of unity, smooth bump function, whitney theorem -/ universes uE uF uH uM variables {E : Type uE} [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] {H : Type uH} [topological_space H] {I : model_with_corners ℝ E H} {M : Type uM} [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M] open function filter finite_dimensional set open_locale topological_space manifold classical filter big_operators noncomputable theory namespace smooth_bump_covering variables {s : set M} {U : M → set M} (fs : smooth_bump_covering I s) variables [t2_space M] [fintype fs.ι] (f : smooth_bump_covering I (univ : set M)) [fintype f.ι] /-- Smooth embedding of `M` into `(E × ℝ) ^ f.ι`. -/ def embedding_pi_tangent : C^∞⟮I, M; 𝓘(ℝ, fs.ι → (E × ℝ)), fs.ι → (E × ℝ)⟯ := { to_fun := λ x i, (fs i x • ext_chart_at I (fs.c i) x, fs i x), times_cont_mdiff_to_fun := times_cont_mdiff_pi_space.2 $ λ i, ((fs i).smooth_smul times_cont_mdiff_on_ext_chart_at).prod_mk_space ((fs i).smooth) } local attribute [simp] lemma embedding_pi_tangent_coe : ⇑fs.embedding_pi_tangent = λ x i, (fs i x • ext_chart_at I (fs.c i) x, fs i x) := rfl lemma embedding_pi_tangent_inj_on : inj_on fs.embedding_pi_tangent s := begin intros x hx y hy h, simp only [embedding_pi_tangent_coe, funext_iff] at h, obtain ⟨h₁, h₂⟩ := prod.mk.inj_iff.1 (h (fs.ind x hx)), rw [fs.apply_ind x hx] at h₂, rw [← h₂, fs.apply_ind x hx, one_smul, one_smul] at h₁, have := fs.mem_ext_chart_at_source_of_eq_one h₂.symm, exact (ext_chart_at I (fs.c _)).inj_on (fs.mem_ext_chart_at_ind_source x hx) this h₁ end lemma embedding_pi_tangent_injective : injective f.embedding_pi_tangent := injective_iff_inj_on_univ.2 f.embedding_pi_tangent_inj_on lemma comp_embedding_pi_tangent_mfderiv (x : M) (hx : x ∈ s) : ((continuous_linear_map.fst ℝ E ℝ).comp (@continuous_linear_map.proj ℝ _ fs.ι (λ _, E × ℝ) _ _ (λ _, infer_instance) (fs.ind x hx))).comp (mfderiv I 𝓘(ℝ, fs.ι → (E × ℝ)) fs.embedding_pi_tangent x) = mfderiv I I (chart_at H (fs.c (fs.ind x hx))) x := begin set L := ((continuous_linear_map.fst ℝ E ℝ).comp (@continuous_linear_map.proj ℝ _ fs.ι (λ _, E × ℝ) _ _ (λ _, infer_instance) (fs.ind x hx))), have := (L.has_mfderiv_at.comp x (fs.embedding_pi_tangent.mdifferentiable_at.has_mfderiv_at)), convert has_mfderiv_at_unique this _, refine (has_mfderiv_at_ext_chart_at I (fs.mem_chart_at_ind_source x hx)).congr_of_eventually_eq _, refine (fs.eventually_eq_one x hx).mono (λ y hy, _), simp only [embedding_pi_tangent_coe, continuous_linear_map.coe_comp', (∘), continuous_linear_map.coe_fst', continuous_linear_map.proj_apply], rw [hy, pi.one_apply, one_smul] end lemma embedding_pi_tangent_ker_mfderiv (x : M) (hx : x ∈ s) : (mfderiv I 𝓘(ℝ, fs.ι → (E × ℝ)) fs.embedding_pi_tangent x).ker = ⊥ := begin apply bot_unique, rw [← (mdifferentiable_chart I (fs.c (fs.ind x hx))).ker_mfderiv_eq_bot (fs.mem_chart_at_ind_source x hx), ← comp_embedding_pi_tangent_mfderiv], exact linear_map.ker_le_ker_comp _ _ end lemma embedding_pi_tangent_injective_mfderiv (x : M) (hx : x ∈ s) : injective (mfderiv I 𝓘(ℝ, fs.ι → (E × ℝ)) fs.embedding_pi_tangent x) := linear_map.ker_eq_bot.1 (fs.embedding_pi_tangent_ker_mfderiv x hx) /-- Baby version of the Whitney weak embedding theorem: if `M` admits a finite covering by supports of bump functions, then for some `n` it can be immersed into the `n`-dimensional Euclidean space. -/ lemma exists_immersion_finrank (f : smooth_bump_covering I (univ : set M)) [fintype f.ι] : ∃ (n : ℕ) (e : M → euclidean_space ℝ (fin n)), smooth I (𝓡 n) e ∧ injective e ∧ ∀ x : M, injective (mfderiv I (𝓡 n) e x) := begin set F := euclidean_space ℝ (fin $ finrank ℝ (f.ι → (E × ℝ))), letI : finite_dimensional ℝ (E × ℝ) := by apply_instance, set eEF : (f.ι → (E × ℝ)) ≃L[ℝ] F := continuous_linear_equiv.of_finrank_eq finrank_euclidean_space_fin.symm, refine ⟨_, eEF ∘ f.embedding_pi_tangent, eEF.to_diffeomorph.smooth.comp f.embedding_pi_tangent.smooth, eEF.injective.comp f.embedding_pi_tangent_injective, λ x, _⟩, rw [mfderiv_comp _ eEF.differentiable_at.mdifferentiable_at f.embedding_pi_tangent.mdifferentiable_at, eEF.mfderiv_eq], exact eEF.injective.comp (f.embedding_pi_tangent_injective_mfderiv _ trivial) end end smooth_bump_covering /-- Baby version of the Whitney weak embedding theorem: if `M` admits a finite covering by supports of bump functions, then for some `n` it can be embedded into the `n`-dimensional Euclidean space. -/ lemma exists_embedding_finrank_of_compact [t2_space M] [compact_space M] : ∃ (n : ℕ) (e : M → euclidean_space ℝ (fin n)), smooth I (𝓡 n) e ∧ closed_embedding e ∧ ∀ x : M, injective (mfderiv I (𝓡 n) e x) := begin rcases (smooth_bump_covering.choice I M).exists_immersion_finrank with ⟨n, e, hsmooth, hinj, hinj_mfderiv⟩, exact ⟨n, e, hsmooth, hsmooth.continuous.closed_embedding hinj, hinj_mfderiv⟩ end
21f1737ce4de5dd37c6ef408b1d80883f752c924
618003631150032a5676f229d13a079ac875ff77
/src/tactic/nth_rewrite/default.lean
379a9cee97bbf98543cddeaae6d7763d81ca0413
[ "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
5,109
lean
/- Copyright (c) 2018 Keeley Hoek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Keeley Hoek, Scott Morrison -/ import tactic.nth_rewrite.congr /-! # Advanced rewriting tactics This file provides three interactive tactics that give the user more control over where to perform a rewrite. ## Main definitions * `nth_write n rules`: performs only the `n`th possible rewrite using the `rules`. * `nth_rewrite_lhs`: as above, but only rewrites on the left hand side of an equation or iff. * `nth_rewrite_rhs`: as above, but only rewrites on the right hand side of an equation or iff. ## Implementation details There are two alternative backends, provided by `.congr` and `.kabstract`. The kabstract backend is not currently available through mathlib. The kabstract backend is faster, but if there are multiple identical occurrences of the same rewritable subexpression, all are rewritten simultaneously, and this isn't always what we want. (In particular, `rewrite_search` is much less capable on the `category_theory` library.) -/ open tactic lean.parser interactive interactive.types expr namespace tactic /-- Returns the target of the goal when passed `none`, otherwise, return the type of `h` in `some h`. -/ meta def target_or_hyp_type : option expr → tactic expr | none := target | (some h) := infer_type h /-- Replace the target, or a hypothesis, depending on whether `none` or `some h` is given as the first argument. -/ meta def replace_in_state : option expr → expr → expr → tactic unit | none := tactic.replace_target | (some h) := λ e p, tactic.replace_hyp h e p >> skip open nth_rewrite nth_rewrite.congr nth_rewrite.tracked_rewrite open tactic.interactive /-- Preprocess a rewrite rule for use in `get_nth_rewrite`. -/ private meta def unpack_rule (p : rw_rule) : tactic (expr × bool) := do r ← to_expr p.rule tt ff, return (r, p.symm) /-- Get the `n`th rewrite of rewrite rules `q` in expression `e`, or fail if there are not enough such rewrites. -/ meta def get_nth_rewrite (n : ℕ) (q : rw_rules_t) (e : expr) : tactic tracked_rewrite := do rewrites ← q.rules.mmap $ λ r, unpack_rule r >>= nth_rewrite e, rewrites.join.nth n <|> fail "failed: not enough rewrites found" /-- Rewrite the `n`th occurrence of the rewrite rules `q` of (optionally after zooming into) a hypothesis or target `h` which is an application of a relation. -/ meta def get_nth_rewrite_with_zoom (n : ℕ) (q : rw_rules_t) (path : list expr_lens.dir) (h : option expr) : tactic tracked_rewrite := do e ← target_or_hyp_type h, (ln, new_e) ← expr_lens.entire.zoom path e, rw ← get_nth_rewrite n q new_e, return ⟨ln.fill rw.exp, rw.proof >>= ln.congr, rw.addr.map $ λ l, path ++ l⟩ /-- Rewrite the `n`th occurrence of the rewrite rules `q` (optionally on a side) at all the locations `loc`. -/ meta def nth_rewrite_core (path : list expr_lens.dir) (n : parse small_nat) (q : parse rw_rules) (l : parse location) : tactic unit := do let fn := λ h, get_nth_rewrite_with_zoom n q path h >>= λ rw, (rw.proof >>= replace_in_state h rw.exp), match l with | loc.wildcard := l.try_apply (fn ∘ some) (fn none) | _ := l.apply (fn ∘ some) (fn none) end, tactic.try (tactic.reflexivity reducible), (returnopt q.end_pos >>= save_info <|> skip) namespace interactive open expr_lens /-- `nth_rewrite n rules` performs only the `n`th possible rewrite using the `rules`. The tactics `nth_rewrite_lhs` and `nth_rewrite_rhs` are variants that operate on the left and right hand sides of an equation or iff. Note: `n` is zero-based, so `nth_rewrite 0 h` will rewrite along `h` at the first possible location. In more detail, given `rules = [h1, ..., hk]`, this tactic will search for all possible locations where one of `h1, ..., hk` can be rewritten, and perform the `n`th occurrence. Example: Given a goal of the form `a + x = x + b`, and hypothesis `h : x = y`, the tactic `nth_rewrite 1 h` will change the goal to `a + x = y + b`. The core `rewrite` has a `occs` configuration setting intended to achieve a similar purpose, but this doesn't really work. (If a rule matches twice, but with different values of arguments, the second match will not be identified.) -/ meta def nth_rewrite (n : parse small_nat) (q : parse rw_rules) (l : parse location) : tactic unit := nth_rewrite_core [] n q l meta def nth_rewrite_lhs (n : parse small_nat) (q : parse rw_rules) (l : parse location) : tactic unit := nth_rewrite_core [dir.F, dir.A] n q l meta def nth_rewrite_rhs (n : parse small_nat) (q : parse rw_rules) (l : parse location) : tactic unit := nth_rewrite_core [dir.A] n q l copy_doc_string nth_rewrite → nth_rewrite_lhs nth_rewrite_rhs add_tactic_doc { name := "nth_rewrite / nth_rewrite_lhs / nth_rewrite_rhs", category := doc_category.tactic, inherit_description_from := ``nth_rewrite, decl_names := [``nth_rewrite, ``nth_rewrite_lhs, ``nth_rewrite_rhs], tags := ["rewriting"] } end interactive end tactic
d42b4f83395841af1fbb5683d45ad5afbad0ad4e
fd7ca05aed4422fb0428e5a31bf6fa13221ee291
/src/constructions.lean
89d71d8a3d703938aa00a5913df029ae33a52fee
[]
no_license
ericrbg/HatGames
f5712f2ab1b9bf1e681d9b57f17f51b3c010af24
33cfbf4d23d43c1f71b4aa2a6a0d60a2b2b2a984
refs/heads/main
1,692,247,407,481
1,632,194,504,000
1,632,194,504,000
354,602,607
0
0
null
null
null
null
UTF-8
Lean
false
false
848
lean
import data.nat.basic import combinatorics.simple_graph.basic variables {α β : Type*} (G : simple_graph α) /-- The lexicographic product of a graph with a type. This is equivalent to the well-known graph lexicographic product on `G` and the complete graph for `β`. -/ def lex_product (β) : simple_graph (α × β) := { adj := λ a b, G.adj a.1 b.1 ∨ (a.1 = b.1 ∧ a.2 ≠ b.2), symm := by { rintros _ _ (_|⟨_,_⟩); tauto }, loopless := λ x , by { have := G.loopless x.fst, rintros (_ | _); tauto } } infix `·`:50 := lex_product @[simp] theorem lex_adj {G} {a b : α × β} : (G·β).adj a b ↔ G.adj a.1 b.1 ∨ (a.1 = b.1 ∧ a.2 ≠ b.2) := iff.rfl theorem lex_adj' {G} {a₁ a₂ : α} {b₁ b₂ : β} : (G·β).adj ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ ↔ G.adj a₁ a₂ ∨ (a₁ = a₂ ∧ b₁ ≠ b₂) := iff.rfl
604f5399e75127bd13b94d8a361ae729e0a89ea4
6094e25ea0b7699e642463b48e51b2ead6ddc23f
/hott/types/nat/sub.hlean
94be4077c63532b8e12e035a6f4a2d02a7d4068f
[ "Apache-2.0" ]
permissive
gbaz/lean
a7835c4e3006fbbb079e8f8ffe18aacc45adebfb
a501c308be3acaa50a2c0610ce2e0d71becf8032
refs/heads/master
1,611,198,791,433
1,451,339,111,000
1,451,339,111,000
48,713,797
0
0
null
1,451,338,939,000
1,451,338,939,000
null
UTF-8
Lean
false
false
19,540
hlean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Jeremy Avigad Subtraction on the natural numbers, as well as min, max, prod distance. -/ import .order open eq.ops eq algebra namespace nat /- subtraction -/ protected theorem sub_zero (n : ℕ) : n - 0 = n := rfl theorem sub_succ (n m : ℕ) : n - succ m = pred (n - m) := rfl protected theorem zero_sub (n : ℕ) : 0 - n = 0 := nat.rec_on n !nat.sub_zero (take k : nat, assume IH : 0 - k = 0, calc 0 - succ k = pred (0 - k) : sub_succ ... = pred 0 : IH ... = 0 : pred_zero) theorem succ_sub_succ (n m : ℕ) : succ n - succ m = n - m := succ_sub_succ_eq_sub n m protected theorem sub_self (n : ℕ) : n - n = 0 := nat.rec_on n !nat.sub_zero (take k IH, !succ_sub_succ ⬝ IH) protected theorem add_sub_add_right (n k m : ℕ) : (n + k) - (m + k) = n - m := nat.rec_on k (calc (n + 0) - (m + 0) = n - (m + 0) : {!add_zero} ... = n - m : {!add_zero}) (take l : nat, assume IH : (n + l) - (m + l) = n - m, calc (n + succ l) - (m + succ l) = succ (n + l) - (m + succ l) : {!add_succ} ... = succ (n + l) - succ (m + l) : {!add_succ} ... = (n + l) - (m + l) : !succ_sub_succ ... = n - m : IH) protected theorem add_sub_add_left (k n m : ℕ) : (k + n) - (k + m) = n - m := add.comm n k ▸ add.comm m k ▸ nat.add_sub_add_right n k m protected theorem add_sub_cancel (n m : ℕ) : n + m - m = n := nat.rec_on m (begin rewrite add_zero end) (take k : ℕ, assume IH : n + k - k = n, calc n + succ k - succ k = succ (n + k) - succ k : add_succ ... = n + k - k : succ_sub_succ ... = n : IH) protected theorem add_sub_cancel_left (n m : ℕ) : n + m - n = m := !add.comm ▸ !nat.add_sub_cancel protected theorem sub_sub (n m k : ℕ) : n - m - k = n - (m + k) := nat.rec_on k (calc n - m - 0 = n - m : nat.sub_zero ... = n - (m + 0) : add_zero) (take l : nat, assume IH : n - m - l = n - (m + l), calc n - m - succ l = pred (n - m - l) : !sub_succ ... = pred (n - (m + l)) : IH ... = n - succ (m + l) : sub_succ ... = n - (m + succ l) : by rewrite add_succ) theorem succ_sub_sub_succ (n m k : ℕ) : succ n - m - succ k = n - m - k := calc succ n - m - succ k = succ n - (m + succ k) : nat.sub_sub ... = succ n - succ (m + k) : add_succ ... = n - (m + k) : succ_sub_succ ... = n - m - k : nat.sub_sub theorem sub_self_add (n m : ℕ) : n - (n + m) = 0 := calc n - (n + m) = n - n - m : nat.sub_sub ... = 0 - m : nat.sub_self ... = 0 : nat.zero_sub protected theorem sub.right_comm (m n k : ℕ) : m - n - k = m - k - n := calc m - n - k = m - (n + k) : !nat.sub_sub ... = m - (k + n) : {!add.comm} ... = m - k - n : !nat.sub_sub⁻¹ theorem sub_one (n : ℕ) : n - 1 = pred n := rfl theorem succ_sub_one (n : ℕ) : succ n - 1 = n := rfl /- interaction with multiplication -/ theorem mul_pred_left (n m : ℕ) : pred n * m = n * m - m := nat.rec_on n (calc pred 0 * m = 0 * m : pred_zero ... = 0 : zero_mul ... = 0 - m : nat.zero_sub ... = 0 * m - m : zero_mul) (take k : nat, assume IH : pred k * m = k * m - m, calc pred (succ k) * m = k * m : pred_succ ... = k * m + m - m : nat.add_sub_cancel ... = succ k * m - m : succ_mul) theorem mul_pred_right (n m : ℕ) : n * pred m = n * m - n := calc n * pred m = pred m * n : mul.comm ... = m * n - n : mul_pred_left ... = n * m - n : mul.comm protected theorem mul_sub_right_distrib (n m k : ℕ) : (n - m) * k = n * k - m * k := nat.rec_on m (calc (n - 0) * k = n * k : nat.sub_zero ... = n * k - 0 : nat.sub_zero ... = n * k - 0 * k : zero_mul) (take l : nat, assume IH : (n - l) * k = n * k - l * k, calc (n - succ l) * k = pred (n - l) * k : sub_succ ... = (n - l) * k - k : mul_pred_left ... = n * k - l * k - k : IH ... = n * k - (l * k + k) : nat.sub_sub ... = n * k - (succ l * k) : succ_mul) protected theorem mul_sub_left_distrib (n m k : ℕ) : n * (m - k) = n * m - n * k := calc n * (m - k) = (m - k) * n : !mul.comm ... = m * n - k * n : !nat.mul_sub_right_distrib ... = n * m - k * n : {!mul.comm} ... = n * m - n * k : {!mul.comm} protected theorem mul_self_sub_mul_self_eq (a b : nat) : a * a - b * b = (a + b) * (a - b) := by rewrite [nat.mul_sub_left_distrib, *right_distrib, mul.comm b a, add.comm (a*a) (a*b), nat.add_sub_add_left] theorem succ_mul_succ_eq (a : nat) : succ a * succ a = a*a + a + a + 1 := calc succ a * succ a = (a+1)*(a+1) : by rewrite [add_one] ... = a*a + a + a + 1 : by rewrite [right_distrib, left_distrib, one_mul, mul_one] /- interaction with inequalities -/ theorem succ_sub {m n : ℕ} : m ≥ n → succ m - n = succ (m - n) := sub_induction n m (take k, assume H : 0 ≤ k, rfl) (take k, assume H : succ k ≤ 0, absurd H !not_succ_le_zero) (take k l, assume IH : k ≤ l → succ l - k = succ (l - k), take H : succ k ≤ succ l, calc succ (succ l) - succ k = succ l - k : succ_sub_succ ... = succ (l - k) : IH (le_of_succ_le_succ H) ... = succ (succ l - succ k) : succ_sub_succ) theorem sub_eq_zero_of_le {n m : ℕ} (H : n ≤ m) : n - m = 0 := obtain (k : ℕ) (Hk : n + k = m), from le.elim H, Hk ▸ !sub_self_add theorem add_sub_of_le {n m : ℕ} : n ≤ m → n + (m - n) = m := sub_induction n m (take k, assume H : 0 ≤ k, calc 0 + (k - 0) = k - 0 : zero_add ... = k : nat.sub_zero) (take k, assume H : succ k ≤ 0, absurd H !not_succ_le_zero) (take k l, assume IH : k ≤ l → k + (l - k) = l, take H : succ k ≤ succ l, calc succ k + (succ l - succ k) = succ k + (l - k) : succ_sub_succ ... = succ (k + (l - k)) : succ_add ... = succ l : IH (le_of_succ_le_succ H)) theorem add_sub_of_ge {n m : ℕ} (H : n ≥ m) : n + (m - n) = n := calc n + (m - n) = n + 0 : sub_eq_zero_of_le H ... = n : add_zero protected theorem sub_add_cancel {n m : ℕ} : n ≥ m → n - m + m = n := !add.comm ▸ !add_sub_of_le theorem sub_add_of_le {n m : ℕ} : n ≤ m → n - m + m = m := !add.comm ▸ add_sub_of_ge theorem sub.cases {P : ℕ → Type} {n m : ℕ} (H1 : n ≤ m → P 0) (H2 : Πk, m + k = n -> P k) : P (n - m) := sum.elim !le.total (assume H3 : n ≤ m, (sub_eq_zero_of_le H3)⁻¹ ▸ (H1 H3)) (assume H3 : m ≤ n, H2 (n - m) (add_sub_of_le H3)) theorem exists_sub_eq_of_le {n m : ℕ} (H : n ≤ m) : Σk, m - k = n := obtain (k : ℕ) (Hk : n + k = m), from le.elim H, sigma.mk k (calc m - k = n + k - k : by rewrite Hk ... = n : nat.add_sub_cancel) protected theorem add_sub_assoc {m k : ℕ} (H : k ≤ m) (n : ℕ) : n + m - k = n + (m - k) := have l1 : k ≤ m → n + m - k = n + (m - k), from sub_induction k m (take m : ℕ, assume H : 0 ≤ m, calc n + m - 0 = n + m : nat.sub_zero ... = n + (m - 0) : nat.sub_zero) (take k : ℕ, assume H : succ k ≤ 0, absurd H !not_succ_le_zero) (take k m, assume IH : k ≤ m → n + m - k = n + (m - k), take H : succ k ≤ succ m, calc n + succ m - succ k = succ (n + m) - succ k : add_succ ... = n + m - k : succ_sub_succ ... = n + (m - k) : IH (le_of_succ_le_succ H) ... = n + (succ m - succ k) : succ_sub_succ), l1 H theorem le_of_sub_eq_zero {n m : ℕ} : n - m = 0 → n ≤ m := sub.cases (assume H1 : n ≤ m, assume H2 : 0 = 0, H1) (take k : ℕ, assume H1 : m + k = n, assume H2 : k = 0, have H3 : n = m, from !add_zero ▸ H2 ▸ H1⁻¹, H3 ▸ !le.refl) theorem sub_sub.cases {P : ℕ → ℕ → Type} {n m : ℕ} (H1 : Πk, n = m + k -> P k 0) (H2 : Πk, m = n + k → P 0 k) : P (n - m) (m - n) := sum.elim !le.total (assume H3 : n ≤ m, (sub_eq_zero_of_le H3)⁻¹ ▸ (H2 (m - n) (add_sub_of_le H3)⁻¹)) (assume H3 : m ≤ n, (sub_eq_zero_of_le H3)⁻¹ ▸ (H1 (n - m) (add_sub_of_le H3)⁻¹)) protected theorem sub_eq_of_add_eq {n m k : ℕ} (H : n + m = k) : k - n = m := have H2 : k - n + n = m + n, from calc k - n + n = k : nat.sub_add_cancel (le.intro H) ... = n + m : H⁻¹ ... = m + n : !add.comm, add.right_cancel H2 protected theorem eq_sub_of_add_eq {a b c : ℕ} (H : a + c = b) : a = b - c := (nat.sub_eq_of_add_eq (!add.comm ▸ H))⁻¹ protected theorem sub_eq_of_eq_add {a b c : ℕ} (H : a = c + b) : a - b = c := nat.sub_eq_of_add_eq (!add.comm ▸ H⁻¹) protected theorem sub_le_sub_right {n m : ℕ} (H : n ≤ m) (k : ℕ) : n - k ≤ m - k := obtain (l : ℕ) (Hl : n + l = m), from le.elim H, sum.elim !le.total (assume H2 : n ≤ k, (sub_eq_zero_of_le H2)⁻¹ ▸ !zero_le) (assume H2 : k ≤ n, have H3 : n - k + l = m - k, from calc n - k + l = l + (n - k) : add.comm ... = l + n - k : nat.add_sub_assoc H2 l ... = n + l - k : add.comm ... = m - k : Hl, le.intro H3) protected theorem sub_le_sub_left {n m : ℕ} (H : n ≤ m) (k : ℕ) : k - m ≤ k - n := obtain (l : ℕ) (Hl : n + l = m), from le.elim H, sub.cases (assume H2 : k ≤ m, !zero_le) (take m' : ℕ, assume Hm : m + m' = k, have H3 : n ≤ k, from le.trans H (le.intro Hm), have H4 : m' + l + n = k - n + n, from calc m' + l + n = n + (m' + l) : add.comm ... = n + (l + m') : add.comm ... = n + l + m' : add.assoc ... = m + m' : Hl ... = k : Hm ... = k - n + n : nat.sub_add_cancel H3, le.intro (add.right_cancel H4)) protected theorem sub_pos_of_lt {m n : ℕ} (H : m < n) : n - m > 0 := assert H1 : n = n - m + m, from (nat.sub_add_cancel (le_of_lt H))⁻¹, have H2 : 0 + m < n - m + m, begin rewrite [zero_add, -H1], exact H end, !lt_of_add_lt_add_right H2 protected theorem lt_of_sub_pos {m n : ℕ} (H : n - m > 0) : m < n := lt_of_not_ge (take H1 : m ≥ n, have H2 : n - m = 0, from sub_eq_zero_of_le H1, !lt.irrefl (H2 ▸ H)) protected theorem lt_of_sub_lt_sub_right {n m k : ℕ} (H : n - k < m - k) : n < m := lt_of_not_ge (assume H1 : m ≤ n, have H2 : m - k ≤ n - k, from nat.sub_le_sub_right H1 _, not_le_of_gt H H2) protected theorem lt_of_sub_lt_sub_left {n m k : ℕ} (H : n - m < n - k) : k < m := lt_of_not_ge (assume H1 : m ≤ k, have H2 : n - k ≤ n - m, from nat.sub_le_sub_left H1 _, not_le_of_gt H H2) protected theorem sub_lt_sub_add_sub (n m k : ℕ) : n - k ≤ (n - m) + (m - k) := sub.cases (assume H : n ≤ m, (zero_add (m - k))⁻¹ ▸ nat.sub_le_sub_right H k) (take mn : ℕ, assume Hmn : m + mn = n, sub.cases (assume H : m ≤ k, have H2 : n - k ≤ n - m, from nat.sub_le_sub_left H n, assert H3 : n - k ≤ mn, from nat.sub_eq_of_add_eq Hmn ▸ H2, show n - k ≤ mn + 0, begin rewrite add_zero, assumption end) (take km : ℕ, assume Hkm : k + km = m, have H : k + (mn + km) = n, from calc k + (mn + km) = k + (km + mn): add.comm ... = k + km + mn : add.assoc ... = m + mn : Hkm ... = n : Hmn, have H2 : n - k = mn + km, from nat.sub_eq_of_add_eq H, H2 ▸ !le.refl)) protected theorem sub_lt_self {m n : ℕ} (H1 : m > 0) (H2 : n > 0) : m - n < m := calc m - n = succ (pred m) - n : succ_pred_of_pos H1 ... = succ (pred m) - succ (pred n) : succ_pred_of_pos H2 ... = pred m - pred n : succ_sub_succ ... ≤ pred m : sub_le ... < succ (pred m) : lt_succ_self ... = m : succ_pred_of_pos H1 protected theorem le_sub_of_add_le {m n k : ℕ} (H : m + k ≤ n) : m ≤ n - k := calc m = m + k - k : nat.add_sub_cancel ... ≤ n - k : nat.sub_le_sub_right H k protected theorem lt_sub_of_add_lt {m n k : ℕ} (H : m + k < n) (H2 : k ≤ n) : m < n - k := lt_of_succ_le (nat.le_sub_of_add_le (calc succ m + k = succ (m + k) : succ_add_eq_succ_add ... ≤ n : succ_le_of_lt H)) protected theorem sub_lt_of_lt_add {v n m : nat} (h₁ : v < n + m) (h₂ : n ≤ v) : v - n < m := have succ v ≤ n + m, from succ_le_of_lt h₁, have succ (v - n) ≤ m, from calc succ (v - n) = succ v - n : succ_sub h₂ ... ≤ n + m - n : nat.sub_le_sub_right this n ... = m : nat.add_sub_cancel_left, lt_of_succ_le this /- distance -/ definition dist [reducible] (n m : ℕ) := (n - m) + (m - n) theorem dist.comm (n m : ℕ) : dist n m = dist m n := !add.comm theorem dist_self (n : ℕ) : dist n n = 0 := calc (n - n) + (n - n) = 0 + (n - n) : nat.sub_self ... = 0 + 0 : nat.sub_self ... = 0 : rfl theorem eq_of_dist_eq_zero {n m : ℕ} (H : dist n m = 0) : n = m := have H2 : n - m = 0, from eq_zero_of_add_eq_zero_right H, have H3 : n ≤ m, from le_of_sub_eq_zero H2, have H4 : m - n = 0, from eq_zero_of_add_eq_zero_left H, have H5 : m ≤ n, from le_of_sub_eq_zero H4, le.antisymm H3 H5 theorem dist_eq_zero {n m : ℕ} (H : n = m) : dist n m = 0 := by substvars; rewrite [↑dist, *nat.sub_self, add_zero] theorem dist_eq_sub_of_le {n m : ℕ} (H : n ≤ m) : dist n m = m - n := calc dist n m = 0 + (m - n) : {sub_eq_zero_of_le H} ... = m - n : zero_add theorem dist_eq_sub_of_lt {n m : ℕ} (H : n < m) : dist n m = m - n := dist_eq_sub_of_le (le_of_lt H) theorem dist_eq_sub_of_ge {n m : ℕ} (H : n ≥ m) : dist n m = n - m := !dist.comm ▸ dist_eq_sub_of_le H theorem dist_eq_sub_of_gt {n m : ℕ} (H : n > m) : dist n m = n - m := dist_eq_sub_of_ge (le_of_lt H) theorem dist_zero_right (n : ℕ) : dist n 0 = n := dist_eq_sub_of_ge !zero_le ⬝ !nat.sub_zero theorem dist_zero_left (n : ℕ) : dist 0 n = n := dist_eq_sub_of_le !zero_le ⬝ !nat.sub_zero theorem dist.intro {n m k : ℕ} (H : n + m = k) : dist k n = m := calc dist k n = k - n : dist_eq_sub_of_ge (le.intro H) ... = m : nat.sub_eq_of_add_eq H theorem dist_add_add_right (n k m : ℕ) : dist (n + k) (m + k) = dist n m := calc dist (n + k) (m + k) = ((n+k) - (m+k)) + ((m+k)-(n+k)) : rfl ... = (n - m) + ((m + k) - (n + k)) : nat.add_sub_add_right ... = (n - m) + (m - n) : nat.add_sub_add_right theorem dist_add_add_left (k n m : ℕ) : dist (k + n) (k + m) = dist n m := begin rewrite [add.comm k n, add.comm k m]; apply dist_add_add_right end theorem dist_add_eq_of_ge {n m : ℕ} (H : n ≥ m) : dist n m + m = n := calc dist n m + m = n - m + m : {dist_eq_sub_of_ge H} ... = n : nat.sub_add_cancel H theorem dist_eq_intro {n m k l : ℕ} (H : n + m = k + l) : dist n k = dist l m := calc dist n k = dist (n + m) (k + m) : dist_add_add_right ... = dist (k + l) (k + m) : H ... = dist l m : dist_add_add_left theorem dist_sub_eq_dist_add_left {n m : ℕ} (H : n ≥ m) (k : ℕ) : dist (n - m) k = dist n (k + m) := have H2 : n - m + (k + m) = k + n, from calc n - m + (k + m) = n - m + (m + k) : add.comm ... = n - m + m + k : add.assoc ... = n + k : nat.sub_add_cancel H ... = k + n : add.comm, dist_eq_intro H2 theorem dist_sub_eq_dist_add_right {k m : ℕ} (H : k ≥ m) (n : ℕ) : dist n (k - m) = dist (n + m) k := dist.comm (k - m) n ▸ dist.comm k (n + m) ▸ dist_sub_eq_dist_add_left H n theorem dist.triangle_inequality (n m k : ℕ) : dist n k ≤ dist n m + dist m k := have (n - m) + (m - k) + ((k - m) + (m - n)) = (n - m) + (m - n) + ((m - k) + (k - m)), begin rewrite [add.comm (k - m) (m - n), {n - m + _ + _}add.assoc, {m - k + _}add.left_comm, -add.assoc] end, this ▸ add_le_add !nat.sub_lt_sub_add_sub !nat.sub_lt_sub_add_sub theorem dist_add_add_le_add_dist_dist (n m k l : ℕ) : dist (n + m) (k + l) ≤ dist n k + dist m l := assert H : dist (n + m) (k + m) + dist (k + m) (k + l) = dist n k + dist m l, by rewrite [dist_add_add_left, dist_add_add_right], by rewrite -H; apply dist.triangle_inequality theorem dist_mul_right (n k m : ℕ) : dist (n * k) (m * k) = dist n m * k := assert Π n m, dist n m = n - m + (m - n), from take n m, rfl, by rewrite [this, this n m, right_distrib, *nat.mul_sub_right_distrib] theorem dist_mul_left (k n m : ℕ) : dist (k * n) (k * m) = k * dist n m := begin rewrite [mul.comm k n, mul.comm k m, dist_mul_right, mul.comm] end theorem dist_mul_dist (n m k l : ℕ) : dist n m * dist k l = dist (n * k + m * l) (n * l + m * k) := have aux : Πk l, k ≥ l → dist n m * dist k l = dist (n * k + m * l) (n * l + m * k), from take k l : ℕ, assume H : k ≥ l, have H2 : m * k ≥ m * l, from !mul_le_mul_left H, have H3 : n * l + m * k ≥ m * l, from le.trans H2 !le_add_left, calc dist n m * dist k l = dist n m * (k - l) : dist_eq_sub_of_ge H ... = dist (n * (k - l)) (m * (k - l)) : dist_mul_right ... = dist (n * k - n * l) (m * k - m * l) : by rewrite [*nat.mul_sub_left_distrib] ... = dist (n * k) (m * k - m * l + n * l) : dist_sub_eq_dist_add_left (!mul_le_mul_left H) ... = dist (n * k) (n * l + (m * k - m * l)) : add.comm ... = dist (n * k) (n * l + m * k - m * l) : nat.add_sub_assoc H2 (n * l) ... = dist (n * k + m * l) (n * l + m * k) : dist_sub_eq_dist_add_right H3 _, sum.elim !le.total (assume H : k ≤ l, !dist.comm ▸ !dist.comm ▸ aux l k H) (assume H : l ≤ k, aux k l H) lemma dist_eq_max_sub_min {i j : nat} : dist i j = (max i j) - min i j := sum.elim (lt_sum_ge i j) (suppose i < j, by rewrite [max_eq_right_of_lt this, min_eq_left_of_lt this, dist_eq_sub_of_lt this]) (suppose i ≥ j, by rewrite [max_eq_left this , min_eq_right this, dist_eq_sub_of_ge this]) lemma dist_succ {i j : nat} : dist (succ i) (succ j) = dist i j := by rewrite [↑dist, *succ_sub_succ] lemma dist_le_max {i j : nat} : dist i j ≤ max i j := begin rewrite dist_eq_max_sub_min, apply sub_le end lemma dist_pos_of_ne {i j : nat} : i ≠ j → dist i j > 0 := assume Pne, lt.by_cases (suppose i < j, begin rewrite [dist_eq_sub_of_lt this], apply nat.sub_pos_of_lt this end) (suppose i = j, by contradiction) (suppose i > j, begin rewrite [dist_eq_sub_of_gt this], apply nat.sub_pos_of_lt this end) end nat
9b999924786ac95813b7ce26d0116dc0c742349c
3f7026ea8bef0825ca0339a275c03b911baef64d
/src/data/pfun.lean
b34d24771645f6a97c573613140e9a470213ff67
[ "Apache-2.0" ]
permissive
rspencer01/mathlib
b1e3afa5c121362ef0881012cc116513ab09f18c
c7d36292c6b9234dc40143c16288932ae38fdc12
refs/heads/master
1,595,010,346,708
1,567,511,503,000
1,567,511,503,000
206,071,681
0
0
Apache-2.0
1,567,513,643,000
1,567,513,643,000
null
UTF-8
Lean
false
false
22,538
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro, Jeremy Avigad -/ import data.set.basic data.equiv.basic data.rel logic.relator /-- `roption α` is the type of "partial values" of type `α`. It is similar to `option α` except the domain condition can be an arbitrary proposition, not necessarily decidable. -/ structure {u} roption (α : Type u) : Type u := (dom : Prop) (get : dom → α) namespace roption variables {α : Type*} {β : Type*} {γ : Type*} /-- Convert an `roption α` with a decidable domain to an option -/ def to_option (o : roption α) [decidable o.dom] : option α := if h : dom o then some (o.get h) else none /-- `roption` extensionality -/ def ext' : Π {o p : roption α} (H1 : o.dom ↔ p.dom) (H2 : ∀h₁ h₂, o.get h₁ = p.get h₂), o = p | ⟨od, o⟩ ⟨pd, p⟩ H1 H2 := have t : od = pd, from propext H1, by cases t; rw [show o = p, from funext $ λp, H2 p p] /-- `roption` eta expansion -/ @[simp] theorem eta : Π (o : roption α), (⟨o.dom, λ h, o.get h⟩ : roption α) = o | ⟨h, f⟩ := rfl /-- `a ∈ o` means that `o` is defined and equal to `a` -/ protected def mem (a : α) (o : roption α) : Prop := ∃ h, o.get h = a instance : has_mem α (roption α) := ⟨roption.mem⟩ theorem mem_eq (a : α) (o : roption α) : (a ∈ o) = (∃ h, o.get h = a) := rfl theorem dom_iff_mem : ∀ {o : roption α}, o.dom ↔ ∃y, y ∈ o | ⟨p, f⟩ := ⟨λh, ⟨f h, h, rfl⟩, λ⟨_, h, rfl⟩, h⟩ theorem get_mem {o : roption α} (h) : get o h ∈ o := ⟨_, rfl⟩ /-- `roption` extensionality -/ def ext {o p : roption α} (H : ∀ a, a ∈ o ↔ a ∈ p) : o = p := ext' ⟨λ h, ((H _).1 ⟨h, rfl⟩).fst, λ h, ((H _).2 ⟨h, rfl⟩).fst⟩ $ λ a b, ((H _).2 ⟨_, rfl⟩).snd /-- The `none` value in `roption` has a `false` domain and an empty function. -/ def none : roption α := ⟨false, false.rec _⟩ @[simp] theorem not_mem_none (a : α) : a ∉ @none α := λ h, h.fst /-- The `some a` value in `roption` has a `true` domain and the function returns `a`. -/ def some (a : α) : roption α := ⟨true, λ_, a⟩ theorem mem_unique : relator.left_unique ((∈) : α → roption α → Prop) | _ ⟨p, f⟩ _ ⟨h₁, rfl⟩ ⟨h₂, rfl⟩ := rfl theorem get_eq_of_mem {o : roption α} {a} (h : a ∈ o) (h') : get o h' = a := mem_unique ⟨_, rfl⟩ h @[simp] theorem get_some {a : α} (ha : (some a).dom) : get (some a) ha = a := rfl theorem mem_some (a : α) : a ∈ some a := ⟨trivial, rfl⟩ @[simp] theorem mem_some_iff {a b} : b ∈ (some a : roption α) ↔ b = a := ⟨λ⟨h, e⟩, e.symm, λ e, ⟨trivial, e.symm⟩⟩ theorem eq_some_iff {a : α} {o : roption α} : o = some a ↔ a ∈ o := ⟨λ e, e.symm ▸ mem_some _, λ ⟨h, e⟩, e ▸ ext' (iff_true_intro h) (λ _ _, rfl)⟩ theorem eq_none_iff {o : roption α} : o = none ↔ ∀ a, a ∉ o := ⟨λ e, e.symm ▸ not_mem_none, λ h, ext (by simpa [not_mem_none])⟩ theorem eq_none_iff' {o : roption α} : o = none ↔ ¬ o.dom := ⟨λ e, e.symm ▸ id, λ h, eq_none_iff.2 (λ a h', h h'.fst)⟩ lemma some_ne_none (x : α) : some x ≠ none := by { intro h, change none.dom, rw [← h], trivial } lemma ne_none_iff {o : roption α} : o ≠ none ↔ ∃x, o = some x := begin split, { rw [ne, eq_none_iff], intro h, push_neg at h, cases h with x hx, use x, rwa [eq_some_iff] }, { rintro ⟨x, rfl⟩, apply some_ne_none } end @[simp] lemma some_inj {a b : α} : roption.some a = some b ↔ a = b := function.injective.eq_iff (λ a b h, congr_fun (eq_of_heq (roption.mk.inj h).2) trivial) @[simp] lemma some_get {a : roption α} (ha : a.dom) : roption.some (roption.get a ha) = a := eq.symm (eq_some_iff.2 ⟨ha, rfl⟩) lemma get_eq_iff_eq_some {a : roption α} {ha : a.dom} {b : α} : a.get ha = b ↔ a = some b := ⟨λ h, by simp [h.symm], λ h, by simp [h]⟩ instance none_decidable : decidable (@none α).dom := decidable.false instance some_decidable (a : α) : decidable (some a).dom := decidable.true def get_or_else (a : roption α) [decidable a.dom] (d : α) := if ha : a.dom then a.get ha else d @[simp] lemma get_or_else_none (d : α) : get_or_else none d = d := dif_neg id @[simp] lemma get_or_else_some (a : α) (d : α) : get_or_else (some a) d = a := dif_pos trivial @[simp] theorem mem_to_option {o : roption α} [decidable o.dom] {a : α} : a ∈ to_option o ↔ a ∈ o := begin unfold to_option, by_cases h : o.dom; simp [h], { exact ⟨λ h, ⟨_, h⟩, λ ⟨_, h⟩, h⟩ }, { exact mt Exists.fst h } end /-- Convert an `option α` into an `roption α` -/ def of_option : option α → roption α | option.none := none | (option.some a) := some a @[simp] theorem mem_of_option {a : α} : ∀ {o : option α}, a ∈ of_option o ↔ a ∈ o | option.none := ⟨λ h, h.fst.elim, λ h, option.no_confusion h⟩ | (option.some b) := ⟨λ h, congr_arg option.some h.snd, λ h, ⟨trivial, option.some.inj h⟩⟩ @[simp] theorem of_option_dom {α} : ∀ (o : option α), (of_option o).dom ↔ o.is_some | option.none := by simp [of_option, none] | (option.some a) := by simp [of_option] theorem of_option_eq_get {α} (o : option α) : of_option o = ⟨_, @option.get _ o⟩ := roption.ext' (of_option_dom o) $ λ h₁ h₂, by cases o; [cases h₁, refl] instance : has_coe (option α) (roption α) := ⟨of_option⟩ @[simp] theorem mem_coe {a : α} {o : option α} : a ∈ (o : roption α) ↔ a ∈ o := mem_of_option @[simp] theorem coe_none : (@option.none α : roption α) = none := rfl @[simp] theorem coe_some (a : α) : (option.some a : roption α) = some a := rfl @[elab_as_eliminator] protected lemma roption.induction_on {P : roption α → Prop} (a : roption α) (hnone : P none) (hsome : ∀ a : α, P (some a)) : P a := (classical.em a.dom).elim (λ h, roption.some_get h ▸ hsome _) (λ h, (eq_none_iff'.2 h).symm ▸ hnone) instance of_option_decidable : ∀ o : option α, decidable (of_option o).dom | option.none := roption.none_decidable | (option.some a) := roption.some_decidable a @[simp] theorem to_of_option (o : option α) : to_option (of_option o) = o := by cases o; refl @[simp] theorem of_to_option (o : roption α) [decidable o.dom] : of_option (to_option o) = o := ext $ λ a, mem_of_option.trans mem_to_option noncomputable def equiv_option : roption α ≃ option α := by haveI := classical.dec; exact ⟨λ o, to_option o, of_option, λ o, of_to_option o, λ o, eq.trans (by dsimp; congr) (to_of_option o)⟩ /-- `assert p f` is a bind-like operation which appends an additional condition `p` to the domain and uses `f` to produce the value. -/ def assert (p : Prop) (f : p → roption α) : roption α := ⟨∃h : p, (f h).dom, λha, (f ha.fst).get ha.snd⟩ /-- The bind operation has value `g (f.get)`, and is defined when all the parts are defined. -/ protected def bind (f : roption α) (g : α → roption β) : roption β := assert (dom f) (λb, g (f.get b)) /-- The map operation for `roption` just maps the value and maintains the same domain. -/ def map (f : α → β) (o : roption α) : roption β := ⟨o.dom, f ∘ o.get⟩ theorem mem_map (f : α → β) {o : roption α} : ∀ {a}, a ∈ o → f a ∈ map f o | _ ⟨h, rfl⟩ := ⟨_, rfl⟩ @[simp] theorem mem_map_iff (f : α → β) {o : roption α} {b} : b ∈ map f o ↔ ∃ a ∈ o, f a = b := ⟨match b with _, ⟨h, rfl⟩ := ⟨_, ⟨_, rfl⟩, rfl⟩ end, λ ⟨a, h₁, h₂⟩, h₂ ▸ mem_map f h₁⟩ @[simp] theorem map_none (f : α → β) : map f none = none := eq_none_iff.2 $ λ a, by simp @[simp] theorem map_some (f : α → β) (a : α) : map f (some a) = some (f a) := eq_some_iff.2 $ mem_map f $ mem_some _ theorem mem_assert {p : Prop} {f : p → roption α} : ∀ {a} (h : p), a ∈ f h → a ∈ assert p f | _ _ ⟨h, rfl⟩ := ⟨⟨_, _⟩, rfl⟩ @[simp] theorem mem_assert_iff {p : Prop} {f : p → roption α} {a} : a ∈ assert p f ↔ ∃ h : p, a ∈ f h := ⟨match a with _, ⟨h, rfl⟩ := ⟨_, ⟨_, rfl⟩⟩ end, λ ⟨a, h⟩, mem_assert _ h⟩ theorem mem_bind {f : roption α} {g : α → roption β} : ∀ {a b}, a ∈ f → b ∈ g a → b ∈ f.bind g | _ _ ⟨h, rfl⟩ ⟨h₂, rfl⟩ := ⟨⟨_, _⟩, rfl⟩ @[simp] theorem mem_bind_iff {f : roption α} {g : α → roption β} {b} : b ∈ f.bind g ↔ ∃ a ∈ f, b ∈ g a := ⟨match b with _, ⟨⟨h₁, h₂⟩, rfl⟩ := ⟨_, ⟨_, rfl⟩, ⟨_, rfl⟩⟩ end, λ ⟨a, h₁, h₂⟩, mem_bind h₁ h₂⟩ @[simp] theorem bind_none (f : α → roption β) : none.bind f = none := eq_none_iff.2 $ λ a, by simp @[simp] theorem bind_some (a : α) (f : α → roption β) : (some a).bind f = f a := ext $ by simp theorem bind_some_eq_map (f : α → β) (x : roption α) : x.bind (some ∘ f) = map f x := ext $ by simp [eq_comm] theorem bind_assoc {γ} (f : roption α) (g : α → roption β) (k : β → roption γ) : (f.bind g).bind k = f.bind (λ x, (g x).bind k) := ext $ λ a, by simp; exact ⟨λ ⟨_, ⟨_, h₁, h₂⟩, h₃⟩, ⟨_, h₁, _, h₂, h₃⟩, λ ⟨_, h₁, _, h₂, h₃⟩, ⟨_, ⟨_, h₁, h₂⟩, h₃⟩⟩ @[simp] theorem bind_map {γ} (f : α → β) (x) (g : β → roption γ) : (map f x).bind g = x.bind (λ y, g (f y)) := by rw [← bind_some_eq_map, bind_assoc]; simp @[simp] theorem map_bind {γ} (f : α → roption β) (x : roption α) (g : β → γ) : map g (x.bind f) = x.bind (λ y, map g (f y)) := by rw [← bind_some_eq_map, bind_assoc]; simp [bind_some_eq_map] theorem map_map (g : β → γ) (f : α → β) (o : roption α) : map g (map f o) = map (g ∘ f) o := by rw [← bind_some_eq_map, bind_map, bind_some_eq_map] instance : monad roption := { pure := @some, map := @map, bind := @roption.bind } instance : is_lawful_monad roption := { bind_pure_comp_eq_map := @bind_some_eq_map, id_map := λ β f, by cases f; refl, pure_bind := @bind_some, bind_assoc := @bind_assoc } theorem map_id' {f : α → α} (H : ∀ (x : α), f x = x) (o) : map f o = o := by rw [show f = id, from funext H]; exact id_map o @[simp] theorem bind_some_right (x : roption α) : x.bind some = x := by rw [bind_some_eq_map]; simp [map_id'] @[simp] theorem ret_eq_some (a : α) : return a = some a := rfl @[simp] theorem map_eq_map {α β} (f : α → β) (o : roption α) : f <$> o = map f o := rfl @[simp] theorem bind_eq_bind {α β} (f : roption α) (g : α → roption β) : f >>= g = f.bind g := rfl instance : monad_fail roption := { fail := λ_ _, none, ..roption.monad } /- `restrict p o h` replaces the domain of `o` with `p`, and is well defined when `p` implies `o` is defined. -/ def restrict (p : Prop) : ∀ (o : roption α), (p → o.dom) → roption α | ⟨d, f⟩ H := ⟨p, λh, f (H h)⟩ @[simp] theorem mem_restrict (p : Prop) (o : roption α) (h : p → o.dom) (a : α) : a ∈ restrict p o h ↔ p ∧ a ∈ o := begin cases o, dsimp [restrict, mem_eq], split, { rintro ⟨h₀, h₁⟩, exact ⟨h₀, ⟨_, h₁⟩⟩ }, rintro ⟨h₀, h₁, h₂⟩, exact ⟨h₀, h₂⟩ end /-- `unwrap o` gets the value at `o`, ignoring the condition. (This function is unsound.) -/ meta def unwrap (o : roption α) : α := o.get undefined theorem assert_defined {p : Prop} {f : p → roption α} : ∀ (h : p), (f h).dom → (assert p f).dom := exists.intro theorem bind_defined {f : roption α} {g : α → roption β} : ∀ (h : f.dom), (g (f.get h)).dom → (f.bind g).dom := assert_defined @[simp] theorem bind_dom {f : roption α} {g : α → roption β} : (f.bind g).dom ↔ ∃ h : f.dom, (g (f.get h)).dom := iff.rfl end roption /-- `pfun α β`, or `α →. β`, is the type of partial functions from `α` to `β`. It is defined as `α → roption β`. -/ def pfun (α : Type*) (β : Type*) := α → roption β infixr ` →. `:25 := pfun namespace pfun variables {α : Type*} {β : Type*} {γ : Type*} /-- The domain of a partial function -/ def dom (f : α →. β) : set α := λ a, (f a).dom theorem mem_dom (f : α →. β) (x : α) : x ∈ dom f ↔ ∃ y, y ∈ f x := by simp [dom, set.mem_def, roption.dom_iff_mem] theorem dom_eq (f : α →. β) : dom f = {x | ∃ y, y ∈ f x} := set.ext (mem_dom f) /-- Evaluate a partial function -/ def fn (f : α →. β) (x) (h : dom f x) : β := (f x).get h /-- Evaluate a partial function to return an `option` -/ def eval_opt (f : α →. β) [D : decidable_pred (dom f)] (x : α) : option β := @roption.to_option _ _ (D x) /-- Partial function extensionality -/ def ext' {f g : α →. β} (H1 : ∀ a, a ∈ dom f ↔ a ∈ dom g) (H2 : ∀ a p q, f.fn a p = g.fn a q) : f = g := funext $ λ a, roption.ext' (H1 a) (H2 a) def ext {f g : α →. β} (H : ∀ a b, b ∈ f a ↔ b ∈ g a) : f = g := funext $ λ a, roption.ext (H a) /-- Turn a partial function into a function out of a subtype -/ def as_subtype (f : α →. β) (s : {x // f.dom x}) : β := f.fn s.1 s.2 def equiv_subtype : (α →. β) ≃ (Σ p : α → Prop, subtype p → β) := ⟨λ f, ⟨f.dom, as_subtype f⟩, λ ⟨p, f⟩ x, ⟨p x, λ h, f ⟨x, h⟩⟩, λ f, funext $ λ a, roption.eta _, λ ⟨p, f⟩, by dsimp; congr; funext a; cases a; refl⟩ theorem as_subtype_eq_of_mem {f : α →. β} {x : α} {y : β} (fxy : y ∈ f x) (domx : x ∈ f.dom) : f.as_subtype ⟨x, domx⟩ = y := roption.mem_unique (roption.get_mem _) fxy /-- Turn a total function into a partial function -/ protected def lift (f : α → β) : α →. β := λ a, roption.some (f a) instance : has_coe (α → β) (α →. β) := ⟨pfun.lift⟩ @[simp] theorem lift_eq_coe (f : α → β) : pfun.lift f = f := rfl @[simp] theorem coe_val (f : α → β) (a : α) : (f : α →. β) a = roption.some (f a) := rfl /-- The graph of a partial function is the set of pairs `(x, f x)` where `x` is in the domain of `f`. -/ def graph (f : α →. β) : set (α × β) := {p | p.2 ∈ f p.1} def graph' (f : α →. β) : rel α β := λ x y, y ∈ f x /-- The range of a partial function is the set of values `f x` where `x` is in the domain of `f`. -/ def ran (f : α →. β) : set β := {b | ∃a, b ∈ f a} /-- Restrict a partial function to a smaller domain. -/ def restrict (f : α →. β) {p : set α} (H : p ⊆ f.dom) : α →. β := λ x, roption.restrict (p x) (f x) (@H x) @[simp] theorem mem_restrict {f : α →. β} {s : set α} (h : s ⊆ f.dom) (a : α) (b : β) : b ∈ restrict f h a ↔ a ∈ s ∧ b ∈ f a := by { simp [restrict], reflexivity } def res (f : α → β) (s : set α) : α →. β := restrict (pfun.lift f) (set.subset_univ s) theorem mem_res (f : α → β) (s : set α) (a : α) (b : β) : b ∈ res f s a ↔ (a ∈ s ∧ f a = b) := by { simp [res], split; {intro h, simp [h]} } theorem res_univ (f : α → β) : pfun.res f set.univ = f := rfl theorem dom_iff_graph (f : α →. β) (x : α) : x ∈ f.dom ↔ ∃y, (x, y) ∈ f.graph := roption.dom_iff_mem theorem lift_graph {f : α → β} {a b} : (a, b) ∈ (f : α →. β).graph ↔ f a = b := show (∃ (h : true), f a = b) ↔ f a = b, by simp /-- The monad `pure` function, the total constant `x` function -/ protected def pure (x : β) : α →. β := λ_, roption.some x /-- The monad `bind` function, pointwise `roption.bind` -/ def bind (f : α →. β) (g : β → α →. γ) : α →. γ := λa, roption.bind (f a) (λb, g b a) /-- The monad `map` function, pointwise `roption.map` -/ def map (f : β → γ) (g : α →. β) : α →. γ := λa, roption.map f (g a) instance : monad (pfun α) := { pure := @pfun.pure _, bind := @pfun.bind _, map := @pfun.map _ } instance : is_lawful_monad (pfun α) := { bind_pure_comp_eq_map := λ β γ f x, funext $ λ a, roption.bind_some_eq_map _ _, id_map := λ β f, by funext a; dsimp [functor.map, pfun.map]; cases f a; refl, pure_bind := λ β γ x f, funext $ λ a, roption.bind_some.{u_1 u_2} _ (f x), bind_assoc := λ β γ δ f g k, funext $ λ a, roption.bind_assoc (f a) (λ b, g b a) (λ b, k b a) } theorem pure_defined (p : set α) (x : β) : p ⊆ (@pfun.pure α _ x).dom := set.subset_univ p theorem bind_defined {α β γ} (p : set α) {f : α →. β} {g : β → α →. γ} (H1 : p ⊆ f.dom) (H2 : ∀x, p ⊆ (g x).dom) : p ⊆ (f >>= g).dom := λa ha, (⟨H1 ha, H2 _ ha⟩ : (f >>= g).dom a) def fix (f : α →. β ⊕ α) : α →. β := λ a, roption.assert (acc (λ x y, sum.inr x ∈ f y) a) $ λ h, @well_founded.fix_F _ (λ x y, sum.inr x ∈ f y) _ (λ a IH, roption.assert (f a).dom $ λ hf, by cases e : (f a).get hf with b a'; [exact roption.some b, exact IH _ ⟨hf, e⟩]) a h theorem dom_of_mem_fix {f : α →. β ⊕ α} {a : α} {b : β} (h : b ∈ fix f a) : (f a).dom := let ⟨h₁, h₂⟩ := roption.mem_assert_iff.1 h in by rw well_founded.fix_F_eq at h₂; exact h₂.fst.fst theorem mem_fix_iff {f : α →. β ⊕ α} {a : α} {b : β} : b ∈ fix f a ↔ sum.inl b ∈ f a ∨ ∃ a', sum.inr a' ∈ f a ∧ b ∈ fix f a' := ⟨λ h, let ⟨h₁, h₂⟩ := roption.mem_assert_iff.1 h in begin rw well_founded.fix_F_eq at h₂, simp at h₂, cases h₂ with h₂ h₃, cases e : (f a).get h₂ with b' a'; simp [e] at h₃, { subst b', refine or.inl ⟨h₂, e⟩ }, { exact or.inr ⟨a', ⟨_, e⟩, roption.mem_assert _ h₃⟩ } end, λ h, begin simp [fix], rcases h with ⟨h₁, h₂⟩ | ⟨a', h, h₃⟩, { refine ⟨⟨_, λ y h', _⟩, _⟩, { injection roption.mem_unique ⟨h₁, h₂⟩ h' }, { rw well_founded.fix_F_eq, simp [h₁, h₂] } }, { simp [fix] at h₃, cases h₃ with h₃ h₄, refine ⟨⟨_, λ y h', _⟩, _⟩, { injection roption.mem_unique h h' with e, exact e ▸ h₃ }, { cases h with h₁ h₂, rw well_founded.fix_F_eq, simp [h₁, h₂, h₄] } } end⟩ @[elab_as_eliminator] theorem fix_induction {f : α →. β ⊕ α} {b : β} {C : α → Sort*} {a : α} (h : b ∈ fix f a) (H : ∀ a, b ∈ fix f a → (∀ a', b ∈ fix f a' → sum.inr a' ∈ f a → C a') → C a) : C a := begin replace h := roption.mem_assert_iff.1 h, have := h.snd, revert this, induction h.fst with a ha IH, intro h₂, refine H a (roption.mem_assert_iff.2 ⟨⟨_, ha⟩, h₂⟩) (λ a' ha' fa', _), have := (roption.mem_assert_iff.1 ha').snd, exact IH _ fa' ⟨ha _ fa', this⟩ this end end pfun namespace pfun variables {α : Type*} {β : Type*} (f : α →. β) def image (s : set α) : set β := rel.image f.graph' s lemma image_def (s : set α) : image f s = {y | ∃ x ∈ s, y ∈ f x} := rfl lemma mem_image (y : β) (s : set α) : y ∈ image f s ↔ ∃ x ∈ s, y ∈ f x := iff.refl _ lemma image_mono {s t : set α} (h : s ⊆ t) : f.image s ⊆ f.image t := rel.image_mono _ h lemma image_inter (s t : set α) : f.image (s ∩ t) ⊆ f.image s ∩ f.image t := rel.image_inter _ s t lemma image_union (s t : set α) : f.image (s ∪ t) = f.image s ∪ f.image t := rel.image_union _ s t def preimage (s : set β) : set α := rel.preimage (λ x y, y ∈ f x) s lemma preimage_def (s : set β) : preimage f s = {x | ∃ y ∈ s, y ∈ f x} := rfl def mem_preimage (s : set β) (x : α) : x ∈ preimage f s ↔ ∃ y ∈ s, y ∈ f x := iff.refl _ lemma preimage_subset_dom (s : set β) : f.preimage s ⊆ f.dom := assume x ⟨y, ys, fxy⟩, roption.dom_iff_mem.mpr ⟨y, fxy⟩ lemma preimage_mono {s t : set β} (h : s ⊆ t) : f.preimage s ⊆ f.preimage t := rel.preimage_mono _ h lemma preimage_inter (s t : set β) : f.preimage (s ∩ t) ⊆ f.preimage s ∩ f.preimage t := rel.preimage_inter _ s t lemma preimage_union (s t : set β) : f.preimage (s ∪ t) = f.preimage s ∪ f.preimage t := rel.preimage_union _ s t lemma preimage_univ : f.preimage set.univ = f.dom := by ext; simp [mem_preimage, mem_dom] def core (s : set β) : set α := rel.core f.graph' s lemma core_def (s : set β) : core f s = {x | ∀ y, y ∈ f x → y ∈ s} := rfl lemma mem_core (x : α) (s : set β) : x ∈ core f s ↔ (∀ y, y ∈ f x → y ∈ s) := iff.rfl lemma compl_dom_subset_core (s : set β) : -f.dom ⊆ f.core s := assume x hx y fxy, absurd ((mem_dom f x).mpr ⟨y, fxy⟩) hx lemma core_mono {s t : set β} (h : s ⊆ t) : f.core s ⊆ f.core t := rel.core_mono _ h lemma core_inter (s t : set β) : f.core (s ∩ t) = f.core s ∩ f.core t := rel.core_inter _ s t lemma mem_core_res (f : α → β) (s : set α) (t : set β) (x : α) : x ∈ core (res f s) t ↔ (x ∈ s → f x ∈ t) := begin simp [mem_core, mem_res], split, { intros h h', apply h _ h', reflexivity }, intros h y xs fxeq, rw ←fxeq, exact h xs end section local attribute [instance] classical.prop_decidable lemma core_res (f : α → β) (s : set α) (t : set β) : core (res f s) t = -s ∪ f ⁻¹' t := by { ext, rw mem_core_res, by_cases h : x ∈ s; simp [h] } end lemma core_restrict (f : α → β) (s : set β) : core (f : α →. β) s = set.preimage f s := by ext x; simp [core_def] lemma preimage_subset_core (f : α →. β) (s : set β) : f.preimage s ⊆ f.core s := assume x ⟨y, ys, fxy⟩ y' fxy', have y = y', from roption.mem_unique fxy fxy', this ▸ ys lemma preimage_eq (f : α →. β) (s : set β) : f.preimage s = f.core s ∩ f.dom := set.eq_of_subset_of_subset (set.subset_inter (preimage_subset_core f s) (preimage_subset_dom f s)) (assume x ⟨xcore, xdom⟩, let y := (f x).get xdom in have ys : y ∈ s, from xcore _ (roption.get_mem _), show x ∈ preimage f s, from ⟨(f x).get xdom, ys, roption.get_mem _⟩) lemma core_eq (f : α →. β) (s : set β) : f.core s = f.preimage s ∪ -f.dom := by rw [preimage_eq, set.union_distrib_right, set.union_comm (dom f), set.compl_union_self, set.inter_univ, set.union_eq_self_of_subset_right (compl_dom_subset_core f s)] lemma preimage_as_subtype (f : α →. β) (s : set β) : f.as_subtype ⁻¹' s = subtype.val ⁻¹' pfun.preimage f s := begin ext x, simp only [set.mem_preimage, set.mem_set_of_eq, pfun.as_subtype, pfun.mem_preimage], show pfun.fn f (x.val) _ ∈ s ↔ ∃ y ∈ s, y ∈ f (x.val), exact iff.intro (assume h, ⟨_, h, roption.get_mem _⟩) (assume ⟨y, ys, fxy⟩, have f.fn x.val x.property ∈ f x.val := roption.get_mem _, roption.mem_unique fxy this ▸ ys) end end pfun
b14494802dbbbf0f562983f972fd48547a06c4bf
4727251e0cd73359b15b664c3170e5d754078599
/src/tactic/apply_fun.lean
997834e350b3625dd6cb612bbbbc6d6bda44446e
[ "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,162
lean
/- Copyright (c) 2019 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Keeley Hoek, Patrick Massot -/ import tactic.monotonicity namespace tactic /-- Apply the function `f` given by `e : pexpr` to the local hypothesis `hyp`, which must either be of the form `a = b` or `a ≤ b`, replacing the type of `hyp` with `f a = f b` or `f a ≤ f b`. If `hyp` names an inequality then a new goal `monotone f` is created, unless the name of a proof of this fact is passed as the optional argument `mono_lem`, or the `mono` tactic can prove it. -/ meta def apply_fun_to_hyp (e : pexpr) (mono_lem : option pexpr) (hyp : expr) : tactic unit := do { t ← infer_type hyp, prf ← match t with | `(%%l = %%r) := do ltp ← infer_type l, mv ← mk_mvar, to_expr ``(congr_arg (%%e : %%ltp → %%mv) %%hyp) | `(%%l ≤ %%r) := do Hmono ← match mono_lem with | some mono_lem := tactic.i_to_expr mono_lem | none := do n ← get_unused_name `mono, to_expr ``(monotone %%e) >>= assert n, -- In order to resolve implicit arguments in `%%e`, -- we build (and discard) the expression `%%n %%hyp` before calling the `mono` tactic. swap, n ← get_local n, to_expr ``(%%n %%hyp), swap, do { intro_lst [`x, `y, `h], `[try { dsimp }, mono] } <|> swap, return n end, to_expr ``(%%Hmono %%hyp) | _ := fail!"failed to apply {e} at {hyp}" end, clear hyp, hyp ← note hyp.local_pp_name none prf, -- let's try to force β-reduction at `h` try $ tactic.dsimp_hyp hyp simp_lemmas.mk [] { eta := false, beta := true } } /-- Attempt to "apply" a function `f` represented by the argument `e : pexpr` to the goal. If the goal is of the form `a ≠ b`, we obtain the new goal `f a ≠ f b`. If the goal is of the form `a = b`, we obtain a new goal `f a = f b`, and a subsidiary goal `injective f`. (We attempt to discharge this subsidiary goal automatically, or using the optional argument.) If the goal is of the form `a ≤ b` (or similarly for `a < b`), and `f` is an `order_iso`, we obtain a new goal `f a ≤ f b`. -/ meta def apply_fun_to_goal (e : pexpr) (lem : option pexpr) : tactic unit := do t ← target, match t with | `(%%l ≠ %%r) := to_expr ``(ne_of_apply_ne %%e) >>= apply >> skip | `(¬%%l = %%r) := to_expr ``(ne_of_apply_ne %%e) >>= apply >> skip | `(%%l ≤ %%r) := to_expr ``((order_iso.le_iff_le %%e).mp) >>= apply >> skip | `(%%l < %%r) := to_expr ``((order_iso.lt_iff_lt %%e).mp) >>= apply >> skip | `(%%l = %%r) := focus1 (do to_expr ``(%%e %%l), -- build and discard an application, to fill in implicit arguments n ← get_unused_name `inj, to_expr ``(function.injective %%e) >>= assert n, -- Attempt to discharge the `injective f` goal (focus1 $ assumption <|> (to_expr ``(equiv.injective) >>= apply >> done) <|> -- We require that applying the lemma closes the goal, not just makes progress: (lem.mmap (λ l, to_expr l >>= apply) >> done)) <|> swap, -- return to the main goal if we couldn't discharge `injective f`. n ← get_local n, apply n, clear n) | _ := fail!"failed to apply {e} to the goal" end namespace interactive setup_tactic_parser /-- Apply a function to an equality or inequality in either a local hypothesis or the goal. * If we have `h : a = b`, then `apply_fun f at h` will replace this with `h : f a = f b`. * If we have `h : a ≤ b`, then `apply_fun f at h` will replace this with `h : f a ≤ f b`, and create a subsidiary goal `monotone f`. `apply_fun` will automatically attempt to discharge this subsidiary goal using `mono`, or an explicit solution can be provided with `apply_fun f at h using P`, where `P : monotone f`. * If the goal is `a ≠ b`, `apply_fun f` will replace this with `f a ≠ f b`. * If the goal is `a = b`, `apply_fun f` will replace this with `f a = f b`, and create a subsidiary goal `injective f`. `apply_fun` will automatically attempt to discharge this subsidiary goal using local hypotheses, or if `f` is actually an `equiv`, or an explicit solution can be provided with `apply_fun f using P`, where `P : injective f`. * If the goal is `a ≤ b` (or similarly for `a < b`), and `f` is actually an `order_iso`, `apply_fun f` will replace the goal with `f a ≤ f b`. If `f` is anything else (e.g. just a function, or an `equiv`), `apply_fun` will fail. Typical usage is: ```lean open function example (X Y Z : Type) (f : X → Y) (g : Y → Z) (H : injective $ g ∘ f) : injective f := begin intros x x' h, apply_fun g at h, exact H h end ``` -/ meta def apply_fun (q : parse texpr) (locs : parse location) (lem : parse (tk "using" *> texpr)?) : tactic unit := locs.apply (apply_fun_to_hyp q lem) (apply_fun_to_goal q lem) add_tactic_doc { name := "apply_fun", category := doc_category.tactic, decl_names := [`tactic.interactive.apply_fun], tags := ["context management"] } end interactive end tactic
6b46c7beeeeebf5dfe9f0fa5dbc7c32f7ffdebdd
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/tactic/omega/int/dnf.lean
a9c88dda5c1a241c676a37dfa940e170f0a95943
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
6,276
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Seul Baek -/ import data.list.prod_sigma import tactic.omega.clause import tactic.omega.int.form /-! # DNF transformation -/ namespace omega namespace int open_locale omega.int /-- 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, push_neg, preform.holds] }, { 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 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 /-- Argument is free of negations -/ def neg_free : preform → Prop | (t =* s) := true | (t ≤* s) := true | (p ∨* q) := neg_free p ∧ neg_free q | (p ∧* q) := neg_free p ∧ neg_free q | _ := false 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 /-- Eliminate all negations from preform -/ @[simp] def neg_elim : preform → preform | (¬* (t =* s)) := (t.add_one ≤* s) ∨* (s.add_one ≤* t) | (¬* (t ≤* s)) := s.add_one ≤* t | (p ∨* q) := (neg_elim p) ∨* (neg_elim q) | (p ∧* q) := (neg_elim p) ∧* (neg_elim q) | p := p lemma neg_free_neg_elim : ∀ p : preform, is_nnf p → neg_free (neg_elim p) := begin preform.induce `[intro h1, try {simp only [neg_free, neg_elim]}, 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 : ∀ {p : preform}, preform.implies p (neg_elim p) := begin preform.induce `[intros v h, try {apply h}], { cases p with t s t s; try {apply h}, { simp only [le_and_le_iff_eq.symm, not_and_distrib, not_le, preterm.val, preform.holds] at h, simp only [int.add_one_le_iff, preterm.add_one, preterm.val, preform.holds, neg_elim], rw or_comm, assumption }, { simp only [not_le, int.add_one_le_iff, preterm.add_one, not_le, preterm.val, preform.holds, neg_elim] at *, assumption} }, { simp only [neg_elim], cases h; [{left, apply ihp}, {right, apply ihq}]; assumption }, { apply and.imp (ihp _) (ihq _) h } end @[simp] def dnf_core : preform → list clause | (p ∨* q) := (dnf_core p) ++ (dnf_core q) | (p ∧* q) := (list.product (dnf_core p) (dnf_core q)).map (λ pq, clause.append pq.fst pq.snd) | (t =* s) := [([term.sub (canonize s) (canonize t)],[])] | (t ≤* s) := [([],[term.sub (canonize s) (canonize t)])] | (¬* _) := [] /-- DNF transformation -/ def dnf (p : preform) : list clause := dnf_core $ neg_elim $ nnf p lemma exists_clause_holds {v : nat → int} : ∀ {p : preform}, neg_free p → p.holds v → ∃ c ∈ (dnf_core p), clause.holds v c := begin preform.induce `[intros h1 h2], { apply list.exists_mem_cons_of, constructor, { simp only [preterm.val, preform.holds] at h2, rw [list.forall_mem_singleton], simp only [h2, omega.int.val_canonize, omega.term.val_sub, sub_self] }, { apply list.forall_mem_nil } }, { apply list.exists_mem_cons_of, constructor, { apply list.forall_mem_nil }, { simp only [preterm.val, preform.holds] at h2 , rw [list.forall_mem_singleton], simp only [val_canonize, preterm.val, term.val_sub], rw [le_sub_comm, sub_zero], assumption } }, { cases h1 }, { cases h2 with h2 h2; [ {cases (ihp h1.left h2) with c h3}, {cases (ihq h1.right h2) with c h3}]; cases h3 with h3 h4; refine ⟨c, list.mem_append.elim_right _, h4⟩; [left,right]; assumption }, { rcases (ihp h1.left h2.left) with ⟨cp, hp1, hp2⟩, rcases (ihq h1.right h2.right) with ⟨cq, hq1, hq2⟩, refine ⟨clause.append cp cq, ⟨_, clause.holds_append hp2 hq2⟩⟩, simp only [dnf_core, list.mem_map], refine ⟨(cp,cq),⟨_,rfl⟩⟩, rw list.mem_product, constructor; assumption } end lemma clauses_sat_dnf_core {p : preform} : neg_free p → p.sat → clauses.sat (dnf_core p) := begin intros h1 h2, cases h2 with v h2, rcases (exists_clause_holds h1 h2) with ⟨c,h3,h4⟩, refine ⟨c,h3,v,h4⟩ end lemma unsat_of_clauses_unsat {p : preform} : clauses.unsat (dnf p) → p.unsat := begin intros h1 h2, apply h1, apply clauses_sat_dnf_core, apply neg_free_neg_elim _ (is_nnf_nnf _), apply preform.sat_of_implies_of_sat implies_neg_elim, have hrw := exists_congr (@nnf_equiv p), apply hrw.elim_right h2 end end int end omega
2f58d1a1295edeaf330a2c4e9a22cbe5576656b2
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/group_theory/semidirect_product.lean
86238ac809660706dbc8428bdf1374431eab6971
[ "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
8,598
lean
/- Copyright (c) 2020 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import algebra.hom.aut import logic.function.basic import group_theory.subgroup.basic /-! # Semidirect product > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines semidirect products of groups, and the canonical maps in and out of the semidirect product. The semidirect product of `N` and `G` given a hom `φ` from `G` to the automorphism group of `N` is the product of sets with the group `⟨n₁, g₁⟩ * ⟨n₂, g₂⟩ = ⟨n₁ * φ g₁ n₂, g₁ * g₂⟩` ## Key definitions There are two homs into the semidirect product `inl : N →* N ⋊[φ] G` and `inr : G →* N ⋊[φ] G`, and `lift` can be used to define maps `N ⋊[φ] G →* H` out of the semidirect product given maps `f₁ : N →* H` and `f₂ : G →* H` that satisfy the condition `∀ n g, f₁ (φ g n) = f₂ g * f₁ n * f₂ g⁻¹` ## Notation This file introduces the global notation `N ⋊[φ] G` for `semidirect_product N G φ` ## Tags group, semidirect product -/ variables (N : Type*) (G : Type*) {H : Type*} [group N] [group G] [group H] /-- The semidirect product of groups `N` and `G`, given a map `φ` from `G` to the automorphism group of `N`. It the product of sets with the group operation `⟨n₁, g₁⟩ * ⟨n₂, g₂⟩ = ⟨n₁ * φ g₁ n₂, g₁ * g₂⟩` -/ @[ext, derive decidable_eq] structure semidirect_product (φ : G →* mul_aut N) := (left : N) (right : G) attribute [pp_using_anonymous_constructor] semidirect_product notation N` ⋊[`:35 φ:35`] `:0 G :35 := semidirect_product N G φ namespace semidirect_product variables {N G} {φ : G →* mul_aut N} instance : group (N ⋊[φ] G) := { one := ⟨1, 1⟩, mul := λ a b, ⟨a.1 * φ a.2 b.1, a.2 * b.2⟩, inv := λ x, ⟨φ x.2⁻¹ x.1⁻¹, x.2⁻¹⟩, mul_assoc := λ a b c, by ext; simp [mul_assoc], one_mul := λ a, ext _ _ (by simp) (one_mul a.2), mul_one := λ a, ext _ _ (by simp) (mul_one _), mul_left_inv := λ ⟨a, b⟩, ext _ _ (show φ b⁻¹ a⁻¹ * φ b⁻¹ a = 1, by simp) (mul_left_inv b) } instance : inhabited (N ⋊[φ] G) := ⟨1⟩ @[simp] lemma one_left : (1 : N ⋊[φ] G).left = 1 := rfl @[simp] lemma one_right : (1 : N ⋊[φ] G).right = 1 := rfl @[simp] lemma inv_left (a : N ⋊[φ] G) : (a⁻¹).left = φ a.right⁻¹ a.left⁻¹ := rfl @[simp] lemma inv_right (a : N ⋊[φ] G) : (a⁻¹).right = a.right⁻¹ := rfl @[simp] lemma mul_left (a b : N ⋊[φ] G) : (a * b).left = a.left * φ a.right b.left := rfl @[simp] lemma mul_right (a b : N ⋊[φ] G) : (a * b).right = a.right * b.right := rfl /-- The canonical map `N →* N ⋊[φ] G` sending `n` to `⟨n, 1⟩` -/ def inl : N →* N ⋊[φ] G := { to_fun := λ n, ⟨n, 1⟩, map_one' := rfl, map_mul' := by intros; ext; simp } @[simp] lemma left_inl (n : N) : (inl n : N ⋊[φ] G).left = n := rfl @[simp] lemma right_inl (n : N) : (inl n : N ⋊[φ] G).right = 1 := rfl lemma inl_injective : function.injective (inl : N → N ⋊[φ] G) := function.injective_iff_has_left_inverse.2 ⟨left, left_inl⟩ @[simp] lemma inl_inj {n₁ n₂ : N} : (inl n₁ : N ⋊[φ] G) = inl n₂ ↔ n₁ = n₂ := inl_injective.eq_iff /-- The canonical map `G →* N ⋊[φ] G` sending `g` to `⟨1, g⟩` -/ def inr : G →* N ⋊[φ] G := { to_fun := λ g, ⟨1, g⟩, map_one' := rfl, map_mul' := by intros; ext; simp } @[simp] lemma left_inr (g : G) : (inr g : N ⋊[φ] G).left = 1 := rfl @[simp] lemma right_inr (g : G) : (inr g : N ⋊[φ] G).right = g := rfl lemma inr_injective : function.injective (inr : G → N ⋊[φ] G) := function.injective_iff_has_left_inverse.2 ⟨right, right_inr⟩ @[simp] lemma inr_inj {g₁ g₂ : G} : (inr g₁ : N ⋊[φ] G) = inr g₂ ↔ g₁ = g₂ := inr_injective.eq_iff lemma inl_aut (g : G) (n : N) : (inl (φ g n) : N ⋊[φ] G) = inr g * inl n * inr g⁻¹ := by ext; simp lemma inl_aut_inv (g : G) (n : N) : (inl ((φ g)⁻¹ n) : N ⋊[φ] G) = inr g⁻¹ * inl n * inr g := by rw [← monoid_hom.map_inv, inl_aut, inv_inv] @[simp] lemma mk_eq_inl_mul_inr (g : G) (n : N) : (⟨n, g⟩ : N ⋊[φ] G) = inl n * inr g := by ext; simp @[simp] lemma inl_left_mul_inr_right (x : N ⋊[φ] G) : inl x.left * inr x.right = x := by ext; simp /-- The canonical projection map `N ⋊[φ] G →* G`, as a group hom. -/ def right_hom : N ⋊[φ] G →* G := { to_fun := semidirect_product.right, map_one' := rfl, map_mul' := λ _ _, rfl } @[simp] lemma right_hom_eq_right : (right_hom : N ⋊[φ] G → G) = right := rfl @[simp] lemma right_hom_comp_inl : (right_hom : N ⋊[φ] G →* G).comp inl = 1 := by ext; simp [right_hom] @[simp] lemma right_hom_comp_inr : (right_hom : N ⋊[φ] G →* G).comp inr = monoid_hom.id _ := by ext; simp [right_hom] @[simp] lemma right_hom_inl (n : N) : right_hom (inl n : N ⋊[φ] G) = 1 := by simp [right_hom] @[simp] lemma right_hom_inr (g : G) : right_hom (inr g : N ⋊[φ] G) = g := by simp [right_hom] lemma right_hom_surjective : function.surjective (right_hom : N ⋊[φ] G → G) := function.surjective_iff_has_right_inverse.2 ⟨inr, right_hom_inr⟩ lemma range_inl_eq_ker_right_hom : (inl : N →* N ⋊[φ] G).range = right_hom.ker := le_antisymm (λ _, by simp [monoid_hom.mem_ker, eq_comm] {contextual := tt}) (λ x hx, ⟨x.left, by ext; simp [*, monoid_hom.mem_ker] at *⟩) section lift variables (f₁ : N →* H) (f₂ : G →* H) (h : ∀ g, f₁.comp (φ g).to_monoid_hom = (mul_aut.conj (f₂ g)).to_monoid_hom.comp f₁) /-- Define a group hom `N ⋊[φ] G →* H`, by defining maps `N →* H` and `G →* H` -/ def lift (f₁ : N →* H) (f₂ : G →* H) (h : ∀ g, f₁.comp (φ g).to_monoid_hom = (mul_aut.conj (f₂ g)).to_monoid_hom.comp f₁) : N ⋊[φ] G →* H := { to_fun := λ a, f₁ a.1 * f₂ a.2, map_one' := by simp, map_mul' := λ a b, begin have := λ n g, monoid_hom.ext_iff.1 (h n) g, simp only [mul_aut.conj_apply, monoid_hom.comp_apply, mul_equiv.coe_to_monoid_hom] at this, simp [this, mul_assoc] end } @[simp] lemma lift_inl (n : N) : lift f₁ f₂ h (inl n) = f₁ n := by simp [lift] @[simp] lemma lift_comp_inl : (lift f₁ f₂ h).comp inl = f₁ := by ext; simp @[simp] lemma lift_inr (g : G) : lift f₁ f₂ h (inr g) = f₂ g := by simp [lift] @[simp] lemma lift_comp_inr : (lift f₁ f₂ h).comp inr = f₂ := by ext; simp lemma lift_unique (F : N ⋊[φ] G →* H) : F = lift (F.comp inl) (F.comp inr) (λ _, by ext; simp [inl_aut]) := begin ext, simp only [lift, monoid_hom.comp_apply, monoid_hom.coe_mk], rw [← F.map_mul, inl_left_mul_inr_right], end /-- Two maps out of the semidirect product are equal if they're equal after composition with both `inl` and `inr` -/ lemma hom_ext {f g : (N ⋊[φ] G) →* H} (hl : f.comp inl = g.comp inl) (hr : f.comp inr = g.comp inr) : f = g := by { rw [lift_unique f, lift_unique g], simp only * } end lift section map variables {N₁ : Type*} {G₁ : Type*} [group N₁] [group G₁] {φ₁ : G₁ →* mul_aut N₁} /-- Define a map from `N ⋊[φ] G` to `N₁ ⋊[φ₁] G₁` given maps `N →* N₁` and `G →* G₁` that satisfy a commutativity condition `∀ n g, f₁ (φ g n) = φ₁ (f₂ g) (f₁ n)`. -/ def map (f₁ : N →* N₁) (f₂ : G →* G₁) (h : ∀ g : G, f₁.comp (φ g).to_monoid_hom = (φ₁ (f₂ g)).to_monoid_hom.comp f₁) : N ⋊[φ] G →* N₁ ⋊[φ₁] G₁ := { to_fun := λ x, ⟨f₁ x.1, f₂ x.2⟩, map_one' := by simp, map_mul' := λ x y, begin replace h := monoid_hom.ext_iff.1 (h x.right) y.left, ext; simp * at *, end } variables (f₁ : N →* N₁) (f₂ : G →* G₁) (h : ∀ g : G, f₁.comp (φ g).to_monoid_hom = (φ₁ (f₂ g)).to_monoid_hom.comp f₁) @[simp] lemma map_left (g : N ⋊[φ] G) : (map f₁ f₂ h g).left = f₁ g.left := rfl @[simp] lemma map_right (g : N ⋊[φ] G) : (map f₁ f₂ h g).right = f₂ g.right := rfl @[simp] lemma right_hom_comp_map : right_hom.comp (map f₁ f₂ h) = f₂.comp right_hom := rfl @[simp] lemma map_inl (n : N) : map f₁ f₂ h (inl n) = inl (f₁ n) := by simp [map] @[simp] lemma map_comp_inl : (map f₁ f₂ h).comp inl = inl.comp f₁ := by ext; simp @[simp] lemma map_inr (g : G) : map f₁ f₂ h (inr g) = inr (f₂ g) := by simp [map] @[simp] lemma map_comp_inr : (map f₁ f₂ h).comp inr = inr.comp f₂ := by ext; simp [map] end map end semidirect_product
7c40ab086774cceefb0e8ef2c60f49274583d731
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/docs/tutorial/Zmod37.lean
b847c1cd5a716b1267bbc7fd0b85a0a4ab8a4ac8
[ "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
8,104
lean
/- Integers mod 37 A demonstration of how to use equivalence relations and equivalence classes in Lean. We define the "congruent mod 37" relation on integers, prove it is an equivalence relation, define Zmod37 to be the equivalence classes, and put a ring structure on the quotient. -/ -- this import is helpful for some intermediate calculations import tactic.ring -- Definition of the equivalence relation definition cong_mod37 (a b : ℤ) : Prop := ∃ (k : ℤ), k * 37 = b - a -- Now check it's an equivalence reln! theorem cong_mod_refl : reflexive (cong_mod37) := begin intro x, -- to prove cong_mod37 x x we just observe that k = 0 will do. use (0 : ℤ), -- this is k simp, end theorem cong_mod_symm : symmetric (cong_mod37) := begin intros a b H, -- H : cond_mod37 a b cases H with l Hl, -- Hl : l * 37 = (b - a) -- Goal is to find an integer k with k * 37 = a - b use -l, simp [Hl], end theorem cong_mod_trans : transitive (cong_mod37) := begin intros a b c Hab Hbc, cases Hab with l Hl, cases Hbc with m Hm, -- Hl : l * 37 = b - a, and Hm : m * 37 = c - b -- Goal : ∃ k, k * 37 = c - a use (l + m), rw [add_mul, Hl, Hm], ring end -- so we've now seen a general technique for proving a ≈ b -- use (the k that works) theorem cong_mod_equiv : equivalence (cong_mod37) := ⟨cong_mod_refl, cong_mod_symm, cong_mod_trans⟩ -- Now let's put an equivalence relation on ℤ definition Zmod37.setoid : setoid ℤ := { r := cong_mod37, iseqv := cong_mod_equiv } -- Tell the type class inference system about this equivalence relation. local attribute [instance] Zmod37.setoid -- Now we can make the quotient. definition Zmod37 := quotient (Zmod37.setoid) -- now a little bit of basic interface namespace Zmod37 -- Let's give a name to the reduction mod 37 map. definition reduce_mod37 : ℤ → Zmod37 := quot.mk (cong_mod37) -- Let's now set up a coercion. definition coe_int_Zmod37 : has_coe ℤ (Zmod37) := ⟨reduce_mod37⟩ -- Let's tell Lean that given an integer, it can consider it as -- an integer mod 37 automatically. local attribute [instance] coe_int_Zmod37 -- Notation for 0 and 1 instance : has_zero (Zmod37) := ⟨reduce_mod37 0⟩ instance : has_one (Zmod37) := ⟨reduce_mod37 1⟩ -- Add basic facts about 0 and 1 to the set of simp facts @[simp] theorem of_int_zero : (0 : (Zmod37)) = reduce_mod37 0 := rfl @[simp] theorem of_int_one : (1 : (Zmod37)) = reduce_mod37 1 := rfl -- now back to the maths -- here's a useful lemma -- it's needed to prove addition is well-defined on the quotient. -- Note the use of quotient.sound to get from Zmod37 back to Z lemma congr_add (a₁ a₂ b₁ b₂ : ℤ) : a₁ ≈ b₁ → a₂ ≈ b₂ → ⟦a₁ + a₂⟧ = ⟦b₁ + b₂⟧ := begin intros H1 H2, cases H1 with m Hm, -- Hm : m * 37 = b₁ - a₁ cases H2 with n Hn, -- Hn : n * 37 = b₂ - a₂ -- goal is ⟦a₁ + a₂⟧ = ⟦b₁ + b₂⟧ apply quotient.sound, -- goal now a₁ + a₂ ≈ b₁ + b₂, and we know how to do these. use (m + n), rw [add_mul, Hm, Hn], ring end -- That lemma above is *exactly* what we need to make sure addition is -- well-defined on Zmod37, so let's do this now, using quotient.lift -- note: stuff like "add" is used everywhere so it's best to protect. protected definition add : Zmod37 → Zmod37 → Zmod37 := quotient.lift₂ (λ a b : ℤ, ⟦a + b⟧) (begin show ∀ (a₁ a₂ b₁ b₂ : ℤ), a₁ ≈ b₁ → a₂ ≈ b₂ → ⟦a₁ + a₂⟧ = ⟦b₁ + b₂⟧, -- that's what quotient.lift₂ reduces us to doing. But we did it already! exact congr_add, end) -- Now here's the lemma we need for the definition of neg -- I spelt out the proof for add, here's a quick term proof for neg. lemma congr_neg (a b : ℤ) : a ≈ b → ⟦-a⟧ = ⟦-b⟧ := λ ⟨m, Hm⟩, quotient.sound ⟨-m, by simp [Hm]⟩ protected def neg : Zmod37 → Zmod37 := quotient.lift (λ a : ℤ, ⟦-a⟧) congr_neg -- For multiplication I won't even bother proving the lemma, I'll just let ring do it protected def mul : Zmod37 → Zmod37 → Zmod37 := quotient.lift₂ (λ a b : ℤ, ⟦a * b⟧) (λ a₁ a₂ b₁ b₂ ⟨m₁, H₁⟩ ⟨m₂, H₂⟩, quotient.sound ⟨b₁ * m₂ + a₂ * m₁, by rw [add_mul, mul_assoc, mul_assoc, H₁, H₂]; ring⟩) -- this adds notation to the quotient instance : has_add (Zmod37) := ⟨Zmod37.add⟩ instance : has_neg (Zmod37) := ⟨Zmod37.neg⟩ instance : has_mul (Zmod37) := ⟨Zmod37.mul⟩ -- these are now very cool proofs: @[simp] lemma coe_add {a b : ℤ} : (↑(a + b) : Zmod37) = ↑a + ↑b := rfl @[simp] lemma coe_neg {a : ℤ} : (↑(-a) : Zmod37) = -↑a := rfl @[simp] lemma coe_mul {a b : ℤ} : (↑(a * b) : Zmod37) = ↑a * ↑b := rfl -- Note that the proof of these results is `rfl`. If we had defined addition -- on the quotient in the standard way that mathematicians do, -- by choosing representatives and then adding them, -- then the proof would not be rfl. This is the power of quotient.lift. -- Now here's how to use quotient.induction_on and quotient.sound instance : add_comm_group (Zmod37) := { add_comm_group . zero := 0, -- because we already defined has_zero add := (+), -- could also have written has_add.add or Zmod37.add neg := has_neg.neg, zero_add := λ abar, quotient.induction_on abar (begin -- goal is ∀ (a : ℤ), 0 + ⟦a⟧ = ⟦a⟧ -- that's what quotient.induction_on does for us intro a, apply quotient.sound, -- works because 0 + ⟦a⟧ is by definition ⟦0⟧ + ⟦a⟧ which -- is by definition ⟦0 + a⟧ -- goal is now 0 + a ≈ a -- here's the way we used to do it. use (0 : ℤ), simp, -- but there are tricks now, which I'll show you with add_zero and add_assoc. end), add_assoc := λ abar bbar cbar,quotient.induction_on₃ abar bbar cbar (λ a b c, begin -- goal now ⟦a⟧ + ⟦b⟧ + ⟦c⟧ = ⟦a⟧ + (⟦b⟧ + ⟦c⟧) apply quotient.sound, -- goal now a + b + c ≈ a + (b + c) rw add_assoc, -- done :-) because after a rw a goal is closed if it's of the form x ≈ x, -- as ≈ is known by Lean to be reflexive. end), add_zero := -- I will introduce some more sneaky stuff now -- add_zero for Zmod37 follows from add_zero on Z. -- Note use of $ instead of the brackets λ abar, quotient.induction_on abar $ λ a, quotient.sound $ by rw add_zero, -- that's it! Term mode proof. add_left_neg := -- super-slow method not even using quotient.induction_on begin intro abar, cases (quot.exists_rep abar) with a Ha, rw [←Ha], apply quot.sound, use (0 : ℤ), simp, end, -- but really all proofs should just look something like this add_comm := λ abar bbar, quotient.induction_on₂ abar bbar $ λ _ _,quotient.sound $ by rw add_comm, -- the noise at the beginning is just the machine; all the work is done by the rewrite } -- Now let's just nail this using all the tricks in the book. All ring axioms on the quotient -- follow from the corresponding axioms for Z. instance : comm_ring (Zmod37) := { mul := Zmod37.mul, -- could have written (*) -- Now look how the proof of mul_assoc is just the same structure as add_comm above -- but with three variables not two mul_assoc := λ a b c, quotient.induction_on₃ a b c $ λ _ _ _, quotient.sound $ by rw mul_assoc, one := 1, one_mul := λ a, quotient.induction_on a $ λ _, quotient.sound $ by rw one_mul, mul_one := λ a, quotient.induction_on a $ λ _, quotient.sound $ by rw mul_one, left_distrib := λ a b c, quotient.induction_on₃ a b c $ λ _ _ _, quotient.sound $ by rw left_distrib, right_distrib := λ a b c, quotient.induction_on₃ a b c $ λ _ _ _, quotient.sound $ by rw right_distrib, mul_comm := λ a b, quotient.induction_on₂ a b $ λ _ _, quotient.sound $ by rw mul_comm, ..Zmod37.add_comm_group } end Zmod37
46126816d9519afc72035fc58cfafe36ed2363d0
82e44445c70db0f03e30d7be725775f122d72f3e
/src/data/pequiv.lean
c868a56d5cb8f888d3cd20ef5cf6c6649d05388b
[ "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
13,238
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import data.set.lattice /-! # Partial Equivalences In this file, we define partial equivalences `pequiv`, which are a bijection between a subset of `α` and a subset of `β`. Notationally, a `pequiv` is denoted by "`≃.`" (note that the full stop is part of the notation). The way we store these internally is with two functions `f : α → option β` and the reverse function `g : β → option α`, with the condition that if `f a` is `option.some b`, then `g b` is `option.some a`. ## Main results - `pequiv.of_set`: creates a `pequiv` from a set `s`, which sends an element to itself if it is in `s`. - `pequiv.single`: given two elements `a : α` and `b : β`, create a `pequiv` that sends them to each other, and ignores all other elements. - `pequiv.injective_of_forall_ne_is_some`/`injective_of_forall_is_some`: If the domain of a `pequiv` is all of `α` (except possibly one point), its `to_fun` is injective. ## Canonical order `pequiv` is canonically ordered by inclusion; that is, if a function `f` defined on a subset `s` is equal to `g` on that subset, but `g` is also defined on a larger set, then `f ≤ g`. We also have a definition of `⊥`, which is the empty `pequiv` (sends all to `none`), which in the end gives us a `semilattice_inf_bot` instance. ## Tags pequiv, partial equivalence -/ universes u v w x /-- A `pequiv` is a partial equivalence, a representation of a bijection between a subset of `α` and a subset of `β` -/ structure pequiv (α : Type u) (β : Type v) := (to_fun : α → option β) (inv_fun : β → option α) (inv : ∀ (a : α) (b : β), a ∈ inv_fun b ↔ b ∈ to_fun a) infixr ` ≃. `:25 := pequiv namespace pequiv variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} open function option instance : has_coe_to_fun (α ≃. β) := ⟨_, to_fun⟩ @[simp] lemma coe_mk_apply (f₁ : α → option β) (f₂ : β → option α) (h) (x : α) : (pequiv.mk f₁ f₂ h : α → option β) x = f₁ x := rfl @[ext] lemma ext : ∀ {f g : α ≃. β} (h : ∀ x, f x = g x), f = g | ⟨f₁, f₂, hf⟩ ⟨g₁, g₂, hg⟩ h := have h : f₁ = g₁, from funext h, have ∀ b, f₂ b = g₂ b, begin subst h, assume b, have hf := λ a, hf a b, have hg := λ a, hg a b, cases h : g₂ b with a, { simp only [h, option.not_mem_none, false_iff] at hg, simp only [hg, iff_false] at hf, rwa [option.eq_none_iff_forall_not_mem] }, { rw [← option.mem_def, hf, ← hg, h, option.mem_def] } end, by simp [*, funext_iff] lemma ext_iff {f g : α ≃. β} : f = g ↔ ∀ x, f x = g x := ⟨congr_fun ∘ congr_arg _, ext⟩ @[refl] protected def refl (α : Type*) : α ≃. α := { to_fun := some, inv_fun := some, inv := λ _ _, eq_comm } @[symm] protected def symm (f : α ≃. β) : β ≃. α := { to_fun := f.2, inv_fun := f.1, inv := λ _ _, (f.inv _ _).symm } lemma mem_iff_mem (f : α ≃. β) : ∀ {a : α} {b : β}, a ∈ f.symm b ↔ b ∈ f a := f.3 lemma eq_some_iff (f : α ≃. β) : ∀ {a : α} {b : β}, f.symm b = some a ↔ f a = some b := f.3 @[trans] protected def trans (f : α ≃. β) (g : β ≃. γ) : pequiv α γ := { to_fun := λ a, (f a).bind g, inv_fun := λ a, (g.symm a).bind f.symm, inv := λ a b, by simp [*, and.comm, eq_some_iff f, eq_some_iff g] at * } @[simp] lemma refl_apply (a : α) : pequiv.refl α a = some a := rfl @[simp] lemma symm_refl : (pequiv.refl α).symm = pequiv.refl α := rfl @[simp] lemma symm_symm (f : α ≃. β) : f.symm.symm = f := by cases f; refl lemma symm_injective : function.injective (@pequiv.symm α β) := left_inverse.injective symm_symm lemma trans_assoc (f : α ≃. β) (g : β ≃. γ) (h : γ ≃. δ) : (f.trans g).trans h = f.trans (g.trans h) := ext (λ _, option.bind_assoc _ _ _) lemma mem_trans (f : α ≃. β) (g : β ≃. γ) (a : α) (c : γ) : c ∈ f.trans g a ↔ ∃ b, b ∈ f a ∧ c ∈ g b := option.bind_eq_some' lemma trans_eq_some (f : α ≃. β) (g : β ≃. γ) (a : α) (c : γ) : f.trans g a = some c ↔ ∃ b, f a = some b ∧ g b = some c := option.bind_eq_some' lemma trans_eq_none (f : α ≃. β) (g : β ≃. γ) (a : α) : f.trans g a = none ↔ (∀ b c, b ∉ f a ∨ c ∉ g b) := begin simp only [eq_none_iff_forall_not_mem, mem_trans, imp_iff_not_or.symm], push_neg, tauto end @[simp] lemma refl_trans (f : α ≃. β) : (pequiv.refl α).trans f = f := by ext; dsimp [pequiv.trans]; refl @[simp] lemma trans_refl (f : α ≃. β) : f.trans (pequiv.refl β) = f := by ext; dsimp [pequiv.trans]; simp protected lemma inj (f : α ≃. β) {a₁ a₂ : α} {b : β} (h₁ : b ∈ f a₁) (h₂ : b ∈ f a₂) : a₁ = a₂ := by rw ← mem_iff_mem at *; cases h : f.symm b; simp * at * /-- If the domain of a `pequiv` is `α` except a point, its forward direction is injective. -/ lemma injective_of_forall_ne_is_some (f : α ≃. β) (a₂ : α) (h : ∀ (a₁ : α), a₁ ≠ a₂ → is_some (f a₁)) : injective f := has_left_inverse.injective ⟨λ b, option.rec_on b a₂ (λ b', option.rec_on (f.symm b') a₂ id), λ x, begin classical, cases hfx : f x, { have : x = a₂, from not_imp_comm.1 (h x) (hfx.symm ▸ by simp), simp [this] }, { simp only [hfx], rw [(eq_some_iff f).2 hfx], refl } end⟩ /-- If the domain of a `pequiv` is all of `α`, its forward direction is injective. -/ lemma injective_of_forall_is_some {f : α ≃. β} (h : ∀ (a : α), is_some (f a)) : injective f := (classical.em (nonempty α)).elim (λ hn, injective_of_forall_ne_is_some f (classical.choice hn) (λ a _, h a)) (λ hn x, (hn ⟨x⟩).elim) section of_set variables (s : set α) [decidable_pred (∈ s)] /-- Creates a `pequiv` that is the identity on `s`, and `none` outside of it. -/ def of_set (s : set α) [decidable_pred (∈ s)] : α ≃. α := { to_fun := λ a, if a ∈ s then some a else none, inv_fun := λ a, if a ∈ s then some a else none, inv := λ a b, by { split_ifs with hb ha ha, { simp [eq_comm] }, { simp [ne_of_mem_of_not_mem hb ha] }, { simp [ne_of_mem_of_not_mem ha hb] }, { simp } } } lemma mem_of_set_self_iff {s : set α} [decidable_pred (∈ s)] {a : α} : a ∈ of_set s a ↔ a ∈ s := by dsimp [of_set]; split_ifs; simp * lemma mem_of_set_iff {s : set α} [decidable_pred (∈ s)] {a b : α} : a ∈ of_set s b ↔ a = b ∧ a ∈ s := begin dsimp [of_set], split_ifs, { simp only [iff_self_and, option.mem_def, eq_comm], rintro rfl, exact h, }, { simp only [false_iff, not_and, option.not_mem_none], rintro rfl, exact h, } end @[simp] lemma of_set_eq_some_iff {s : set α} {h : decidable_pred (∈ s)} {a b : α} : of_set s b = some a ↔ a = b ∧ a ∈ s := mem_of_set_iff @[simp] lemma of_set_eq_some_self_iff {s : set α} {h : decidable_pred (∈ s)} {a : α} : of_set s a = some a ↔ a ∈ s := mem_of_set_self_iff @[simp] lemma of_set_symm : (of_set s).symm = of_set s := rfl @[simp] lemma of_set_univ : of_set set.univ = pequiv.refl α := rfl @[simp] lemma of_set_eq_refl {s : set α} [decidable_pred (∈ s)] : of_set s = pequiv.refl α ↔ s = set.univ := ⟨λ h, begin rw [set.eq_univ_iff_forall], intro, rw [← mem_of_set_self_iff, h], exact rfl end, λ h, by simp only [of_set_univ.symm, h]; congr⟩ end of_set lemma symm_trans_rev (f : α ≃. β) (g : β ≃. γ) : (f.trans g).symm = g.symm.trans f.symm := rfl lemma trans_symm (f : α ≃. β) : f.trans f.symm = of_set {a | (f a).is_some} := begin ext, dsimp [pequiv.trans], simp only [eq_some_iff f, option.is_some_iff_exists, option.mem_def, bind_eq_some', of_set_eq_some_iff], split, { rintros ⟨b, hb₁, hb₂⟩, exact ⟨pequiv.inj _ hb₂ hb₁, b, hb₂⟩ }, { simp {contextual := tt} } end lemma symm_trans (f : α ≃. β) : f.symm.trans f = of_set {b | (f.symm b).is_some} := symm_injective $ by simp [symm_trans_rev, trans_symm, -symm_symm] lemma trans_symm_eq_iff_forall_is_some {f : α ≃. β} : f.trans f.symm = pequiv.refl α ↔ ∀ a, is_some (f a) := by rw [trans_symm, of_set_eq_refl, set.eq_univ_iff_forall]; refl instance : has_bot (α ≃. β) := ⟨{ to_fun := λ _, none, inv_fun := λ _, none, inv := by simp }⟩ @[simp] lemma bot_apply (a : α) : (⊥ : α ≃. β) a = none := rfl @[simp] lemma symm_bot : (⊥ : α ≃. β).symm = ⊥ := rfl @[simp] lemma trans_bot (f : α ≃. β) : f.trans (⊥ : β ≃. γ) = ⊥ := by ext; dsimp [pequiv.trans]; simp @[simp] lemma bot_trans (f : β ≃. γ) : (⊥ : α ≃. β).trans f = ⊥ := by ext; dsimp [pequiv.trans]; simp lemma is_some_symm_get (f : α ≃. β) {a : α} (h : is_some (f a)) : is_some (f.symm (option.get h)) := is_some_iff_exists.2 ⟨a, by rw [f.eq_some_iff, some_get]⟩ section single variables [decidable_eq α] [decidable_eq β] [decidable_eq γ] /-- Create a `pequiv` which sends `a` to `b` and `b` to `a`, but is otherwise `none`. -/ def single (a : α) (b : β) : α ≃. β := { to_fun := λ x, if x = a then some b else none, inv_fun := λ x, if x = b then some a else none, inv := λ _ _, by simp; split_ifs; cc } lemma mem_single (a : α) (b : β) : b ∈ single a b a := if_pos rfl lemma mem_single_iff (a₁ a₂ : α) (b₁ b₂ : β) : b₁ ∈ single a₂ b₂ a₁ ↔ a₁ = a₂ ∧ b₁ = b₂ := by dsimp [single]; split_ifs; simp [*, eq_comm] @[simp] lemma symm_single (a : α) (b : β) : (single a b).symm = single b a := rfl @[simp] lemma single_apply (a : α) (b : β) : single a b a = some b := if_pos rfl lemma single_apply_of_ne {a₁ a₂ : α} (h : a₁ ≠ a₂) (b : β) : single a₁ b a₂ = none := if_neg h.symm lemma single_trans_of_mem (a : α) {b : β} {c : γ} {f : β ≃. γ} (h : c ∈ f b) : (single a b).trans f = single a c := begin ext, dsimp [single, pequiv.trans], split_ifs; simp * at * end lemma trans_single_of_mem {a : α} {b : β} (c : γ) {f : α ≃. β} (h : b ∈ f a) : f.trans (single b c) = single a c := symm_injective $ single_trans_of_mem _ ((mem_iff_mem f).2 h) @[simp] lemma single_trans_single (a : α) (b : β) (c : γ) : (single a b).trans (single b c) = single a c := single_trans_of_mem _ (mem_single _ _) @[simp] lemma single_subsingleton_eq_refl [subsingleton α] (a b : α) : single a b = pequiv.refl α := begin ext i j, dsimp [single], rw [if_pos (subsingleton.elim i a), subsingleton.elim i j, subsingleton.elim b j] end lemma trans_single_of_eq_none {b : β} (c : γ) {f : δ ≃. β} (h : f.symm b = none) : f.trans (single b c) = ⊥ := begin ext, simp only [eq_none_iff_forall_not_mem, option.mem_def, f.eq_some_iff] at h, dsimp [pequiv.trans, single], simp, intros, split_ifs; simp * at * end lemma single_trans_of_eq_none (a : α) {b : β} {f : β ≃. δ} (h : f b = none) : (single a b).trans f = ⊥ := symm_injective $ trans_single_of_eq_none _ h lemma single_trans_single_of_ne {b₁ b₂ : β} (h : b₁ ≠ b₂) (a : α) (c : γ) : (single a b₁).trans (single b₂ c) = ⊥ := single_trans_of_eq_none _ (single_apply_of_ne h.symm _) end single section order instance : partial_order (α ≃. β) := { le := λ f g, ∀ (a : α) (b : β), b ∈ f a → b ∈ g a, le_refl := λ _ _ _, id, le_trans := λ f g h fg gh a b, (gh a b) ∘ (fg a b), le_antisymm := λ f g fg gf, ext begin assume a, cases h : g a with b, { exact eq_none_iff_forall_not_mem.2 (λ b hb, option.not_mem_none b $ h ▸ fg a b hb) }, { exact gf _ _ h } end } lemma le_def {f g : α ≃. β} : f ≤ g ↔ (∀ (a : α) (b : β), b ∈ f a → b ∈ g a) := iff.rfl instance : order_bot (α ≃. β) := { bot_le := λ _ _ _ h, (not_mem_none _ h).elim, ..pequiv.partial_order, ..pequiv.has_bot } instance [decidable_eq α] [decidable_eq β] : semilattice_inf_bot (α ≃. β) := { inf := λ f g, { to_fun := λ a, if f a = g a then f a else none, inv_fun := λ b, if f.symm b = g.symm b then f.symm b else none, inv := λ a b, begin have := @mem_iff_mem _ _ f a b, have := @mem_iff_mem _ _ g a b, split_ifs; finish end }, inf_le_left := λ _ _ _ _, by simp; split_ifs; cc, inf_le_right := λ _ _ _ _, by simp; split_ifs; cc, le_inf := λ f g h fg gh a b, begin have := fg a b, have := gh a b, simp [le_def], split_ifs; finish end, ..pequiv.order_bot } end order end pequiv namespace equiv variables {α : Type*} {β : Type*} {γ : Type*} /-- Turns an `equiv` into a `pequiv` of the whole type. -/ def to_pequiv (f : α ≃ β) : α ≃. β := { to_fun := some ∘ f, inv_fun := some ∘ f.symm, inv := by simp [equiv.eq_symm_apply, eq_comm] } @[simp] lemma to_pequiv_refl : (equiv.refl α).to_pequiv = pequiv.refl α := rfl lemma to_pequiv_trans (f : α ≃ β) (g : β ≃ γ) : (f.trans g).to_pequiv = f.to_pequiv.trans g.to_pequiv := rfl lemma to_pequiv_symm (f : α ≃ β) : f.symm.to_pequiv = f.to_pequiv.symm := rfl lemma to_pequiv_apply (f : α ≃ β) (x : α) : f.to_pequiv x = some (f x) := rfl end equiv
f54a59a824bfc25a599e13e5992296929cd9c71a
8e31b9e0d8cec76b5aa1e60a240bbd557d01047c
/scratch/simplex.lean
34b26503cd94cc14574a5cbb67607abeb8349a95
[]
no_license
ChrisHughes24/LP
7bdd62cb648461c67246457f3ddcb9518226dd49
e3ed64c2d1f642696104584e74ae7226d8e916de
refs/heads/master
1,685,642,642,858
1,578,070,602,000
1,578,070,602,000
195,268,102
4
3
null
1,569,229,518,000
1,562,255,287,000
Lean
UTF-8
Lean
false
false
46,935
lean
import data.matrix data.rat.basic .misc tactic.fin_cases import .matrix_pequiv open matrix fintype finset function variables {m n : ℕ} local notation `rvec`:2000 n := matrix (fin 1) (fin n) ℚ local notation `cvec`:2000 m := matrix (fin m) (fin 1) ℚ def list.to_matrix (m :ℕ) (n : ℕ) (l : list (list ℚ)) : matrix (fin m) (fin n) ℚ := λ i j, (l.nth_le i sorry).nth_le j sorry local attribute [instance] matrix.ordered_comm_group matrix.decidable_le open pequiv lemma cvec_one_lt_iff {a b : cvec 1} : a < b ↔ a 0 0 < b 0 0 := begin simp only [lt_iff_le_not_le], show (∀ i j, a i j ≤ b i j) ∧ (¬ ∀ i j, b i j ≤ a i j) ↔ _, simp [unique.forall_iff], refl, end instance : discrete_linear_ordered_field (cvec 1) := { mul_nonneg := λ a b ha0 hb0 i j, by simp [matrix.mul]; exact mul_nonneg (ha0 _ _) (hb0 _ _), mul_pos := λ a b ha0 hb0, begin rw [cvec_one_lt_iff] at *, simp [matrix.mul], exact mul_pos ha0 hb0 end, le_total := λ a b, (le_total (a 0 0) (b 0 0)).elim (λ hab, or.inl $ λ i j, by fin_cases i; fin_cases j; exact hab) (λ hba, or.inr $ λ i j, by fin_cases i; fin_cases j; exact hba), zero_lt_one := dec_trivial, decidable_le := matrix.decidable_le, ..matrix.discrete_field, ..matrix.ordered_comm_group } instance : decidable_linear_order (cvec 1) := { ..matrix.discrete_linear_ordered_field } local infix ` ⬝ `:70 := matrix.mul local postfix `ᵀ` : 1500 := transpose lemma cvec_le_iff (a b : cvec n) : a ≤ b ↔ (∀ i : fin n, (single (0 : fin 1) i).to_matrix ⬝ a ≤ (single 0 i).to_matrix ⬝ b) := show (∀ i j, a i j ≤ b i j) ↔ (∀ i j k, ((single (0 : fin 1) i).to_matrix ⬝ a) j k ≤ ((single 0 i).to_matrix ⬝ b) j k), begin simp only [mul_matrix_apply], split, { intros h i j k, fin_cases j, fin_cases k, exact h _ _ }, { intros h i j, fin_cases j, exact h i 0 0 } end lemma rvec_le_iff (a b : rvec n) : a ≤ b ↔ (∀ j : fin n, a ⬝ (single j (0 : fin 1)).to_matrix ≤ b ⬝ (single j 0).to_matrix) := show (∀ i k, a i k ≤ b i k) ↔ (∀ j i k, (a ⬝ (single j (0 : fin 1)).to_matrix) i k ≤ (b ⬝ (single j 0).to_matrix) i k), begin simp only [matrix_mul_apply], split, { intros h i j k, fin_cases j, fin_cases k, exact h _ _ }, { intros h i j, fin_cases i, exact h _ 0 0 } end def rvec.to_list {n : ℕ} (x : rvec n) : list ℚ := (vector.of_fn (x 0)).1 instance has_repr_fin_fun {n : ℕ} {α : Type*} [has_repr α] : has_repr (fin n → α) := ⟨λ f, repr (vector.of_fn f).to_list⟩ instance {m n} : has_repr (matrix (fin m) (fin n) ℚ) := has_repr_fin_fun namespace simplex open list def pequiv_of_vector (v : vector (fin n) m) (hv : v.1.nodup) : fin m ≃. fin n := { to_fun := λ i, some $ v.nth i, inv_fun := λ j, fin.find (λ i, v.nth i = j), inv := λ i j, ⟨λ h, by rw ← fin.find_spec _ h; exact rfl, λ h, fin.mem_find_of_unique (begin rintros ⟨i, him⟩ ⟨j, hjm⟩ h₁ h₂, cases v, refine fin.eq_of_veq (list.nodup_iff_nth_le_inj.1 hv i j _ _ (h₁.trans h₂.symm)); simpa [v.2] end) (option.some_inj.1 h)⟩ } def nonbasis_vector_of_vector (v : vector (fin n) m) (hv : v.to_list.nodup) : {v : vector (fin n) (n - m) // v.to_list.nodup} := ⟨⟨(fin_range n).diff v.to_list, have h : m ≤ n, by rw [← list.length_fin_range n, ← v.2]; exact list.length_le_of_subperm (subperm_of_subset_nodup hv (λ _ _, list.mem_fin_range _)), begin rw [← add_right_inj m, nat.sub_add_cancel h], conv in m { rw [← vector.to_list_length v] }, rw ← length_append, conv_rhs { rw ← length_fin_range n }, exact list.perm_length ((perm_ext (nodup_append.2 ⟨nodup_diff (nodup_fin_range _), hv, by simp [list.disjoint, mem_diff_iff_of_nodup (nodup_fin_range n), imp_false]⟩) (nodup_fin_range _)).2 (by simp only [list.mem_diff_iff_of_nodup (nodup_fin_range n), list.mem_append, mem_fin_range, true_and, iff_true]; exact λ _, or.symm (decidable.em _))), end⟩, nodup_diff (nodup_fin_range _)⟩ def pre_nonbasis_of_vector (v : vector (fin n) m) (hv : v.1.nodup) : fin (n - m) ≃. fin n := pequiv_of_vector (nonbasis_vector_of_vector v hv).1 (nonbasis_vector_of_vector v hv).2 structure prebasis (m n : ℕ) : Type := ( basis : fin m ≃. fin n ) ( nonbasis : fin (n - m) ≃. fin n ) ( basis_trans_basis_symm : basis.trans basis.symm = pequiv.refl (fin m) ) ( nonbasis_trans_nonbasis_symm : nonbasis.trans nonbasis.symm = pequiv.refl (fin (n - m)) ) ( basis_trans_nonbasis_symm : basis.trans nonbasis.symm = ⊥ ) namespace prebasis open pequiv attribute [simp] basis_trans_basis_symm nonbasis_trans_nonbasis_symm basis_trans_nonbasis_symm lemma is_some_basis (B : prebasis m n) : ∀ (i : fin m), (B.basis i).is_some := by rw [← trans_symm_eq_iff_forall_is_some, basis_trans_basis_symm] lemma is_some_nonbasis (B : prebasis m n) : ∀ (k : fin (n - m)), (B.nonbasis k).is_some := by rw [← trans_symm_eq_iff_forall_is_some, nonbasis_trans_nonbasis_symm] lemma injective_basis (B : prebasis m n) : injective B.basis := injective_of_forall_is_some (is_some_basis B) lemma injective_nonbasis (B : prebasis m n) : injective B.nonbasis := injective_of_forall_is_some (is_some_nonbasis B) def basisg (B : prebasis m n) (r : fin m) : fin n := option.get (B.is_some_basis r) def nonbasisg (B : prebasis m n) (s : fin (n - m)) : fin n := option.get (B.is_some_nonbasis s) lemma injective_basisg (B : prebasis m n) : injective B.basisg := λ x y h, by rw [basisg, basisg, ← option.some_inj, option.some_get, option.some_get] at h; exact injective_basis B h lemma injective_nonbasisg (B : prebasis m n) : injective B.nonbasisg := λ x y h, by rw [nonbasisg, nonbasisg, ← option.some_inj, option.some_get, option.some_get] at h; exact injective_nonbasis B h local infix ` ♣ `: 70 := pequiv.trans def swap (B : prebasis m n) (r : fin m) (s : fin (n - m)) : prebasis m n := { basis := B.basis.trans (equiv.swap (B.basisg r) (B.nonbasisg s)).to_pequiv, nonbasis := B.nonbasis.trans (equiv.swap (B.basisg r) (B.nonbasisg s)).to_pequiv, basis_trans_basis_symm := by rw [symm_trans_rev, ← trans_assoc, trans_assoc B.basis, ← equiv.to_pequiv_symm, ← equiv.to_pequiv_trans]; simp, nonbasis_trans_nonbasis_symm := by rw [symm_trans_rev, ← trans_assoc, trans_assoc B.nonbasis, ← equiv.to_pequiv_symm, ← equiv.to_pequiv_trans]; simp, basis_trans_nonbasis_symm := by rw [symm_trans_rev, ← trans_assoc, trans_assoc B.basis, ← equiv.to_pequiv_symm, ← equiv.to_pequiv_trans]; simp } lemma not_is_some_nonbasis_of_is_some_basis (B : prebasis m n) (j : fin n) : (B.basis.symm j).is_some → (B.nonbasis.symm j).is_some → false := begin rw [option.is_some_iff_exists, option.is_some_iff_exists], rintros ⟨i, hi⟩ ⟨k, hk⟩, have : B.basis.trans B.nonbasis.symm i = none, { rw [B.basis_trans_nonbasis_symm, pequiv.bot_apply] }, rw [pequiv.trans_eq_none] at this, rw [pequiv.eq_some_iff] at hi, exact (this j k).resolve_left (not_not.2 hi) hk end lemma nonbasis_ne_none_of_basis_eq_none (B : prebasis m n) (j : fin n) (hb : B.basis.symm j = none) (hnb : B.nonbasis.symm j = none) : false := have hs : card (univ.image B.basis) = m, by rw [card_image_of_injective _ (B.injective_basis), card_univ, card_fin], have ht : card (univ.image B.nonbasis) = (n - m), by rw [card_image_of_injective _ (B.injective_nonbasis), card_univ, card_fin], have hst : disjoint (univ.image B.basis) (univ.image B.nonbasis), from finset.disjoint_left.2 begin simp only [mem_image, exists_imp_distrib, not_exists], assume j i _ hbasis k _ hnonbasis, cases option.is_some_iff_exists.1 (is_some_basis B i) with x hi, cases option.is_some_iff_exists.1 (is_some_nonbasis B k) with y hk, have hxy : x = y, { rw [← option.some_inj, ← hk, ← hi, hbasis, hnonbasis] }, subst hxy, rw [← eq_some_iff] at hi hk, refine not_is_some_nonbasis_of_is_some_basis B x _ _; simp [hi, hk] end, have (univ.image B.basis) ∪ (univ.image B.nonbasis) = univ.image (@some (fin n)), from eq_of_subset_of_card_le begin assume i h, simp only [finset.mem_image, finset.mem_union] at h, rcases h with ⟨j, _, hj⟩ | ⟨k, _, hk⟩, { simpa [hj.symm, option.is_some_iff_exists, eq_comm] using is_some_basis B j }, { simpa [hk.symm, option.is_some_iff_exists, eq_comm] using is_some_nonbasis B k } end (begin rw [card_image_of_injective, card_univ, card_fin, card_disjoint_union hst, hs, ht], { rw add_comm, exact nat.le_sub_add _ _ }, { intros _ _ h, injection h } end), begin simp only [option.eq_none_iff_forall_not_mem, mem_iff_mem B.basis, mem_iff_mem B.nonbasis] at hb hnb, have := (finset.ext.1 this (some j)).2 (mem_image_of_mem _ (mem_univ _)), simp only [hb, hnb, mem_image, finset.mem_union, option.mem_def.symm] at this, tauto end lemma is_some_basis_iff (B : prebasis m n) (j : fin n) : (B.basis.symm j).is_some ↔ ¬(B.nonbasis.symm j).is_some := ⟨not_is_some_nonbasis_of_is_some_basis B j, by erw [option.not_is_some_iff_eq_none, ← option.ne_none_iff_is_some, forall_swap]; exact nonbasis_ne_none_of_basis_eq_none B j⟩ @[simp] lemma nonbasis_basisg_eq_none (B : prebasis m n) (r : fin m) : B.nonbasis.symm (B.basisg r) = none := option.not_is_some_iff_eq_none.1 ((B.is_some_basis_iff _).1 (is_some_symm_get _ _)) @[simp] lemma basis_nonbasisg_eq_none (B : prebasis m n) (s : fin (n - m)) : B.basis.symm (B.nonbasisg s) = none := option.not_is_some_iff_eq_none.1 (mt (B.is_some_basis_iff _).1 $ not_not.2 (is_some_symm_get _ _)) @[simp] lemma basisg_mem (B : prebasis m n) (r : fin m) : (B.basisg r) ∈ B.basis r := option.get_mem _ @[simp] lemma nonbasisg_mem (B : prebasis m n) (s : fin (n - m)) : (B.nonbasisg s) ∈ B.nonbasis s := option.get_mem _ @[simp] lemma basis_basisg (B : prebasis m n) (r : fin m) : B.basis.symm (B.basisg r) = some r:= B.basis.mem_iff_mem.2 (basisg_mem _ _) @[simp] lemma nonbasis_nonbasisg (B : prebasis m n) (s : fin (n - m)) : B.nonbasis.symm (B.nonbasisg s) = some s := B.nonbasis.mem_iff_mem.2 (nonbasisg_mem _ _) lemma eq_basisg_or_nonbasisg (B : prebasis m n) (i : fin n) : (∃ j, i = B.basisg j) ∨ (∃ j, i = B.nonbasisg j) := begin dsimp only [basisg, nonbasisg], by_cases h : ↥(B.basis.symm i).is_some, { cases option.is_some_iff_exists.1 h with j hj, exact or.inl ⟨j, by rw [B.basis.eq_some_iff] at hj; rw [← option.some_inj, ← hj, option.some_get]⟩ }, { rw [(@not_iff_comm _ _ (classical.dec _) (classical.dec _)).1 (B.is_some_basis_iff _).symm] at h, cases option.is_some_iff_exists.1 h with j hj, exact or.inr ⟨j, by rw [B.nonbasis.eq_some_iff] at hj; rw [← option.some_inj, ← hj, option.some_get]⟩ } end lemma basisg_ne_nonbasisg (B : prebasis m n) (i : fin m) (j : fin (n - m)): B.basisg i ≠ B.nonbasisg j := λ h, by simpa using congr_arg B.basis.symm h lemma single_basisg_mul_basis (B : prebasis m n) (i : fin m) : ((single (0 : fin 1) (B.basisg i)).to_matrix : matrix _ _ ℚ) ⬝ B.basis.to_matrixᵀ = (single (0 : fin 1) i).to_matrix := by rw [← to_matrix_symm, ← to_matrix_trans, single_trans_of_mem _ (basis_basisg _ _)] lemma single_basisg_mul_nonbasis (B : prebasis m n) (i : fin m) : ((single (0 : fin 1) (B.basisg i)).to_matrix : matrix _ _ ℚ) ⬝ B.nonbasis.to_matrixᵀ = 0 := by rw [← to_matrix_symm, ← to_matrix_trans, single_trans_of_eq_none _ (nonbasis_basisg_eq_none _ _), to_matrix_bot]; apply_instance lemma single_nonbasisg_mul_nonbasis (B : prebasis m n) (k : fin (n - m)) : ((single (0 : fin 1) (B.nonbasisg k)).to_matrix : matrix _ _ ℚ) ⬝ B.nonbasis.to_matrixᵀ = (single (0 : fin 1) k).to_matrix := by rw [← to_matrix_symm, ← to_matrix_trans, single_trans_of_mem _ (nonbasis_nonbasisg _ _)] lemma single_nonbasisg_mul_basis (B : prebasis m n) (k : fin (n - m)) : ((single (0 : fin 1) (B.nonbasisg k)).to_matrix : matrix _ _ ℚ) ⬝ B.basis.to_matrixᵀ = 0 := by rw [← to_matrix_symm, ← to_matrix_trans, single_trans_of_eq_none _ (basis_nonbasisg_eq_none _ _), to_matrix_bot]; apply_instance lemma nonbasis_trans_basis_symm (B : prebasis m n) : B.nonbasis.trans B.basis.symm = ⊥ := symm_injective $ by rw [symm_trans_rev, symm_symm, basis_trans_nonbasis_symm, symm_bot] @[simp] lemma nonbasis_mul_basis_transpose (B : prebasis m n) : (B.nonbasis.to_matrix : matrix _ _ ℚ) ⬝ B.basis.to_matrixᵀ = 0 := by rw [← to_matrix_bot, ← B.nonbasis_trans_basis_symm, to_matrix_trans, to_matrix_symm] @[simp] lemma basis_mul_nonbasis_transpose (B : prebasis m n) : (B.basis.to_matrix : matrix _ _ ℚ) ⬝ B.nonbasis.to_matrixᵀ = 0 := by rw [← to_matrix_bot, ← B.basis_trans_nonbasis_symm, to_matrix_trans, to_matrix_symm] @[simp] lemma nonbasis_mul_nonbasis_transpose (B : prebasis m n) : (B.nonbasis.to_matrix : matrix _ _ ℚ) ⬝ B.nonbasis.to_matrixᵀ = 1 := by rw [← to_matrix_refl, ← B.nonbasis_trans_nonbasis_symm, to_matrix_trans, to_matrix_symm] @[simp] lemma basis_mul_basis_transpose (B : prebasis m n) : (B.basis.to_matrix : matrix _ _ ℚ) ⬝ B.basis.to_matrixᵀ = 1 := by rw [← to_matrix_refl, ← B.basis_trans_basis_symm, to_matrix_trans, to_matrix_symm] lemma transpose_mul_add_tranpose_mul (B : prebasis m n) : (B.basis.to_matrixᵀ ⬝ B.basis.to_matrix : matrix (fin n) (fin n) ℚ) + B.nonbasis.to_matrixᵀ ⬝ B.nonbasis.to_matrix = 1 := begin ext, repeat {rw [← to_matrix_symm, ← to_matrix_trans] }, simp only [add_val, pequiv.symm_trans, pequiv.to_matrix, one_val, pequiv.mem_of_set_iff, set.mem_set_of_eq], have := is_some_basis_iff B j, split_ifs; tauto end lemma swap_basis_eq (B : prebasis m n) (r : fin m) (s : fin (n - m)) : (B.swap r s).basis.to_matrix = (B.basis.to_matrix : matrix _ _ ℚ) - (single r (B.basisg r)).to_matrix + (single r (B.nonbasisg s)).to_matrix := begin dsimp [swap], rw [to_matrix_trans, to_matrix_swap], simp only [matrix.mul_add, sub_eq_add_neg, matrix.mul_one, matrix.mul_neg, (to_matrix_trans _ _).symm, trans_single_of_mem _ (basisg_mem B r), trans_single_of_eq_none _ (basis_nonbasisg_eq_none B s), to_matrix_bot, neg_zero, add_zero] end lemma nonbasis_trans_swap_basis_symm (B : prebasis m n) (r : fin m) (s : fin (n - m)) : B.nonbasis.trans (B.swap r s).basis.symm = single s r := begin rw [swap, symm_trans_rev, ← equiv.to_pequiv_symm, ← equiv.perm.inv_def, equiv.swap_inv], ext i j, rw [mem_single_iff], dsimp [pequiv.trans, equiv.to_pequiv, equiv.swap_apply_def], simp only [coe, coe_mk_apply, option.mem_def, option.bind_eq_some'], rw [option.mem_def.1 (nonbasisg_mem B i)], simp [B.injective_nonbasisg.eq_iff, (B.basisg_ne_nonbasisg _ _).symm], split_ifs; simp [*, eq_comm] end lemma nonbasis_mul_swap_basis_tranpose (B : prebasis m n) (r : fin m) (s : fin (n - m)) : (B.nonbasis.to_matrix : matrix _ _ ℚ) ⬝ (B.swap r s).basis.to_matrixᵀ = (single s r).to_matrix := by rw [← nonbasis_trans_swap_basis_symm, to_matrix_trans, to_matrix_symm] lemma basis_trans_swap_basis_transpose (B : prebasis m n) (r : fin m) (s : fin (n - m)) : B.basis.trans (B.swap r s).basis.symm = of_set {i | i ≠ r} := begin rw [swap, symm_trans_rev, ← equiv.to_pequiv_symm, ← equiv.perm.inv_def, equiv.swap_inv], ext i j, dsimp [pequiv.trans, equiv.to_pequiv, equiv.swap_apply_def], simp only [coe, coe_mk_apply, option.mem_def, option.bind_eq_some'], rw [option.mem_def.1 (basisg_mem B i)], simp [B.injective_basisg.eq_iff, B.basisg_ne_nonbasisg], split_ifs, { simp * }, { simp *; split; intros; simp * at * } end lemma swap_basis_transpose_apply_single_of_ne (B : prebasis m n) {r : fin m} (s : fin (n - m)) {i : fin m} (hir : i ≠ r) : ((B.swap r s).basis.to_matrixᵀ : matrix (fin n) (fin m) ℚ) ⬝ (single i (0 : fin 1)).to_matrix = B.basis.to_matrixᵀ ⬝ (single i 0).to_matrix := begin simp only [swap_basis_eq, sub_eq_add_neg, matrix.mul_add, matrix.mul_neg, matrix.mul_one, matrix.add_mul, (to_matrix_trans _ _).symm, (to_matrix_symm _).symm, transpose_add, transpose_neg, matrix.neg_mul, symm_trans_rev, trans_assoc], rw [trans_single_of_mem _ (basis_basisg _ _), trans_single_of_eq_none, trans_single_of_eq_none, to_matrix_bot, neg_zero, add_zero, add_zero]; {dsimp [single]; simp [*, B.injective_basisg.eq_iff]} <|> apply_instance end lemma swap_basis_transpose_apply_single (B : prebasis m n) (r : fin m) (s : fin (n - m)) : ((B.swap r s).basis.to_matrixᵀ : matrix (fin n) (fin m) ℚ) ⬝ (single r (0 : fin 1)).to_matrix = B.nonbasis.to_matrixᵀ ⬝ (single s (0 : fin 1)).to_matrix := begin simp only [swap_basis_eq, sub_eq_add_neg, matrix.mul_add, matrix.mul_neg, matrix.mul_one, matrix.add_mul, (to_matrix_trans _ _).symm, (to_matrix_symm _).symm, transpose_add, transpose_neg, matrix.neg_mul, symm_trans_rev, trans_assoc, symm_single], rw [trans_single_of_mem _ (basis_basisg _ _), trans_single_of_mem _ (mem_single _ _), trans_single_of_mem _ (mem_single _ _), trans_single_of_mem _ (nonbasis_nonbasisg _ _)], simp, all_goals {apply_instance} end def equiv_aux : prebasis m n ≃ Σ' (basis : fin m ≃. fin n) (nonbasis : fin (n - m) ≃. fin n) ( basis_trans_basis_symm : basis.trans basis.symm = pequiv.refl (fin m) ) ( nonbasis_trans_nonbasis_symm : nonbasis.trans nonbasis.symm = pequiv.refl (fin (n - m)) ), basis.trans nonbasis.symm = ⊥ := { to_fun := λ ⟨a, b, c, d, e⟩, ⟨a, b, c, d, e⟩, inv_fun := λ ⟨a, b, c, d, e⟩, ⟨a, b, c, d, e⟩, left_inv := λ ⟨_, _, _, _, _⟩, rfl, right_inv := λ ⟨_, _, _, _, _⟩, rfl } --instance : fintype (prebasis m n) := sorry end prebasis open prebasis /- By convention `A_bar` and `b_bar` are in tableau form, so definitions may only be correct assuming `A ⬝ B.basis.to_matrixᵀ = 1` and `b_bar = 0` -/ def pivot_element (B : prebasis m n) (A_bar : matrix (fin m) (fin n) ℚ) (r : fin m) (s : fin (n - m)) : cvec 1 := (single 0 r).to_matrix ⬝ A_bar ⬝ B.nonbasis.to_matrixᵀ ⬝ (single s 0).to_matrix def swap_inverse (B : prebasis m n) (A_bar : matrix (fin m) (fin n) ℚ) (r : fin m) (s : fin (n - m)) : matrix (fin m) (fin m) ℚ := (1 + (1 - A_bar ⬝ B.nonbasis.to_matrixᵀ ⬝ (single s (0 : fin 1)).to_matrix ⬝ (single (0 : fin 1) r).to_matrix) ⬝ (single r (0 : fin 1)).to_matrix ⬝ (pivot_element B A_bar r s)⁻¹ ⬝ (single (0 : fin 1) r).to_matrix) def ratio (B : prebasis m n) (A_bar : matrix (fin m) (fin n) ℚ) (b_bar : cvec m) (r : fin m) (s : fin (n - m)) : cvec 1 := (pivot_element B A_bar r s)⁻¹ ⬝ ((single 0 r).to_matrix ⬝ b_bar) lemma swap_mul_swap_inverse {B : prebasis m n} {A_bar : matrix (fin m) (fin n) ℚ} {r : fin m} {s : fin (n - m)} (hA_bar : A_bar ⬝ B.basis.to_matrixᵀ = 1) (hpivot : pivot_element B A_bar r s ≠ 0) : swap_inverse B A_bar r s ⬝ (A_bar ⬝ (B.swap r s).basis.to_matrixᵀ) = 1 := have ((single (0 : fin 1) r).to_matrix ⬝ (single r 0).to_matrix : cvec 1) = 1, by rw [← to_matrix_trans]; simp, begin refine mul_single_ext (λ i, _), simp only [swap_inverse, matrix.mul_add, matrix.add_mul, sub_eq_add_neg, matrix.neg_mul, matrix.mul_neg, matrix.one_mul, matrix.mul_one, matrix.mul_assoc, transpose_add, transpose_neg, mul_right_eq_of_mul_eq this, pivot_element], rw [pivot_element, matrix.mul_assoc, matrix.mul_assoc] at hpivot, by_cases h : i = r, { simp only [h, swap_basis_transpose_apply_single, mul_right_eq_of_mul_eq hA_bar, one_by_one_inv_mul_cancel hpivot, inv_eq_inverse], simp }, { have : ((single (0 : fin 1) r).to_matrix ⬝ (single i 0).to_matrix : cvec 1) = 0, { rw [← to_matrix_trans, single_trans_single_of_ne (ne.symm h), to_matrix_bot] }, simp [swap_basis_transpose_apply_single_of_ne _ _ h, mul_right_eq_of_mul_eq hA_bar, this] } end lemma has_left_inverse_swap {B : prebasis m n} {A_bar : matrix (fin m) (fin n) ℚ} {r : fin m} {s : fin (n - m)} (hA_bar : A_bar ⬝ B.basis.to_matrixᵀ = 1) (hpivot : pivot_element B A_bar r s ≠ 0) : (A_bar ⬝ (B.swap r s).basis.to_matrixᵀ).has_left_inverse := ⟨_, swap_mul_swap_inverse hA_bar hpivot⟩ lemma has_left_inverse_swap_inverse {B : prebasis m n} {A_bar : matrix (fin m) (fin n) ℚ} {r : fin m} {s : fin (n - m)} (hA_bar : A_bar ⬝ B.basis.to_matrixᵀ = 1) (hpivot : pivot_element B A_bar r s ≠ 0) : (swap_inverse B A_bar r s).has_left_inverse := has_right_inverse_iff_has_left_inverse.1 ⟨_, swap_mul_swap_inverse hA_bar hpivot⟩ lemma inverse_swap_eq {A_bar : matrix (fin m) (fin n) ℚ} {B : prebasis m n} {r : fin m} {s : fin (n - m)} (hA_bar : A_bar ⬝ B.basis.to_matrixᵀ = 1) (hpivot : pivot_element B A_bar r s ≠ 0) : inverse (A_bar ⬝ (B.swap r s).basis.to_matrixᵀ) = swap_inverse B A_bar r s := eq.symm $ eq_inverse_of_mul_eq_one $ by rw [swap_mul_swap_inverse hA_bar hpivot] def adjust (B : prebasis m n) (A_bar : matrix (fin m) (fin n) ℚ) (b_bar : cvec m) (s : fin (n - m)) (a : cvec 1) : cvec n := B.basis.to_matrixᵀ ⬝ b_bar + (B.nonbasis.to_matrixᵀ - B.basis.to_matrixᵀ ⬝ A_bar ⬝ B.nonbasis.to_matrixᵀ) ⬝ (single s 0).to_matrix ⬝ a lemma adjust_is_solution {B : prebasis m n} {A_bar : matrix (fin m) (fin n) ℚ} (b_bar : cvec m) (s : fin (n - m)) (a : cvec 1) (hA_bar : A_bar ⬝ B.basis.to_matrixᵀ = 1) : A_bar ⬝ adjust B A_bar b_bar s a = b_bar := by simp [matrix.mul_assoc, matrix.mul_add, adjust, matrix.add_mul, mul_right_eq_of_mul_eq hA_bar] lemma single_pivot_mul_adjust (B : prebasis m n) (A_bar : matrix (fin m) (fin n) ℚ) (b_bar : cvec m) (s : fin (n - m)) (a : cvec 1) : (single 0 s).to_matrix ⬝ B.nonbasis.to_matrix ⬝ adjust B A_bar b_bar s a = a := by simp [matrix.mul_assoc, matrix.add_mul, matrix.mul_add, adjust, mul_right_eq_of_mul_eq (nonbasis_mul_basis_transpose B), mul_right_eq_of_mul_eq (nonbasis_mul_nonbasis_transpose B)] lemma basis_mul_adjust (B : prebasis m n) (A_bar : matrix (fin m) (fin n) ℚ) (b_bar : cvec m) (s : fin (n - m)) (a : cvec 1) : B.basis.to_matrix ⬝ adjust B A_bar b_bar s a = b_bar - A_bar ⬝ B.nonbasis.to_matrixᵀ ⬝ (single s 0).to_matrix ⬝ a := by simp [matrix.mul_assoc, matrix.add_mul, matrix.mul_add, adjust, mul_right_eq_of_mul_eq (basis_mul_basis_transpose B), mul_right_eq_of_mul_eq (basis_mul_nonbasis_transpose B)] lemma nonbasis_mul_adjust (B : prebasis m n) (A_bar : matrix (fin m) (fin n) ℚ) (b_bar : cvec m) (s : fin (n - m)) (a : cvec 1) : B.nonbasis.to_matrix ⬝ adjust B A_bar b_bar s a = to_matrix (single s 0) ⬝ a := by simp [matrix.mul_assoc, matrix.add_mul, matrix.mul_add, adjust, mul_right_eq_of_mul_eq (nonbasis_mul_basis_transpose B), mul_right_eq_of_mul_eq (nonbasis_mul_nonbasis_transpose B)] lemma adjust_nonneg_iff {B : prebasis m n} {A_bar : matrix (fin m) (fin n) ℚ} {b_bar : cvec m} {s : fin (n - m)} {a : cvec 1} (ha : 0 ≤ a) (hb : 0 ≤ b_bar) : 0 ≤ adjust B A_bar b_bar s a ↔ ∀ (i : fin m), 0 < pivot_element B A_bar i s → a ≤ ratio B A_bar b_bar i s := have ∀ i : fin m, (single (0 : fin 1) (B.basisg i)).to_matrix ⬝ 0 ≤ (single 0 (B.basisg i)).to_matrix ⬝ (B.basis.to_matrixᵀ ⬝ b_bar + (B.nonbasis.to_matrixᵀ - B.basis.to_matrixᵀ ⬝ A_bar ⬝ B.nonbasis.to_matrixᵀ) ⬝ to_matrix (single s 0) ⬝ a) ↔ 0 < pivot_element B A_bar i s → a ≤ ratio B A_bar b_bar i s, begin assume i, simp only [matrix.mul_zero, ratio, matrix.mul_add, matrix.add_mul, matrix.mul_assoc, sub_eq_add_neg, matrix.mul_neg, matrix.neg_mul, matrix.mul_assoc, mul_right_eq_of_mul_eq (single_basisg_mul_basis B i), mul_right_eq_of_mul_eq (single_basisg_mul_nonbasis B i), matrix.zero_mul, zero_add], rw [← sub_eq_add_neg, sub_nonneg], simp only [pivot_element, matrix.mul_assoc], cases classical.em (0 < (single (0 : fin 1) i).to_matrix ⬝ (A_bar ⬝ (B.nonbasis.to_matrixᵀ ⬝ (single s (0 : fin 1)).to_matrix))) with hpos hpos, { rw [← matrix.mul_eq_mul, ← mul_comm, ← div_eq_mul_inv, le_div_iff hpos, mul_comm, matrix.mul_eq_mul], simp [matrix.mul_assoc, hpos] }, { simp only [hpos, forall_prop_of_false, iff_true, not_false_iff], simp only [(matrix.mul_assoc _ _ _).symm, (matrix.mul_eq_mul _ _).symm] at *, intros, refine le_trans (mul_nonpos_of_nonpos_of_nonneg (le_of_not_gt hpos) ha) _, rw [cvec_le_iff] at hb, simpa using hb i }, end, begin rw [adjust, cvec_le_iff], split, { assume h i, rw [← this], exact h (B.basisg i) }, { assume h j, rcases eq_basisg_or_nonbasisg B j with ⟨i, hi⟩ | ⟨k, hk⟩, { rw [hi, this], exact h _ }, { simp only [hk, matrix.mul_assoc, mul_right_eq_of_mul_eq (single_nonbasisg_mul_basis _ _), matrix.mul_add, matrix.add_mul, matrix.mul_neg, mul_right_eq_of_mul_eq (single_nonbasisg_mul_nonbasis _ _), add_zero, matrix.neg_mul, matrix.zero_mul, zero_add, matrix.mul_zero, sub_eq_add_neg, neg_zero], by_cases hks : k = s, { simpa [hks] }, { rw [mul_right_eq_of_mul_eq (single_mul_single_of_ne hks _ _), matrix.zero_mul], exact le_refl _ } } } end def reduced_cost (B : prebasis m n) (A_bar : matrix (fin m) (fin n) ℚ) (c : rvec n) : rvec (n - m) := c ⬝ (B.nonbasis.to_matrixᵀ - B.basis.to_matrixᵀ ⬝ A_bar ⬝ B.nonbasis.to_matrixᵀ) noncomputable def solution_of_basis (B : prebasis m n) (A : matrix (fin m) (fin n) ℚ) (b : cvec m) : cvec n := B.basis.to_matrixᵀ ⬝ inverse (A ⬝ B.basis.to_matrixᵀ) ⬝ b lemma solution_of_basis_is_solution {A : matrix (fin m) (fin n) ℚ} {B : prebasis m n} (b : cvec m) (hA : (A ⬝ B.basis.to_matrixᵀ).has_left_inverse) : A ⬝ solution_of_basis B A b = b := by rw [solution_of_basis, ← matrix.mul_assoc, ← matrix.mul_assoc, mul_inverse (has_right_inverse_iff_has_left_inverse.2 hA), matrix.one_mul] noncomputable def objective_function_of_basis (A : matrix (fin m) (fin n) ℚ) (B : prebasis m n) (b : cvec m) (c : rvec n) : cvec 1 := c ⬝ solution_of_basis B A b /-- For proving `solution_of_basis_eq_adjust`, it suffices to prove they are equal after left multiplication by `A_bar` and after left multiplication by `B.nonbasis.to_matrix`. This lemma helps prove that. -/ lemma basis_transpose_add_nonbasis_transpose_mul_nonbasis {B : prebasis m n} {A_bar : matrix (fin m) (fin n) ℚ} (hA_bar : A_bar ⬝ B.basis.to_matrixᵀ = 1) : (B.basis.to_matrixᵀ ⬝ A_bar + B.nonbasis.to_matrixᵀ ⬝ B.nonbasis.to_matrix) ⬝ (1 - B.basis.to_matrixᵀ ⬝ A_bar ⬝ B.nonbasis.to_matrixᵀ ⬝ B.nonbasis.to_matrix) = 1 := by rw [← transpose_mul_add_tranpose_mul B]; simp [matrix.mul_add, matrix.add_mul, matrix.mul_neg, matrix.mul_assoc, mul_right_eq_of_mul_eq hA_bar, mul_right_eq_of_mul_eq (nonbasis_mul_basis_transpose _), mul_right_eq_of_mul_eq (nonbasis_mul_nonbasis_transpose _)] lemma solution_of_basis_eq_adjust {B : prebasis m n} {A_bar : matrix (fin m) (fin n) ℚ} (b_bar : cvec m) {r : fin m} {s : fin (n - m)} (hA_bar : A_bar ⬝ B.basis.to_matrixᵀ = 1) (hpivot : pivot_element B A_bar r s ≠ 0) : solution_of_basis (B.swap r s) A_bar b_bar = adjust B A_bar b_bar s (ratio B A_bar b_bar r s) := /- It suffices to prove they are equal after left multiplication by `A_bar` and by `B.nonbasis.to_matrix` -/ suffices A_bar ⬝ (B.swap r s).basis.to_matrixᵀ ⬝ inverse (A_bar ⬝ (B.swap r s).basis.to_matrixᵀ) ⬝ b_bar = A_bar ⬝ adjust B A_bar b_bar s (ratio B A_bar b_bar r s) ∧ B.nonbasis.to_matrix ⬝ (B.swap r s).basis.to_matrixᵀ ⬝ inverse (A_bar ⬝ (B.swap r s).basis.to_matrixᵀ) ⬝ b_bar = B.nonbasis.to_matrix ⬝ adjust B A_bar b_bar s (ratio B A_bar b_bar r s), begin rw [solution_of_basis, ← matrix.mul_left_inj ⟨_, mul_eq_one_comm.1 (basis_transpose_add_nonbasis_transpose_mul_nonbasis hA_bar)⟩, matrix.add_mul, matrix.add_mul], simp only [matrix.mul_assoc] at *, rw [this.1, this.2] end, { left := by rw [adjust_is_solution _ _ _ hA_bar, matrix.mul_inverse (has_right_inverse_iff_has_left_inverse.2 (has_left_inverse_swap hA_bar hpivot)), matrix.one_mul], right := /- This `have` would be unnecessary with a powerful `assoc_rw` tactic -/ have (single s r).to_matrix ⬝ (A_bar ⬝ (B.nonbasis.to_matrixᵀ ⬝ ((single s (0 : fin 1)).to_matrix ⬝ ((single 0 r).to_matrix ⬝ ((single r 0).to_matrix ⬝ (inverse (pivot_element B A_bar r s) ⬝ ((single 0 r).to_matrix ⬝ b_bar))))))) = (single s (0 : fin 1)).to_matrix ⬝ (single 0 r).to_matrix ⬝ b_bar, begin rw [pivot_element, mul_right_eq_of_mul_eq (single_mul_single (0 : fin 1) r (0 : fin 1)), single_subsingleton_eq_refl, to_matrix_refl, matrix.one_mul, ← single_mul_single s (0 : fin 1) r], simp only [(matrix.mul_assoc _ _ _).symm], simp only [(single s (0 : fin 1)).to_matrix.mul_assoc], rw [one_by_one_mul_inv_cancel, matrix.one_mul], { simpa [pivot.matrix.mul_assoc] using hpivot } end, begin simp only [adjust, matrix.mul_add, zero_add, sub_eq_add_neg, matrix.neg_mul, mul_right_eq_of_mul_eq (nonbasis_mul_basis_transpose _), matrix.zero_mul, nonbasis_mul_swap_basis_tranpose, matrix.mul_assoc, matrix.add_mul, matrix.mul_neg, mul_right_eq_of_mul_eq (nonbasis_mul_nonbasis_transpose _), matrix.one_mul, neg_zero, add_zero, inverse_swap_eq hA_bar hpivot, swap_inverse, ratio, this, inv_eq_inverse], simp end } lemma cvec_eq_basis_add_nonbasis (B : prebasis m n) (x : cvec n) : x = B.basis.to_matrixᵀ ⬝ B.basis.to_matrix ⬝ x + B.nonbasis.to_matrixᵀ ⬝ B.nonbasis.to_matrix ⬝ x := by simp only [(matrix.mul_assoc _ _ _).symm, (matrix.add_mul _ _ _).symm, B.transpose_mul_add_tranpose_mul, matrix.one_mul] lemma objective_function_eq {B : prebasis m n} {A_bar : matrix (fin m) (fin n) ℚ} {b_bar : cvec m} {c : rvec n} {x : cvec n} (hAx : A_bar ⬝ x = b_bar) (hA_bar : A_bar ⬝ B.basis.to_matrixᵀ = 1) : c ⬝ x = c ⬝ B.basis.to_matrixᵀ ⬝ b_bar + reduced_cost B A_bar c ⬝ B.nonbasis.to_matrix ⬝ x := have B.basis.to_matrix ⬝ x = b_bar - A_bar ⬝ B.nonbasis.to_matrixᵀ ⬝ B.nonbasis.to_matrix ⬝ x, by rw [eq_sub_iff_add_eq, ← (B.basis.to_matrix).one_mul, ← hA_bar, matrix.mul_assoc, matrix.mul_assoc, matrix.mul_assoc, matrix.mul_assoc, ← matrix.mul_add, ← matrix.mul_assoc, ← matrix.mul_assoc, ← matrix.add_mul, transpose_mul_add_tranpose_mul, matrix.one_mul, hAx], begin conv_lhs {rw [cvec_eq_basis_add_nonbasis B x, matrix.mul_assoc, this]}, simp [matrix.mul_add, matrix.mul_assoc, matrix.add_mul, reduced_cost] end lemma objective_function_swap_eq {B : prebasis m n} {A_bar : matrix (fin m) (fin n) ℚ} (b_bar : cvec m) (c : rvec n) {r : fin m} {s : fin (n - m)} (hA_bar : A_bar ⬝ B.basis.to_matrixᵀ = 1) (hpivot : pivot_element B A_bar r s ≠ 0) : objective_function_of_basis A_bar (B.swap r s) b_bar c = objective_function_of_basis A_bar B b_bar c + reduced_cost B A_bar c ⬝ (single s (0 : fin 1)).to_matrix ⬝ ratio B A_bar b_bar r s := have h₁ : A_bar ⬝ (B.basis.to_matrixᵀ ⬝ b_bar) = b_bar, by rw [← matrix.mul_assoc, hA_bar, matrix.one_mul], have h₂ : (A_bar ⬝ (to_matrix ((swap B r s).basis))ᵀ).has_left_inverse, from has_left_inverse_swap hA_bar hpivot, begin rw [objective_function_of_basis, objective_function_eq (solution_of_basis_is_solution _ h₂) hA_bar, solution_of_basis_eq_adjust _ hA_bar hpivot, objective_function_of_basis, solution_of_basis, hA_bar, inverse_one, matrix.mul_one, c.mul_assoc, matrix.mul_assoc, matrix.mul_assoc], congr' 2, rw [adjust], simp only [matrix.mul_add, matrix.mul_assoc, sub_eq_add_neg, matrix.add_mul, matrix.neg_mul, matrix.mul_neg, mul_right_eq_of_mul_eq (nonbasis_mul_basis_transpose _), mul_right_eq_of_mul_eq (nonbasis_mul_nonbasis_transpose _)], simp end lemma swap_nonneg_iff {B : prebasis m n} {A_bar : matrix (fin m) (fin n) ℚ} (b_bar : cvec m) {r : fin m} {s : fin (n - m)} (hA_bar : A_bar ⬝ B.basis.to_matrixᵀ = 1) (hpivot : 0 < pivot_element B A_bar r s) (h0b : 0 ≤ b_bar) : 0 ≤ solution_of_basis (B.swap r s) A_bar b_bar ↔ (∀ i : fin m, 0 < pivot_element B A_bar i s → ratio B A_bar b_bar r s ≤ ratio B A_bar b_bar i s) := begin rw [solution_of_basis_eq_adjust _ hA_bar (ne_of_lt hpivot).symm, adjust_nonneg_iff _ h0b, ratio], rw cvec_le_iff at h0b, exact mul_nonneg (inv_nonneg.2 (le_of_lt hpivot)) (by simpa using h0b r) end lemma swap_inverse_mul_nonneg {B : prebasis m n} {A_bar : matrix (fin m) (fin n) ℚ} (b_bar : cvec m) {r : fin m} {s : fin (n - m)} (hA_bar : A_bar ⬝ B.basis.to_matrixᵀ = 1) (hpivot : 0 < pivot_element B A_bar r s) (h0b : 0 ≤ b_bar) : (∀ i : fin m, 0 < pivot_element B A_bar i s → ratio B A_bar b_bar r s ≤ ratio B A_bar b_bar i s) → 0 ≤ swap_inverse B A_bar r s ⬝ b_bar:= begin rw [← swap_nonneg_iff b_bar hA_bar hpivot h0b, solution_of_basis, inverse_swap_eq hA_bar (ne_of_lt hpivot).symm], assume hratio, rw [cvec_le_iff] at *, assume i, simpa [mul_right_eq_of_mul_eq (single_basisg_mul_basis _ _), matrix.mul_assoc] using hratio ((B.swap r s).basisg i) end def is_unbounded (A : matrix (fin m) (fin n) ℚ) (b : cvec m) (c : rvec n) : Prop := ∀ q : cvec 1, ∃ x, 0 ≤ x ∧ A ⬝ x = b ∧ q ≤ c ⬝ x def is_optimal (A : matrix (fin m) (fin n) ℚ) (b : cvec m) (c : rvec n) (x : cvec n) : Prop := 0 ≤ x ∧ A ⬝ x = b ∧ ∀ y, 0 ≤ y → A ⬝ y = b → c ⬝ y ≤ c ⬝ x def is_optimal_basis (B : prebasis m n) (A : matrix (fin m) (fin n) ℚ) (b : cvec m) (c : rvec n) : Prop := (A ⬝ B.basis.to_matrixᵀ).has_left_inverse ∧ is_optimal A b c (B.basis.to_matrixᵀ ⬝ inverse (A ⬝ B.basis.to_matrixᵀ) ⬝ b) lemma is_unbounded_of_pivot_element_nonpos {B : prebasis m n} {A_bar : matrix (fin m) (fin n) ℚ} (b_bar : cvec m) (c : rvec n) {s : fin (n - m)} (hA_bar : A_bar ⬝ B.basis.to_matrixᵀ = 1) (h0b : 0 ≤ b_bar) (hs : reduced_cost B A_bar c ⬝ (single s (0 : fin 1)).to_matrix > 0) (h : ∀ r, pivot_element B A_bar r s ≤ 0) : is_unbounded A_bar b_bar c := begin assume q, let a := (reduced_cost B A_bar c ⬝ (single s (0 : fin 1)).to_matrix)⁻¹ ⬝ (q - c ⬝ ((to_matrix (B.basis))ᵀ ⬝ b_bar)), use adjust B A_bar b_bar s (max 0 a), simp only [adjust_is_solution b_bar _ _ hA_bar, true_and, eq_self_iff_true], simp only [objective_function_eq (adjust_is_solution b_bar _ _ hA_bar) hA_bar] {single_pass := tt}, simp only [nonbasis_mul_adjust, matrix.mul_assoc], split, { rw adjust_nonneg_iff (le_max_left _ _) h0b, assume i hi, exact absurd hi (not_lt_of_ge (h _)), }, { cases le_total a 0 with ha0 ha0, { rw [max_eq_left ha0], simp only [a, (mul_eq_mul _ _).symm] at ha0, rw [mul_comm, ← div_eq_mul_inv, div_le_iff hs, _root_.zero_mul, sub_nonpos] at ha0, simpa }, { simp only [max_eq_right ha0], rw [← (reduced_cost _ _ _).mul_assoc], dsimp only [a], rw [← matrix.mul_assoc (reduced_cost _ _ _ ⬝ _ ), ← mul_eq_mul, ← mul_eq_mul, mul_inv_cancel (ne_of_lt hs).symm, one_mul], simp [le_refl] } } end lemma is_optimal_basis_of_reduced_cost_nonpos {B : prebasis m n} {A_bar : matrix (fin m) (fin n) ℚ} (b_bar : cvec m) (c : rvec n) (hA_bar : A_bar ⬝ B.basis.to_matrixᵀ = 1) (h0b : 0 ≤ b_bar) (hs : reduced_cost B A_bar c ≤ 0) : is_optimal_basis B A_bar b_bar c := begin rw [is_optimal_basis, hA_bar, inverse_one, matrix.mul_one], refine ⟨⟨1, matrix.one_mul _⟩, matrix.mul_nonneg (by rw [← to_matrix_symm]; exact pequiv_nonneg _) h0b, by rw [← matrix.mul_assoc, hA_bar, matrix.one_mul], _⟩, assume x h0x hAx, rw [objective_function_eq hAx hA_bar, ← le_sub_iff_add_le', ← matrix.mul_assoc, sub_self], exact matrix.mul_nonpos_of_nonpos_of_nonneg (matrix.mul_nonpos_of_nonpos_of_nonneg hs (pequiv_nonneg _)) h0x end def choose_pivot_column (B : prebasis m n) (A_bar : matrix (fin m) (fin n) ℚ) (b_bar : cvec m) (c : rvec n) : option (fin (n - m)) := (fin.find (λ j : fin n, ∃ h : (B.nonbasis.symm j).is_some, 0 < reduced_cost B A_bar c ⬝ (single (option.get h) (0 : fin 1)).to_matrix)).bind B.nonbasis.symm lemma choose_pivot_column_eq_none (B : prebasis m n) (A_bar : matrix (fin m) (fin n) ℚ) (b_bar : cvec m) (c : rvec n) (hA_bar : A_bar ⬝ B.basis.to_matrixᵀ = 1) (h0b : 0 ≤ b_bar) (h : choose_pivot_column B A_bar b_bar c = none) : is_optimal_basis B A_bar b_bar c := is_optimal_basis_of_reduced_cost_nonpos _ _ hA_bar h0b $ begin rw [choose_pivot_column, option.bind_eq_none] at h, have : ∀ j, j ∉ fin.find (λ j : fin n, ∃ h : (B.nonbasis.symm j).is_some, 0 < reduced_cost B A_bar c ⬝ (single (option.get h) (0 : fin 1)).to_matrix), { assume j hj, cases option.is_some_iff_exists.1 (fin.find_spec _ hj).fst with s hs, exact h s j hj hs }, rw [← option.eq_none_iff_forall_not_mem, fin.find_eq_none_iff] at this, rw [rvec_le_iff], assume j, refine le_of_not_gt (λ h0j, _), have hj : ↥(B.nonbasis.symm (B.nonbasisg j)).is_some, from option.is_some_iff_exists.2 ⟨j, nonbasis_nonbasisg _ _⟩, have hjg : j = option.get hj, { rw [← option.some_inj, option.some_get, nonbasis_nonbasisg] }, exact this (B.nonbasisg j) ⟨hj, by { rw ← hjg, rwa [matrix.zero_mul] at h0j} ⟩ end lemma choose_pivot_column_spec (B : prebasis m n) (A_bar : matrix (fin m) (fin n) ℚ) (b_bar : cvec m) (c : rvec n) (s : fin (n - m)) (hA_bar : A_bar ⬝ B.basis.to_matrixᵀ = 1) (h0b : 0 ≤ b_bar) (h : choose_pivot_column B A_bar b_bar c = some s) : 0 < reduced_cost B A_bar c ⬝ (single s (0 : fin 1)).to_matrix := begin rw [choose_pivot_column, option.bind_eq_some'] at h, cases h with j hj, have := fin.find_spec _ hj.1, have hs : s = option.get this.fst, { rw [← option.some_inj, option.some_get, hj.2] }, exact hs.symm ▸ this.snd end set_option class.instance_max_depth 60 def choose_pivot_row (B : prebasis m n) (A_bar : matrix (fin m) (fin n) ℚ) (b_bar : cvec m) (c : rvec n) (s : fin (n - m)) : option (fin m) := (fin.find (λ j : fin n, ∃ h : (B.basis.symm j).is_some, 0 < pivot_element B A_bar (option.get h) s ∧ ∀ i : fin m, ((0 : cvec 1) < pivot_element B A_bar i s) → ratio B A_bar b_bar (option.get h) s ≤ ratio B A_bar b_bar i s)).bind B.basis.symm lemma choose_pivot_row_spec (B : prebasis m n) (A_bar : matrix (fin m) (fin n) ℚ) (b_bar : cvec m) (c : rvec n) (r : fin m) (s : fin (n - m)) (hr : r ∈ choose_pivot_row B A_bar b_bar c s) : 0 < pivot_element B A_bar r s ∧ ∀ i : fin m, 0 < pivot_element B A_bar i s → ratio B A_bar b_bar r s ≤ ratio B A_bar b_bar i s := begin rw [choose_pivot_row, option.mem_def, option.bind_eq_some'] at hr, cases hr with j hj, have hrj : r = option.get (fin.find_spec _ hj.1).fst, { rw [← option.some_inj, option.some_get, ← hj.2] }, rw hrj, exact (fin.find_spec _ hj.1).snd end lemma choose_pivot_row_eq_none (B : prebasis m n) (A_bar : matrix (fin m) (fin n) ℚ) (b_bar : cvec m) (c : rvec n) (r : fin m) (s : fin (n - m)) (hn : choose_pivot_row B A_bar b_bar c s = none) : pivot_element B A_bar r s ≤ 0 := le_of_not_gt $ λ hpivot, begin rw [choose_pivot_row, option.bind_eq_none] at hn, cases @finset.min_of_mem _ _ ((univ.filter (λ j, 0 < pivot_element B A_bar j s)).image (λ i, ratio B A_bar b_bar i s)) (ratio B A_bar b_bar r s) (mem_image_of_mem _ (finset.mem_filter.2 ⟨mem_univ _, hpivot⟩)) with q hq, rcases mem_image.1 (mem_of_min hq) with ⟨i, hip, hiq⟩, subst hiq, have : ∀ j : fin n, j ∉ fin.find (λ j : fin n, ∃ h : (B.basis.symm j).is_some, 0 < pivot_element B A_bar (option.get h) s ∧ ∀ i : fin m, 0 < pivot_element B A_bar i s → ratio B A_bar b_bar (option.get h) s ≤ ratio B A_bar b_bar i s), { assume j hj, cases option.is_some_iff_exists.1 (fin.find_spec _ hj).fst with r hr, exact hn _ _ hj hr }, rw [← option.eq_none_iff_forall_not_mem, fin.find_eq_none_iff] at this, have hi : ↥(B.basis.symm (B.basisg i)).is_some, from option.is_some_iff_exists.2 ⟨i, basis_basisg _ _⟩, have hig : i = option.get hi, { rw [← option.some_inj, option.some_get, basis_basisg] }, exact this (B.basisg i) ⟨(option.is_some_iff_exists.2 ⟨i, basis_basisg _ _⟩), begin rw [← hig], clear_aux_decl, refine ⟨by simpa using hip, _⟩, assume j hj, refine min_le_of_mem (mem_image.2 ⟨j, _⟩) hq, simp [hj] end⟩ end lemma is_unbounded_of_choose_pivot_row_eq_none (B : prebasis m n) (A_bar : matrix (fin m) (fin n) ℚ) (b_bar : cvec m) (c : rvec n) (s : fin (n - m)) (hA_bar : A_bar ⬝ B.basis.to_matrixᵀ = 1) (h0b : 0 ≤ b_bar) (hs : 0 < reduced_cost B A_bar c ⬝ (single s (0 : fin 1)).to_matrix) (hn : choose_pivot_row B A_bar b_bar c s = none) : is_unbounded A_bar b_bar c := is_unbounded_of_pivot_element_nonpos _ _ hA_bar h0b hs (λ _, choose_pivot_row_eq_none _ _ _ _ _ _ hn) lemma is_unbounded_swap {B : prebasis m n} {A_bar : matrix (fin m) (fin n) ℚ} {b_bar : cvec m} {c : rvec n} {r : fin m} {s : fin (n - m)} (hA_bar : A_bar ⬝ B.basis.to_matrixᵀ = 1) (hpivot : pivot_element B A_bar r s ≠ 0) : is_unbounded (swap_inverse B A_bar r s ⬝ A_bar) (swap_inverse B A_bar r s ⬝ b_bar) c → is_unbounded A_bar b_bar c := by simp only [is_unbounded, matrix.mul_assoc, matrix.mul_left_inj (has_left_inverse_swap_inverse hA_bar hpivot), imp_self] lemma is_optimal_basis_swap {B : prebasis m n} {A_bar : matrix (fin m) (fin n) ℚ} {b_bar : cvec m} {c : rvec n} (S : matrix (fin m) (fin m) ℚ) (hS : S.has_left_inverse) (h : is_optimal_basis B (S ⬝ A_bar) (S ⬝ b_bar) c) : is_optimal_basis B A_bar b_bar c := begin rw [is_optimal_basis, matrix.mul_assoc, ← has_left_inverse_mul hS] at h, simp only [is_optimal_basis, is_optimal, matrix.mul_assoc, matrix.mul_left_inj hS, h.1, inverse_one, matrix.one_mul, matrix.mul_one, matrix.mul_left_inj (inverse_has_left_inverse (has_right_inverse_iff_has_left_inverse.2 hS)), inverse_mul hS, inverse_one, mul_right_eq_of_mul_eq (inverse_mul hS), matrix.one_mul, matrix.mul_one, mul_inverse_rev hS h.1, *] at *, tauto, end axiom wf (p : Prop) : p def simplex : Π (B : prebasis m n) (A_bar : matrix (fin m) (fin n) ℚ) (b_bar : cvec m) (c : rvec n) (hA_bar : A_bar ⬝ B.basis.to_matrixᵀ = 1) (h0b : 0 ≤ b_bar), { o : option (Σ (B : prebasis m n) (A_bar : matrix (fin m) (fin n) ℚ), cvec m) // option.cases_on o (is_unbounded A_bar b_bar c) (λ P, is_optimal_basis P.1 A_bar b_bar c) } | B A_bar b_bar c hA_bar h0b := match choose_pivot_column B A_bar b_bar c, (λ s, choose_pivot_column_spec B A_bar b_bar c s hA_bar h0b), choose_pivot_column_eq_none B A_bar b_bar c hA_bar h0b with | none, _, hn := ⟨some ⟨B, A_bar, b_bar⟩, hn rfl⟩ | some s, hs, _ := match choose_pivot_row B A_bar b_bar c s, (λ r, choose_pivot_row_spec B A_bar b_bar c r s), is_unbounded_of_choose_pivot_row_eq_none B A_bar b_bar c s hA_bar h0b (hs _ rfl) with | none, _, hnone := ⟨none, hnone rfl⟩ | (some r), hr, _ := let S := swap_inverse B A_bar r s in have wf : prebasis.sizeof m n (swap B r s) < prebasis.sizeof m n B, from wf _, let o := simplex (B.swap r s) (S ⬝ A_bar) (S ⬝ b_bar) c (by rw [matrix.mul_assoc, swap_mul_swap_inverse hA_bar (ne_of_lt (hr r rfl).1).symm]) (swap_inverse_mul_nonneg b_bar hA_bar (hr _ rfl).1 h0b (hr _ rfl).2) in ⟨o.1, option.cases_on o.1 (is_unbounded_swap hA_bar (ne_of_lt (hr r rfl).1).symm) (λ P, is_optimal_basis_swap S (has_left_inverse_swap_inverse hA_bar (ne_of_lt (hr r rfl).1).symm)) o.2⟩ end end #print axioms simplex.simplex def rel (A : matrix (fin m) (fin n) ℚ) (b : cvec m) (c : rvec n) : prebasis m n → prebasis m n → Prop := tc (λ B C, ∃ hs : (choose_pivot_column B (inverse (A ⬝ B.basis.to_matrixᵀ) ⬝ A) (inverse (A ⬝ B.basis.to_matrixᵀ) ⬝ b) c).is_some, ∃ hr : (choose_pivot_row B (inverse (A ⬝ B.basis.to_matrixᵀ) ⬝ A) (inverse (A ⬝ B.basis.to_matrixᵀ) ⬝ b) c (option.get hs)).is_some, C = B.swap (option.get hr) (option.get hs)) #eval inverse (list.to_matrix 3 3 [[1,2,3],[0,1,5],[0,0,1]]) -- def ex.A := list.to_matrix 2 5 [[1,1,0,1,0], -- [0,1,-1,0,1]] -- def ex.b : cvec 2 := (λ i _, (list.nth_le [8,0] i sorry)) -- def ex.c : rvec 5 := λ _ i, (list.nth_le [1, 1, 1, 0, 0] i sorry) -- def ex.B : prebasis 2 5 := -- ⟨pequiv_of_vector ⟨[3, 4], rfl⟩ dec_trivial, -- pre_nonbasis_of_vector ⟨[3, 4], rfl⟩ dec_trivial, sorry, sorry, sorry⟩ -- #eval ex.A ⬝ ex.B.basis.to_matrixᵀ -- #eval (simplex ex.B ex.A ex.b ex.c dec_trivial dec_trivial).1.is_some def ex.A := list.to_matrix 3 7 [[1/4, - 8, - 1, 9, 1, 0, 0], [1/2, -12, -1/2, 3, 0, 1, 0], [ 0, 0, 1, 0, 0, 0, 1]] def ex.b : cvec 3 := (λ i _, list.nth_le [0,0,1] i sorry) --#eval ex.b def ex.c : rvec 7 := λ _ i, (list.nth_le [3/4, -20, 1/2, -6, 0, 0, 0] i sorry) --#eval ex.c def ex.B : prebasis 3 7 := ⟨pequiv_of_vector ⟨[4, 5, 6], rfl⟩ dec_trivial, pre_nonbasis_of_vector ⟨[4,5,6], rfl⟩ dec_trivial, sorry, sorry, sorry⟩ --#eval (simplex ex.B ex.A ex.b ex.c dec_trivial dec_trivial).1.is_some #eval (find_optimal_solution_from_starting_basis ex.A ex.c ex.b ex.B) --set_option trace.fun_info true #eval (is_optimal_bool ex.A ex.c ex.b ex.B) -- (some [[2064/445]]) -- (some [[6401/1895]]) #eval (is_feasible_basis ex.A ex.c ex.b ex.B : bool) -- #eval (show matrix _ _ ℚ, from minor ex.A id ex.B.read) * -- _root_.inverse (show matrix _ _ ℚ, from minor ex.A id ex.B.read ) -- #eval ((1 : cvec 1) - (minor ex.c id ex.B.read) ⬝ -- _root_.inverse (minor ex.A id ex.B.read) ⬝ -- (minor ex.A id ex.NB.read)) #eval finishing_basis ex.A ex.c ex.b ex.B #eval test ex.A ex.c ex.b ex.B #eval (let x : cvec 4 := λ i _, list.nth_le [0, 80/89, 62/89, 196/89] i sorry in let A := list.to_matrix 3 4 [[12, -1, 1, 1], [1, 1.45, 1, 0], [1, 2, 0, 1]] in A ⬝ x )
965bfd891a4dca6818ad456b29db53cbfefef4e8
6772a11d96d69b3f90d6eeaf7f9accddf2a7691d
/category.lean
777d66d107de17e4065fb1969552825d9614fc6f
[]
no_license
lbordowitz/lean-category-theory
5397361f0f81037d65762da48de2c16ec85a5e4b
8c59893e44af3804eba4dbc5f7fa5928ed2e0ae6
refs/heads/master
1,611,310,752,156
1,487,070,172,000
1,487,070,172,000
82,003,141
0
0
null
1,487,118,553,000
1,487,118,553,000
null
UTF-8
Lean
false
false
2,131
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 .tactics /- -- We've decided that Obj and Hom should be fields of Category, rather than parameters. -- Mostly this is for the sake of simpler signatures, but it's possible that it is not the right choice. -- Functor and NaturalTransformation are each parameterized by both their source and target. -/ namespace tqft.categories universe variables u v structure Category := (Obj : Type u) (Hom : Obj → Obj → Type v) (identity : Π X : Obj, Hom X X) (compose : Π { X Y Z : Obj }, Hom X Y → Hom Y Z → Hom X Z) (left_identity : ∀ { X Y : Obj } (f : Hom X Y), compose (identity _) f = f) (right_identity : ∀ { X Y : Obj } (f : Hom X Y), compose f (identity _) = f) (associativity : ∀ { W X Y Z : Obj } (f : Hom W X) (g : Hom X Y) (h : Hom Y Z), compose (compose f g) h = compose f (compose g h)) attribute [simp] Category.left_identity attribute [simp] Category.right_identity -- attribute [class] Category /- -- Unfortunately declaring Category as a class when it is first declared results -- in an unexpected type signature; this is a feature, not a bug, as Stephen discovered -- and explained at https://github.com/semorrison/proof/commit/e727197e794647d1148a1b8b920e7e567fb9079f -- -- We just declare things as structures, and then add the class attribute afterwards. -/ structure Isomorphism ( C: Category ) ( X Y : C^.Obj ) := (morphism : C^.Hom X Y) (inverse : C^.Hom Y X) (witness_1 : C^.compose morphism inverse = C^.identity X) (witness_2 : C^.compose inverse morphism = C^.identity Y) instance Isomorphism_coercion_to_morphism { C : Category } { X Y : C^.Obj } : has_coe (Isomorphism C X Y) (C^.Hom X Y) := { coe := Isomorphism.morphism } structure Inverse { C : Category } { X Y : C^.Obj } ( morphism : C^.Hom X Y ) := (inverse : C^.Hom Y X) (witness_1 : C^.compose morphism inverse = C^.identity X) (witness_2 : C^.compose inverse morphism = C^.identity Y) end tqft.categories
d1d3c7ecba1575bf2ac38fb7f442a079f66e214e
1a8c2c9f2b591362e78c4cafa31aa400c878b7e8
/library/init/meta/tactic.lean
1c3b7b7bd0ee8dd4147cba1c3f7248f10f5fc33a
[ "Apache-2.0" ]
permissive
jlpaca/lean-freebsd
ea88cd82635fe6eb0391ebb30e830a58be97cb1a
851cdaacf5d6caf50a42425b9246f427f0551866
refs/heads/master
1,613,685,045,763
1,590,309,513,000
1,590,309,513,000
245,241,297
0
0
null
null
null
null
UTF-8
Lean
false
false
70,841
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.function init.data.option.basic init.util import init.control.combinators init.control.monad init.control.alternative init.control.monad_fail import init.data.nat.div init.meta.exceptional init.meta.format init.meta.environment import init.meta.pexpr init.data.repr init.data.string.basic init.meta.interaction_monad open native meta constant tactic_state : Type universes u v namespace tactic_state meta constant env : tactic_state → environment /-- Format the given tactic state. If `target_lhs_only` is true and the target is of the form `lhs ~ rhs`, where `~` is a simplification relation, then only the `lhs` is displayed. Remark: the parameter `target_lhs_only` is a temporary hack used to implement the `conv` monad. It will be removed in the future. -/ meta constant to_format (s : tactic_state) (target_lhs_only : bool := ff) : format /-- Format expression with respect to the main goal in the tactic state. If the tactic state does not contain any goals, then format expression using an empty local context. -/ meta constant format_expr : tactic_state → expr → format meta constant get_options : tactic_state → options meta constant set_options : tactic_state → options → tactic_state end tactic_state meta instance : has_to_format tactic_state := ⟨tactic_state.to_format⟩ meta instance : has_to_string tactic_state := ⟨λ s, (to_fmt s).to_string s.get_options⟩ /-- `tactic` is the monad for building tactics. You use this to: - View and modify the local goals and hypotheses in the prover's state. - Invoke type checking and elaboration of terms. - View and modify the environment. - Build new tactics out of existing ones such as `simp` and `rewrite`. -/ @[reducible] meta def tactic := interaction_monad tactic_state @[reducible] meta def tactic_result := interaction_monad.result tactic_state namespace tactic export interaction_monad (hiding failed fail) /-- Cause the tactic to fail with no error message. -/ meta def failed {α : Type} : tactic α := interaction_monad.failed meta def fail {α : Type u} {β : Type v} [has_to_format β] (msg : β) : tactic α := interaction_monad.fail msg end tactic namespace tactic_result export interaction_monad.result end tactic_result open tactic open tactic_result infixl ` >>=[tactic] `:2 := interaction_monad_bind infixl ` >>[tactic] `:2 := interaction_monad_seq meta instance : alternative tactic := { failure := @interaction_monad.failed _, orelse := @interaction_monad_orelse _, ..interaction_monad.monad } meta def {u₁ u₂} tactic.up {α : Type u₂} (t : tactic α) : tactic (ulift.{u₁} α) := λ s, match t s with | success a s' := success (ulift.up a) s' | exception t ref s := exception t ref s end meta def {u₁ u₂} tactic.down {α : Type u₂} (t : tactic (ulift.{u₁} α)) : tactic α := λ s, match t s with | success (ulift.up a) s' := success a s' | exception t ref s := exception t ref s end namespace interactive /-- Typeclass for custom interaction monads, which provides the information required to convert an interactive-mode construction to a `tactic` which can actually be executed. Given a `[monad m]`, `execute_with` explains how to turn a `begin ... end` block, or a `by ...` statement into a `tactic α` which can actually be executed. The `inhabited` first argument facilitates the passing of an optional configuration parameter `config`, using the syntax: ``` begin [custom_monad] with config, ... end ``` -/ meta class executor (m : Type → Type u) [monad m] := (config_type : Type) [inhabited : inhabited config_type] (execute_with : config_type → m unit → tactic unit) attribute [inline] executor.execute_with @[inline] meta def executor.execute_explicit (m : Type → Type u) [monad m] [e : executor m] : m unit → tactic unit := executor.execute_with e.inhabited.default @[inline] meta def executor.execute_with_explicit (m : Type → Type u) [monad m] [executor m] : executor.config_type m → m unit → tactic unit := executor.execute_with /-- Default `executor` instance for `tactic`s themselves -/ meta instance : executor tactic := { config_type := unit, inhabited := ⟨()⟩, execute_with := λ _, id } end interactive namespace tactic open interaction_monad.result variables {α : Type u} /-- Does nothing. -/ meta def skip : tactic unit := success () /-- `try_core t` acts like `t`, but succeeds even if `t` fails. It returns the result of `t` if `t` succeeded and `none` otherwise. -/ meta def try_core (t : tactic α) : tactic (option α) := λ s, match t s with | (exception _ _ _) := success none s | (success a s') := success (some a) s' end /-- `try t` acts like `t`, but succeeds even if `t` fails. -/ meta def try (t : tactic α) : tactic unit := λ s, match t s with | (exception _ _ _) := success () s | (success _ s') := success () s' end meta def try_lst : list (tactic unit) → tactic unit | [] := failed | (tac :: tacs) := λ s, match tac s with | success _ s' := try (try_lst tacs) s' | exception e p s' := match try_lst tacs s' with | exception _ _ _ := exception e p s' | r := r end end /-- `fail_if_success t` acts like `t`, but succeeds if `t` fails and fails if `t` succeeds. Changes made by `t` to the `tactic_state` are preserved only if `t` succeeds. -/ meta def fail_if_success {α : Type u} (t : tactic α) : tactic unit := λ s, match (t s) with | (success a s) := mk_exception "fail_if_success combinator failed, given tactic succeeded" none s | (exception _ _ _) := success () s end /-- `success_if_fail t` acts like `t`, but succeeds if `t` fails and fails if `t` succeeds. Changes made by `t` to the `tactic_state` are preserved only if `t` succeeds. -/ meta def success_if_fail {α : Type u} (t : tactic α) : tactic unit := λ s, match t s with | (success a s) := mk_exception "success_if_fail combinator failed, given tactic succeeded" none s | (exception _ _ _) := success () s end open nat /-- `iterate_at_most n t` iterates `t` `n` times or until `t` fails, returning the result of each successful iteration. -/ meta def iterate_at_most : nat → tactic α → tactic (list α) | 0 t := pure [] | (n + 1) t := do (some a) ← try_core t | pure [], as ← iterate_at_most n t, pure $ a :: as /-- `iterate_at_most' n t` repeats `t` `n` times or until `t` fails. -/ meta def iterate_at_most' : nat → tactic unit → tactic unit | 0 t := skip | (succ n) t := do (some _) ← try_core t | skip, iterate_at_most' n t /-- `iterate_exactly n t` iterates `t` `n` times, returning the result of each iteration. If any iteration fails, the whole tactic fails. -/ meta def iterate_exactly : nat → tactic α → tactic (list α) | 0 t := pure [] | (n + 1) t := do a ← t, as ← iterate_exactly n t, pure $ a ::as /-- `iterate_exactly' n t` executes `t` `n` times. If any iteration fails, the whole tactic fails. -/ meta def iterate_exactly' : nat → tactic unit → tactic unit | 0 t := skip | (n + 1) t := t *> iterate_exactly' n t /-- `iterate t` repeats `t` 100.000 times or until `t` fails, returning the result of each iteration. -/ meta def iterate : tactic α → tactic (list α) := iterate_at_most 100000 /-- `iterate' t` repeats `t` 100.000 times or until `t` fails. -/ meta def iterate' : tactic unit → tactic unit := iterate_at_most' 100000 meta def returnopt (e : option α) : tactic α := λ s, match e with | (some a) := success a s | none := mk_exception "failed" none s end meta instance opt_to_tac : has_coe (option α) (tactic α) := ⟨returnopt⟩ /-- Decorate t's exceptions with msg. -/ meta def decorate_ex (msg : format) (t : tactic α) : tactic α := λ s, result.cases_on (t s) success (λ opt_thunk, match opt_thunk with | some e := exception (some (λ u, msg ++ format.nest 2 (format.line ++ e u))) | none := exception none end) /-- Set the tactic_state. -/ @[inline] meta def write (s' : tactic_state) : tactic unit := λ s, success () s' /-- Get the tactic_state. -/ @[inline] meta def read : tactic tactic_state := λ s, success s s meta def get_options : tactic options := do s ← read, return s.get_options meta def set_options (o : options) : tactic unit := do s ← read, write (s.set_options o) meta def save_options {α : Type} (t : tactic α) : tactic α := do o ← get_options, a ← t, set_options o, return a meta def returnex {α : Type} (e : exceptional α) : tactic α := λ s, match e with | exceptional.success a := success a s | exceptional.exception f := match get_options s with | success opt _ := exception (some (λ u, f opt)) none s | exception _ _ _ := exception (some (λ u, f options.mk)) none s end end meta instance ex_to_tac {α : Type} : has_coe (exceptional α) (tactic α) := ⟨returnex⟩ end tactic meta def tactic_format_expr (e : expr) : tactic format := do s ← tactic.read, return (tactic_state.format_expr s e) meta class has_to_tactic_format (α : Type u) := (to_tactic_format : α → tactic format) meta instance : has_to_tactic_format expr := ⟨tactic_format_expr⟩ meta def tactic.pp {α : Type u} [has_to_tactic_format α] : α → tactic format := has_to_tactic_format.to_tactic_format open tactic format meta instance {α : Type u} [has_to_tactic_format α] : has_to_tactic_format (list α) := ⟨λ l, to_fmt <$> l.mmap pp⟩ meta instance (α : Type u) (β : Type v) [has_to_tactic_format α] [has_to_tactic_format β] : has_to_tactic_format (α × β) := ⟨λ ⟨a, b⟩, to_fmt <$> (prod.mk <$> pp a <*> pp b)⟩ meta def option_to_tactic_format {α : Type u} [has_to_tactic_format α] : option α → tactic format | (some a) := do fa ← pp a, return (to_fmt "(some " ++ fa ++ ")") | none := return "none" meta instance {α : Type u} [has_to_tactic_format α] : has_to_tactic_format (option α) := ⟨option_to_tactic_format⟩ meta instance {α} (a : α) : has_to_tactic_format (reflected a) := ⟨λ h, pp h.to_expr⟩ @[priority 10] meta instance has_to_format_to_has_to_tactic_format (α : Type) [has_to_format α] : has_to_tactic_format α := ⟨(λ x, return x) ∘ to_fmt⟩ namespace tactic open tactic_state meta def get_env : tactic environment := do s ← read, return $ env s meta def get_decl (n : name) : tactic declaration := do s ← read, (env s).get n meta def trace {α : Type u} [has_to_tactic_format α] (a : α) : tactic unit := do fmt ← pp a, return $ _root_.trace_fmt fmt (λ u, ()) meta def trace_call_stack : tactic unit := assume state, _root_.trace_call_stack (success () state) meta def timetac {α : Type u} (desc : string) (t : thunk (tactic α)) : tactic α := λ s, timeit desc (t () s) meta def trace_state : tactic unit := do s ← read, trace $ to_fmt s /-- A parameter representing how aggressively definitions should be unfolded when trying to decide if two terms match, unify or are definitionally equal. By default, theorem declarations are never unfolded. - `all` will unfold everything, including macros and theorems. Except projection macros. - `semireducible` will unfold everything except theorems and definitions tagged as irreducible. - `instances` will unfold all class instance definitions and definitions tagged with reducible. - `reducible` will only unfold definitions tagged with the `reducible` attribute. - `none` will never unfold anything. [NOTE] You are not allowed to tag a definition with more than one of `reducible`, `irreducible`, `semireducible` attributes. [NOTE] there is a config flag `m_unfold_lemmas`that will make it unfold theorems. -/ inductive transparency | all | semireducible | instances | reducible | none export transparency (reducible semireducible) /-- (eval_expr α e) evaluates 'e' IF 'e' has type 'α'. -/ meta constant eval_expr (α : Type u) [reflected α] : expr → tactic α /-- Return the partial term/proof constructed so far. Note that the resultant expression may contain variables that are not declarate in the current main goal. -/ meta constant result : tactic expr /-- Display the partial term/proof constructed so far. This tactic is *not* equivalent to `do { r ← result, s ← read, return (format_expr s r) }` because this one will format the result with respect to the current goal, and trace_result will do it with respect to the initial goal. -/ meta constant format_result : tactic format /-- Return target type of the main goal. Fail if tactic_state does not have any goal left. -/ meta constant target : tactic expr meta constant intro_core : name → tactic expr meta constant intron : nat → tactic unit /-- Clear the given local constant. The tactic fails if the given expression is not a local constant. -/ meta constant clear : expr → tactic unit /-- `revert_lst : list expr → tactic nat` is the reverse of `intron`. It takes a local constant `c` and puts it back as bound by a `pi` or `elet` of the main target. If there are other local constants that depend on `c`, these are also reverted. Because of this, the `nat` that is returned is the actual number of reverted local constants. Example: with `x : ℕ, h : P(x) ⊢ T(x)`, `revert_lst [x]` returns `2` and produces the state ` ⊢ Π x, P(x) → T(x)`. -/ meta constant revert_lst : list expr → tactic nat /-- Return `e` in weak head normal form with respect to the given transparency setting. If `unfold_ginductive` is `tt`, then nested and/or mutually recursive inductive datatype constructors and types are unfolded. Recall that nested and mutually recursive inductive datatype declarations are compiled into primitive datatypes accepted by the Kernel. -/ meta constant whnf (e : expr) (md := semireducible) (unfold_ginductive := tt) : tactic expr /-- (head) eta expand the given expression. `f : α → β` head-eta-expands to `λ a, f a`. If `f` isn't a function then it just returns `f`. -/ meta constant head_eta_expand : expr → tactic expr /-- (head) beta reduction. `(λ x, B) c` reduces to `B[x/c]`. -/ meta constant head_beta : expr → tactic expr /-- (head) zeta reduction. Reduction of let bindings at the head of the expression. `let x : a := b in c` reduces to `c[x/b]`. -/ meta constant head_zeta : expr → tactic expr /-- Zeta reduction. Reduction of let bindings. `let x : a := b in c` reduces to `c[x/b]`. -/ meta constant zeta : expr → tactic expr /-- (head) eta reduction. `(λ x, f x)` reduces to `f`. -/ meta constant head_eta : expr → tactic expr /-- Succeeds if `t` and `s` can be unified using the given transparency setting. -/ meta constant unify (t s : expr) (md := semireducible) (approx := ff) : tactic unit /-- Similar to `unify`, but it treats metavariables as constants. -/ meta constant is_def_eq (t s : expr) (md := semireducible) (approx := ff) : tactic unit /-- Infer the type of the given expression. Remark: transparency does not affect type inference -/ meta constant infer_type : expr → tactic expr /-- Get the `local_const` expr for the given `name`. -/ meta constant get_local : name → tactic expr /-- Resolve a name using the current local context, environment, aliases, etc. -/ meta constant resolve_name : name → tactic pexpr /-- Return the hypothesis in the main goal. Fail if tactic_state does not have any goal left. -/ meta constant local_context : tactic (list expr) /-- Get a fresh name that is guaranteed to not be in use in the local context. If `n` is provided and `n` is not in use, then `n` is returned. Otherwise a number `i` is appended to give `"n_i"`. -/ meta constant get_unused_name (n : name := `_x) (i : option nat := none) : tactic name /-- Helper tactic for creating simple applications where some arguments are inferred using type inference. Example, given ``` rel.{l_1 l_2} : Pi (α : Type.{l_1}) (β : α -> Type.{l_2}), (Pi x : α, β x) -> (Pi x : α, β x) -> , Prop nat : Type real : Type vec.{l} : Pi (α : Type l) (n : nat), Type.{l1} f g : Pi (n : nat), vec real n ``` then ``` mk_app_core semireducible "rel" [f, g] ``` returns the application ``` rel.{1 2} nat (fun n : nat, vec real n) f g ``` The unification constraints due to type inference are solved using the transparency `md`. -/ meta constant mk_app (fn : name) (args : list expr) (md := semireducible) : tactic expr /-- Similar to `mk_app`, but allows to specify which arguments are explicit/implicit. Example, given `(a b : nat)` then ``` mk_mapp "ite" [some (a > b), none, none, some a, some b] ``` returns the application ``` @ite.{1} (a > b) (nat.decidable_gt a b) nat a b ``` -/ meta constant mk_mapp (fn : name) (args : list (option expr)) (md := semireducible) : tactic expr /-- (mk_congr_arg h₁ h₂) is a more efficient version of (mk_app `congr_arg [h₁, h₂]) -/ meta constant mk_congr_arg : expr → expr → tactic expr /-- (mk_congr_fun h₁ h₂) is a more efficient version of (mk_app `congr_fun [h₁, h₂]) -/ meta constant mk_congr_fun : expr → expr → tactic expr /-- (mk_congr h₁ h₂) is a more efficient version of (mk_app `congr [h₁, h₂]) -/ meta constant mk_congr : expr → expr → tactic expr /-- (mk_eq_refl h) is a more efficient version of (mk_app `eq.refl [h]) -/ meta constant mk_eq_refl : expr → tactic expr /-- (mk_eq_symm h) is a more efficient version of (mk_app `eq.symm [h]) -/ meta constant mk_eq_symm : expr → tactic expr /-- (mk_eq_trans h₁ h₂) is a more efficient version of (mk_app `eq.trans [h₁, h₂]) -/ meta constant mk_eq_trans : expr → expr → tactic expr /-- (mk_eq_mp h₁ h₂) is a more efficient version of (mk_app `eq.mp [h₁, h₂]) -/ meta constant mk_eq_mp : expr → expr → tactic expr /-- (mk_eq_mpr h₁ h₂) is a more efficient version of (mk_app `eq.mpr [h₁, h₂]) -/ meta constant mk_eq_mpr : expr → expr → tactic expr /- Given a local constant t, if t has type (lhs = rhs) apply substitution. Otherwise, try to find a local constant that has type of the form (t = t') or (t' = t). The tactic fails if the given expression is not a local constant. -/ meta constant subst_core : expr → tactic unit /-- Close the current goal using `e`. Fail is the type of `e` is not definitionally equal to the target type. -/ meta constant exact (e : expr) (md := semireducible) : tactic unit /-- Elaborate the given quoted expression with respect to the current main goal. Note that this means that any implicit arguments for the given `pexpr` will be applied with fresh metavariables. If `allow_mvars` is tt, then metavariables are tolerated and become new goals if `subgoals` is tt. -/ meta constant to_expr (q : pexpr) (allow_mvars := tt) (subgoals := tt) : tactic expr /-- Return true if the given expression is a type class. -/ meta constant is_class : expr → tactic bool /-- Try to create an instance of the given type class. -/ meta constant mk_instance : expr → tactic expr /-- Change the target of the main goal. The input expression must be definitionally equal to the current target. If `check` is `ff`, then the tactic does not check whether `e` is definitionally equal to the current target. If it is not, then the error will only be detected by the kernel type checker. -/ meta constant change (e : expr) (check : bool := tt): tactic unit /-- `assert_core H T`, adds a new goal for T, and change target to `T -> target`. -/ meta constant assert_core : name → expr → tactic unit /-- `assertv_core H T P`, change target to (T -> target) if P has type T. -/ meta constant assertv_core : name → expr → expr → tactic unit /-- `define_core H T`, adds a new goal for T, and change target to `let H : T := ?M in target` in the current goal. -/ meta constant define_core : name → expr → tactic unit /-- `definev_core H T P`, change target to `let H : T := P in target` if P has type T. -/ meta constant definev_core : name → expr → expr → tactic unit /-- Rotate goals to the left. That is, `rotate_left 1` takes the main goal and puts it to the back of the subgoal list. -/ meta constant rotate_left : nat → tactic unit /-- Gets a list of metavariables, one for each goal. -/ meta constant get_goals : tactic (list expr) /-- Replace the current list of goals with the given one. Each expr in the list should be a metavariable. Any assigned metavariables will be ignored.-/ meta constant set_goals : list expr → tactic unit /-- How to order the new goals made from an `apply` tactic. Supposing we were applying `e : ∀ (a:α) (p : P(a)), Q` - `non_dep_first` would produce goals `⊢ P(?m)`, `⊢ α`. It puts the P goal at the front because none of the arguments after `p` in `e` depend on `p`. It doesn't matter what the result `Q` depends on. - `non_dep_only` would produce goal `⊢ P(?m)`. - `all` would produce goals `⊢ α`, `⊢ P(?m)`. -/ inductive new_goals | non_dep_first | non_dep_only | all /-- Configuration options for the `apply` tactic. - `md` sets how aggressively definitions are unfolded. - `new_goals` is the strategy for ordering new goals. - `instances` if `tt`, then `apply` tries to synthesize unresolved `[...]` arguments using type class resolution. - `auto_param` if `tt`, then `apply` tries to synthesize unresolved `(h : p . tac_id)` arguments using tactic `tac_id`. - `opt_param` if `tt`, then `apply` tries to synthesize unresolved `(a : t := v)` arguments by setting them to `v`. - `unify` if `tt`, then `apply` is free to assign existing metavariables in the goal when solving unification constraints. For example, in the goal `|- ?x < succ 0`, the tactic `apply succ_lt_succ` succeeds with the default configuration, but `apply_with succ_lt_succ {unify := ff}` doesn't since it would require Lean to assign `?x` to `succ ?y` where `?y` is a fresh metavariable. -/ structure apply_cfg := (md := semireducible) (approx := tt) (new_goals := new_goals.non_dep_first) (instances := tt) (auto_param := tt) (opt_param := tt) (unify := tt) /-- Apply the expression `e` to the main goal, the unification is performed using the transparency mode in `cfg`. Supposing `e : Π (a₁:α₁) ... (aₙ:αₙ), P(a₁,...,aₙ)` and the target is `Q`, `apply` will attempt to unify `Q` with `P(?a₁,...?aₙ)`. All of the metavariables that are not assigned are added as new metavariables. If `cfg.approx` is `tt`, then fallback to first-order unification, and approximate context during unification. `cfg.new_goals` specifies which unassigned metavariables become new goals, and their order. If `cfg.instances` is `tt`, then use type class resolution to instantiate unassigned meta-variables. The fields `cfg.auto_param` and `cfg.opt_param` are ignored by this tactic (See `tactic.apply`). It returns a list of all introduced meta variables and the parameter name associated with them, even the assigned ones. -/ meta constant apply_core (e : expr) (cfg : apply_cfg := {}) : tactic (list (name × expr)) /- Create a fresh meta universe variable. -/ meta constant mk_meta_univ : tactic level /- Create a fresh meta-variable with the given type. The scope of the new meta-variable is the local context of the main goal. -/ meta constant mk_meta_var : expr → tactic expr /-- Return the value assigned to the given universe meta-variable. Fail if argument is not an universe meta-variable or if it is not assigned. -/ meta constant get_univ_assignment : level → tactic level /-- Return the value assigned to the given meta-variable. Fail if argument is not a meta-variable or if it is not assigned. -/ meta constant get_assignment : expr → tactic expr /-- Return true if the given meta-variable is assigned. Fail if argument is not a meta-variable. -/ meta constant is_assigned : expr → tactic bool /-- Make a name that is guaranteed to be unique. Eg `_fresh.1001.4667`. These will be different for each run of the tactic. -/ meta constant mk_fresh_name : tactic name /-- Induction on `h` using recursor `rec`, names for the new hypotheses are retrieved from `ns`. If `ns` does not have sufficient names, then use the internal binder names in the recursor. It returns for each new goal the name of the constructor (if `rec_name` is a builtin recursor), a list of new hypotheses, and a list of substitutions for hypotheses depending on `h`. The substitutions map internal names to their replacement terms. If the replacement is again a hypothesis the user name stays the same. The internal names are only valid in the original goal, not in the type context of the new goal. Remark: if `rec_name` is not a builtin recursor, we use parameter names of `rec_name` instead of constructor names. If `rec` is none, then the type of `h` is inferred, if it is of the form `C ...`, tactic uses `C.rec` -/ meta constant induction (h : expr) (ns : list name := []) (rec : option name := none) (md := semireducible) : tactic (list (name × list expr × list (name × expr))) /-- Apply `cases_on` recursor, names for the new hypotheses are retrieved from `ns`. `h` must be a local constant. It returns for each new goal the name of the constructor, a list of new hypotheses, and a list of substitutions for hypotheses depending on `h`. The number of new goals may be smaller than the number of constructors. Some goals may be discarded when the indices to not match. See `induction` for information on the list of substitutions. The `cases` tactic is implemented using this one, and it relaxes the restriction of `h`. -/ meta constant cases_core (h : expr) (ns : list name := []) (md := semireducible) : tactic (list (name × list expr × list (name × expr))) /-- Similar to cases tactic, but does not revert/intro/clear hypotheses. -/ meta constant destruct (e : expr) (md := semireducible) : tactic unit /-- Generalizes the target with respect to `e`. -/ meta constant generalize (e : expr) (n : name := `_x) (md := semireducible) : tactic unit /-- instantiate assigned metavariables in the given expression -/ meta constant instantiate_mvars : expr → tactic expr /-- Add the given declaration to the environment -/ meta constant add_decl : declaration → tactic unit /-- Changes the environment to the `new_env`. The new environment does not need to be a descendant of the old one. Use with care. -/ meta constant set_env_core : environment → tactic unit /-- Changes the environment to the `new_env`. `new_env` needs to be a descendant from the current environment. -/ meta constant set_env : environment → tactic unit /-- `doc_string env d k` returns the doc string for `d` (if available) -/ meta constant doc_string : name → tactic string /-- Set the docstring for the given declaration. -/ meta constant add_doc_string : name → string → tactic unit /-- Create an auxiliary definition with name `c` where `type` and `value` may contain local constants and meta-variables. This function collects all dependencies (universe parameters, universe metavariables, local constants (aka hypotheses) and metavariables). It updates the environment in the tactic_state, and returns an expression of the form (c.{l_1 ... l_n} a_1 ... a_m) where l_i's and a_j's are the collected dependencies. -/ meta constant add_aux_decl (c : name) (type : expr) (val : expr) (is_lemma : bool) : tactic expr /-- Returns a list of all top-level (`/-! ... -/`) docstrings in the active module and imported ones. The returned object is a list of modules, indexed by `(some filename)` for imported modules and `none` for the active one, where each module in the list is paired with a list of `(position_in_file, docstring)` pairs. -/ meta constant olean_doc_strings : tactic (list (option string × (list (pos × string)))) /-- Returns a list of docstrings in the active module. An entry in the list can be either: - a top-level (`/-! ... -/`) docstring, represented as `(none, docstring)` - a declaration-specific (`/-- ... -/`) docstring, represented as `(some decl_name, docstring)` -/ meta def module_doc_strings : tactic (list (option name × string)) := do /- Obtain a list of top-level docs in current module. -/ mod_docs ← olean_doc_strings, let mod_docs: list (list (option name × string)) := mod_docs.filter_map (λ d, if d.1.is_none then some (d.2.map (λ pos_doc, ⟨none, pos_doc.2⟩)) else none), let mod_docs := mod_docs.join, /- Obtain list of declarations in current module. -/ e ← get_env, let decls := environment.fold e ([]: list name) (λ d acc, let n := d.to_name in if (environment.decl_olean e n).is_none then n::acc else acc), /- Map declarations to those which have docstrings. -/ decls ← decls.mfoldl (λa n, (doc_string n >>= λ doc, pure $ (some n, doc) :: a) <|> pure a) [], pure (mod_docs ++ decls) /-- Set attribute `attr_name` for constant `c_name` with the given priority. If the priority is none, then use default -/ meta constant set_basic_attribute (attr_name : name) (c_name : name) (persistent := ff) (prio : option nat := none) : tactic unit /-- `unset_attribute attr_name c_name` -/ meta constant unset_attribute : name → name → tactic unit /-- `has_attribute attr_name c_name` succeeds if the declaration `decl_name` has the attribute `attr_name`. The result is the priority and whether or not the attribute is persistent. -/ meta constant has_attribute : name → name → tactic (bool × nat) /-- `copy_attribute attr_name c_name p d_name` copy attribute `attr_name` from `src` to `tgt` if it is defined for `src`; make it persistent if `p` is `tt`; if `p` is `none`, the copied attribute is made persistent iff it is persistent on `src` -/ meta def copy_attribute (attr_name : name) (src : name) (tgt : name) (p : option bool := none) : tactic unit := try $ do (p', prio) ← has_attribute attr_name src, let p := p.get_or_else p', set_basic_attribute attr_name tgt p (some prio) /-- Name of the declaration currently being elaborated. -/ meta constant decl_name : tactic name /-- `save_type_info e ref` save (typeof e) at position associated with ref -/ meta constant save_type_info {elab : bool} : expr → expr elab → tactic unit meta constant save_info_thunk : pos → (unit → format) → tactic unit /-- Return list of currently open namespaces -/ meta constant open_namespaces : tactic (list name) /-- Return tt iff `t` "occurs" in `e`. The occurrence checking is performed using keyed matching with the given transparency setting. We say `t` occurs in `e` by keyed matching iff there is a subterm `s` s.t. `t` and `s` have the same head, and `is_def_eq t s md` The main idea is to minimize the number of `is_def_eq` checks performed. -/ meta constant kdepends_on (e t : expr) (md := reducible) : tactic bool /-- Abstracts all occurrences of the term `t` in `e` using keyed matching. If `unify` is `ff`, then matching is used instead of unification. That is, metavariables occurring in `e` are not assigned. -/ meta constant kabstract (e t : expr) (md := reducible) (unify := tt) : tactic expr /-- Blocks the execution of the current thread for at least `msecs` milliseconds. This tactic is used mainly for debugging purposes. -/ meta constant sleep (msecs : nat) : tactic unit /-- Type check `e` with respect to the current goal. Fails if `e` is not type correct. -/ meta constant type_check (e : expr) (md := semireducible) : tactic unit open list nat /-- A `tag` is a list of `names`. These are attached to goals to help tactics track them.-/ def tag : Type := list name /-- Enable/disable goal tagging. -/ meta constant enable_tags (b : bool) : tactic unit /-- Return tt iff goal tagging is enabled. -/ meta constant tags_enabled : tactic bool /-- Tag goal `g` with tag `t`. It does nothing if goal tagging is disabled. Remark: `set_goal g []` removes the tag -/ meta constant set_tag (g : expr) (t : tag) : tactic unit /-- Return tag associated with `g`. Return `[]` if there is no tag. -/ meta constant get_tag (g : expr) : tactic tag /-- By default, Lean only considers local instances in the header of declarations. This has two main benefits. 1- Results produced by the type class resolution procedure can be easily cached. 2- The set of local instances does not have to be recomputed. This approach has the following disadvantages: 1- Frozen local instances cannot be reverted. 2- Local instances defined inside of a declaration are not considered during type class resolution. This tactic resets the set of local instances. After executing this tactic, the set of local instances will be recomputed and the cache will be frequently reset. Note that, the cache is still used when executing a single tactic that may generate many type class resolution problems (e.g., `simp`). -/ meta constant unfreeze_local_instances : tactic unit /- Return the list of frozen local instances. Return `none` if local instances were not frozen. -/ meta constant frozen_local_instances : tactic (option (list expr)) meta def induction' (h : expr) (ns : list name := []) (rec : option name := none) (md := semireducible) : tactic unit := induction h ns rec md >> return () /-- Remark: set_goals will erase any solved goal -/ meta def cleanup : tactic unit := get_goals >>= set_goals /-- Auxiliary definition used to implement begin ... end blocks -/ meta def step {α : Type u} (t : tactic α) : tactic unit := t >>[tactic] cleanup meta def istep {α : Type u} (line0 col0 : ℕ) (line col : ℕ) (t : tactic α) : tactic unit := λ s, (@scope_trace _ line col (λ _, step t s)).clamp_pos line0 line col meta def is_prop (e : expr) : tactic bool := do t ← infer_type e, return (t = `(Prop)) /-- Return true iff n is the name of declaration that is a proposition. -/ meta def is_prop_decl (n : name) : tactic bool := do env ← get_env, d ← env.get n, t ← return $ d.type, is_prop t meta def is_proof (e : expr) : tactic bool := infer_type e >>= is_prop meta def whnf_no_delta (e : expr) : tactic expr := whnf e transparency.none /-- Return `e` in weak head normal form with respect to the given transparency setting, or `e` head is a generalized constructor or inductive datatype. -/ meta def whnf_ginductive (e : expr) (md := semireducible) : tactic expr := whnf e md ff meta def whnf_target : tactic unit := target >>= whnf >>= change /-- Change the target of the main goal. The input expression must be definitionally equal to the current target. The tactic does not check whether `e` is definitionally equal to the current target. The error will only be detected by the kernel type checker. -/ meta def unsafe_change (e : expr) : tactic unit := change e ff /-- Pi or elet introduction. Given the tactic state `⊢ Π x : α, Y`, ``intro `hello`` will produce the state `hello : α ⊢ Y[x/hello]`. Returns the new local constant. Similarly for `elet` expressions. If the target is not a Pi or elet it will try to put it in WHNF. -/ meta def intro (n : name) : tactic expr := do t ← target, if expr.is_pi t ∨ expr.is_let t then intro_core n else whnf_target >> intro_core n /-- Like `intro` except the name is derived from the bound name in the Π. -/ meta def intro1 : tactic expr := intro `_ /-- Repeatedly apply `intro1` and return the list of new local constants in order of introduction.-/ meta def intros : tactic (list expr) := do t ← target, match t with | expr.pi _ _ _ _ := do H ← intro1, Hs ← intros, return (H :: Hs) | expr.elet _ _ _ _ := do H ← intro1, Hs ← intros, return (H :: Hs) | _ := return [] end /-- Same as `intros`, except with the given names for the new hypotheses. Use the name ```_``` to instead use the binder's name.-/ meta def intro_lst : list name → tactic (list expr) | [] := return [] | (n::ns) := do H ← intro n, Hs ← intro_lst ns, return (H :: Hs) /-- Introduces new hypotheses with forward dependencies. -/ meta def intros_dep : tactic (list expr) := do t ← target, let proc (b : expr) := if b.has_var_idx 0 then do h ← intro1, hs ← intros_dep, return (h::hs) else -- body doesn't depend on new hypothesis return [], match t with | expr.pi _ _ _ b := proc b | expr.elet _ _ _ b := proc b | _ := return [] end meta def introv : list name → tactic (list expr) | [] := intros_dep | (n::ns) := do hs ← intros_dep, h ← intro n, hs' ← introv ns, return (hs ++ h :: hs') /-- `intron' n` introduces `n` hypotheses and returns the resulting local constants. Fails if there are not at least `n` arguments to introduce. If you do not need the return value, use `intron`. -/ meta def intron' : ℕ → tactic (list expr) | 0 := pure [] | (n + 1) := do h ← intro1, hs ← intron' n, pure $ h :: hs /-- Returns n fully qualified if it refers to a constant, or else fails. -/ meta def resolve_constant (n : name) : tactic name := do (expr.const n _) ← resolve_name n, pure n meta def to_expr_strict (q : pexpr) : tactic expr := to_expr q /-- Example: with `x : ℕ, h : P(x) ⊢ T(x)`, `revert x` returns `2` and produces the state ` ⊢ Π x, P(x) → T(x)`. -/ meta def revert (l : expr) : tactic nat := revert_lst [l] /- Revert "all" hypotheses. Actually, the tactic only reverts hypotheses occurring after the last frozen local instance. Recall that frozen local instances cannot be reverted. We can use `unfreeze_local_instances` to workaround this limitation. -/ meta def revert_all : tactic nat := do lctx ← local_context, lis ← frozen_local_instances, match lis with | none := revert_lst lctx | some [] := revert_lst lctx /- `hi` is the last local instance. We shoul truncate `lctx` at `hi`. -/ | some (hi::his) := revert_lst $ lctx.foldl (λ r h, if h.local_uniq_name = hi.local_uniq_name then [] else h :: r) [] end meta def clear_lst : list name → tactic unit | [] := skip | (n::ns) := do H ← get_local n, clear H, clear_lst ns meta def match_not (e : expr) : tactic expr := match (expr.is_not e) with | (some a) := return a | none := fail "expression is not a negation" end meta def match_and (e : expr) : tactic (expr × expr) := match (expr.is_and e) with | (some (α, β)) := return (α, β) | none := fail "expression is not a conjunction" end meta def match_or (e : expr) : tactic (expr × expr) := match (expr.is_or e) with | (some (α, β)) := return (α, β) | none := fail "expression is not a disjunction" end meta def match_iff (e : expr) : tactic (expr × expr) := match (expr.is_iff e) with | (some (lhs, rhs)) := return (lhs, rhs) | none := fail "expression is not an iff" end meta def match_eq (e : expr) : tactic (expr × expr) := match (expr.is_eq e) with | (some (lhs, rhs)) := return (lhs, rhs) | none := fail "expression is not an equality" end meta def match_ne (e : expr) : tactic (expr × expr) := match (expr.is_ne e) with | (some (lhs, rhs)) := return (lhs, rhs) | none := fail "expression is not a disequality" end meta def match_heq (e : expr) : tactic (expr × expr × expr × expr) := do match (expr.is_heq e) with | (some (α, lhs, β, rhs)) := return (α, lhs, β, rhs) | none := fail "expression is not a heterogeneous equality" end meta def match_refl_app (e : expr) : tactic (name × expr × expr) := do env ← get_env, match (environment.is_refl_app env e) with | (some (R, lhs, rhs)) := return (R, lhs, rhs) | none := fail "expression is not an application of a reflexive relation" end meta def match_app_of (e : expr) (n : name) : tactic (list expr) := guard (expr.is_app_of e n) >> return e.get_app_args meta def get_local_type (n : name) : tactic expr := get_local n >>= infer_type meta def trace_result : tactic unit := format_result >>= trace meta def rexact (e : expr) : tactic unit := exact e reducible meta def any_hyp_aux {α : Type} (f : expr → tactic α) : list expr → tactic α | [] := failed | (h :: hs) := f h <|> any_hyp_aux hs meta def any_hyp {α : Type} (f : expr → tactic α) : tactic α := local_context >>= any_hyp_aux f /-- `find_same_type t es` tries to find in es an expression with type definitionally equal to t -/ meta def find_same_type : expr → list expr → tactic expr | e [] := failed | e (H :: Hs) := do t ← infer_type H, (unify e t >> return H) <|> find_same_type e Hs meta def find_assumption (e : expr) : tactic expr := do ctx ← local_context, find_same_type e ctx meta def assumption : tactic unit := do { ctx ← local_context, t ← target, H ← find_same_type t ctx, exact H } <|> fail "assumption tactic failed" meta def save_info (p : pos) : tactic unit := do s ← read, tactic.save_info_thunk p (λ _, tactic_state.to_format s) notation `‹` p `›` := (by assumption : p) /-- Swap first two goals, do nothing if tactic state does not have at least two goals. -/ meta def swap : tactic unit := do gs ← get_goals, match gs with | (g₁ :: g₂ :: rs) := set_goals (g₂ :: g₁ :: rs) | e := skip end /-- `assert h t`, adds a new goal for t, and the hypothesis `h : t` in the current goal. -/ meta def assert (h : name) (t : expr) : tactic expr := do assert_core h t, swap, e ← intro h, swap, return e /-- `assertv h t v`, adds the hypothesis `h : t` in the current goal if v has type t. -/ meta def assertv (h : name) (t : expr) (v : expr) : tactic expr := assertv_core h t v >> intro h /-- `define h t`, adds a new goal for t, and the hypothesis `h : t := ?M` in the current goal. -/ meta def define (h : name) (t : expr) : tactic expr := do define_core h t, swap, e ← intro h, swap, return e /-- `definev h t v`, adds the hypothesis (h : t := v) in the current goal if v has type t. -/ meta def definev (h : name) (t : expr) (v : expr) : tactic expr := definev_core h t v >> intro h /-- Add `h : t := pr` to the current goal -/ meta def pose (h : name) (t : option expr := none) (pr : expr) : tactic expr := let dv := λt, definev h t pr in option.cases_on t (infer_type pr >>= dv) dv /-- Add `h : t` to the current goal, given a proof `pr : t` -/ meta def note (h : name) (t : option expr := none) (pr : expr) : tactic expr := let dv := λt, assertv h t pr in option.cases_on t (infer_type pr >>= dv) dv /-- Return the number of goals that need to be solved -/ meta def num_goals : tactic nat := do gs ← get_goals, return (length gs) /-- Rotate the goals to the right by `n`. That is, take the goal at the back and push it to the front `n` times. [NOTE] We have to provide the instance argument `[has_mod nat]` because mod for nat was not defined yet -/ meta def rotate_right (n : nat) [has_mod nat] : tactic unit := do ng ← num_goals, if ng = 0 then skip else rotate_left (ng - n % ng) /-- Rotate the goals to the left by `n`. That is, put the main goal to the back `n` times. -/ meta def rotate : nat → tactic unit := rotate_left private meta def repeat_aux (t : tactic unit) : list expr → list expr → tactic unit | [] r := set_goals r.reverse | (g::gs) r := do ok ← try_core (set_goals [g] >> t), match ok with | none := repeat_aux gs (g::r) | _ := do gs' ← get_goals, repeat_aux (gs' ++ gs) r end /-- This tactic is applied to each goal. If the application succeeds, the tactic is applied recursively to all the generated subgoals until it eventually fails. The recursion stops in a subgoal when the tactic has failed to make progress. The tactic `repeat` never fails. -/ meta def repeat (t : tactic unit) : tactic unit := do gs ← get_goals, repeat_aux t gs [] /-- `first [t_1, ..., t_n]` applies the first tactic that doesn't fail. The tactic fails if all t_i's fail. -/ meta def first {α : Type u} : list (tactic α) → tactic α | [] := fail "first tactic failed, no more alternatives" | (t::ts) := t <|> first ts /-- Applies the given tactic to the main goal and fails if it is not solved. -/ meta def solve1 {α} (tac : tactic α) : tactic α := do gs ← get_goals, match gs with | [] := fail "solve1 tactic failed, there isn't any goal left to focus" | (g::rs) := do set_goals [g], a ← tac, gs' ← get_goals, match gs' with | [] := set_goals rs >> pure a | gs := fail "solve1 tactic failed, focused goal has not been solved" end end /-- `solve [t_1, ... t_n]` applies the first tactic that solves the main goal. -/ meta def solve {α} (ts : list (tactic α)) : tactic α := first $ map solve1 ts private meta def focus_aux {α} : list (tactic α) → list expr → list expr → tactic (list α) | [] [] rs := set_goals rs *> pure [] | (t::ts) [] rs := fail "focus' tactic failed, insufficient number of goals" | tts (g::gs) rs := mcond (is_assigned g) (focus_aux tts gs rs) $ do set_goals [g], t::ts ← pure tts | fail "focus' tactic failed, insufficient number of tactics", a ← t, rs' ← get_goals, as ← focus_aux ts gs (rs ++ rs'), pure $ a :: as /-- `focus [t_1, ..., t_n]` applies t_i to the i-th goal. Fails if the number of goals is not n. Returns the results of t_i (one per goal). -/ meta def focus {α} (ts : list (tactic α)) : tactic (list α) := do gs ← get_goals, focus_aux ts gs [] private meta def focus'_aux : list (tactic unit) → list expr → list expr → tactic unit | [] [] rs := set_goals rs | (t::ts) [] rs := fail "focus tactic failed, insufficient number of goals" | tts (g::gs) rs := mcond (is_assigned g) (focus'_aux tts gs rs) $ do set_goals [g], t::ts ← pure tts | fail "focus tactic failed, insufficient number of tactics", t, rs' ← get_goals, focus'_aux ts gs (rs ++ rs') /-- `focus' [t_1, ..., t_n]` applies t_i to the i-th goal. Fails if the number of goals is not n. -/ meta def focus' (ts : list (tactic unit)) : tactic unit := do gs ← get_goals, focus'_aux ts gs [] meta def focus1 {α} (tac : tactic α) : tactic α := do g::gs ← get_goals, match gs with | [] := tac | _ := do set_goals [g], a ← tac, gs' ← get_goals, set_goals (gs' ++ gs), return a end private meta def all_goals_core {α} (tac : tactic α) : list expr → list expr → tactic (list α) | [] ac := set_goals ac *> pure [] | (g :: gs) ac := mcond (is_assigned g) (all_goals_core gs ac) $ do set_goals [g], a ← tac, new_gs ← get_goals, as ← all_goals_core gs (ac ++ new_gs), pure $ a :: as /-- Apply the given tactic to all goals. Return one result per goal. -/ meta def all_goals {α} (tac : tactic α) : tactic (list α) := do gs ← get_goals, all_goals_core tac gs [] private meta def all_goals'_core (tac : tactic unit) : list expr → list expr → tactic unit | [] ac := set_goals ac | (g :: gs) ac := mcond (is_assigned g) (all_goals'_core gs ac) $ do set_goals [g], tac, new_gs ← get_goals, all_goals'_core gs (ac ++ new_gs) /-- Apply the given tactic to all goals. -/ meta def all_goals' (tac : tactic unit) : tactic unit := do gs ← get_goals, all_goals'_core tac gs [] private meta def any_goals_core {α} (tac : tactic α) : list expr → list expr → bool → tactic (list (option α)) | [] ac progress := guard progress *> set_goals ac *> pure [] | (g :: gs) ac progress := mcond (is_assigned g) (any_goals_core gs ac progress) $ do set_goals [g], res ← try_core tac, new_gs ← get_goals, ress ← any_goals_core gs (ac ++ new_gs) (res.is_some || progress), pure $ res :: ress /-- Apply `tac` to any goal where it succeeds. The tactic succeeds if `tac` succeeds for at least one goal. The returned list contains the result of `tac` for each goal: `some a` if tac succeeded, or `none` if it did not. -/ meta def any_goals {α} (tac : tactic α) : tactic (list (option α)) := do gs ← get_goals, any_goals_core tac gs [] ff private meta def any_goals'_core (tac : tactic unit) : list expr → list expr → bool → tactic unit | [] ac progress := guard progress >> set_goals ac | (g :: gs) ac progress := mcond (is_assigned g) (any_goals'_core gs ac progress) $ do set_goals [g], succeeded ← try_core tac, new_gs ← get_goals, any_goals'_core gs (ac ++ new_gs) (succeeded.is_some || progress) /-- Apply the given tactic to any goal where it succeeds. The tactic succeeds only if tac succeeds for at least one goal. -/ meta def any_goals' (tac : tactic unit) : tactic unit := do gs ← get_goals, any_goals'_core tac gs [] ff /-- LCF-style AND_THEN tactic. It applies `tac1` to the main goal, then applies `tac2` to each goal produced by `tac1`. -/ meta def seq {α β} (tac1 : tactic α) (tac2 : α → tactic β) : tactic (list β) := do g::gs ← get_goals, set_goals [g], a ← tac1, bs ← all_goals $ tac2 a, gs' ← get_goals, set_goals (gs' ++ gs), pure bs /-- LCF-style AND_THEN tactic. It applies tac1, and if succeed applies tac2 to each subgoal produced by tac1 -/ meta def seq' (tac1 : tactic unit) (tac2 : tactic unit) : tactic unit := do g::gs ← get_goals, set_goals [g], tac1, all_goals' tac2, gs' ← get_goals, set_goals (gs' ++ gs) /-- Applies `tac1` to the main goal, then applies each of the tactics in `tacs2` to one of the produced subgoals (like `focus'`). -/ meta def seq_focus {α β} (tac1 : tactic α) (tacs2 : α → list (tactic β)) : tactic (list β) := do g::gs ← get_goals, set_goals [g], a ← tac1, bs ← focus $ tacs2 a, gs' ← get_goals, set_goals (gs' ++ gs), pure bs /-- Applies `tac1` to the main goal, then applies each of the tactics in `tacs2` to one of the produced subgoals (like `focus`). -/ meta def seq_focus' (tac1 : tactic unit) (tacs2 : list (tactic unit)) : tactic unit := do g::gs ← get_goals, set_goals [g], tac1, focus tacs2, gs' ← get_goals, set_goals (gs' ++ gs) meta instance andthen_seq : has_andthen (tactic unit) (tactic unit) (tactic unit) := ⟨seq'⟩ meta instance andthen_seq_focus : has_andthen (tactic unit) (list (tactic unit)) (tactic unit) := ⟨seq_focus'⟩ meta constant is_trace_enabled_for : name → bool /-- Execute tac only if option trace.n is set to true. -/ meta def when_tracing (n : name) (tac : tactic unit) : tactic unit := when (is_trace_enabled_for n = tt) tac /-- Fail if there are no remaining goals. -/ meta def fail_if_no_goals : tactic unit := do n ← num_goals, when (n = 0) (fail "tactic failed, there are no goals to be solved") /-- Fail if there are unsolved goals. -/ meta def done : tactic unit := do n ← num_goals, when (n ≠ 0) (fail "done tactic failed, there are unsolved goals") meta def apply_opt_param : tactic unit := do `(opt_param %%t %%v) ← target, exact v meta def apply_auto_param : tactic unit := do `(auto_param %%type %%tac_name_expr) ← target, change type, tac_name ← eval_expr name tac_name_expr, tac ← eval_expr (tactic unit) (expr.const tac_name []), tac meta def has_opt_auto_param (ms : list expr) : tactic bool := ms.mfoldl (λ r m, do type ← infer_type m, return $ r || type.is_napp_of `opt_param 2 || type.is_napp_of `auto_param 2) ff meta def try_apply_opt_auto_param (cfg : apply_cfg) (ms : list expr) : tactic unit := when (cfg.auto_param || cfg.opt_param) $ mwhen (has_opt_auto_param ms) $ do gs ← get_goals, ms.mmap' (λ m, mwhen (bnot <$> is_assigned m) $ set_goals [m] >> when cfg.opt_param (try apply_opt_param) >> when cfg.auto_param (try apply_auto_param)), set_goals gs meta def has_opt_auto_param_for_apply (ms : list (name × expr)) : tactic bool := ms.mfoldl (λ r m, do type ← infer_type m.2, return $ r || type.is_napp_of `opt_param 2 || type.is_napp_of `auto_param 2) ff meta def try_apply_opt_auto_param_for_apply (cfg : apply_cfg) (ms : list (name × expr)) : tactic unit := mwhen (has_opt_auto_param_for_apply ms) $ do gs ← get_goals, ms.mmap' (λ m, mwhen (bnot <$> (is_assigned m.2)) $ set_goals [m.2] >> when cfg.opt_param (try apply_opt_param) >> when cfg.auto_param (try apply_auto_param)), set_goals gs meta def apply (e : expr) (cfg : apply_cfg := {}) : tactic (list (name × expr)) := do r ← apply_core e cfg, try_apply_opt_auto_param_for_apply cfg r, return r /-- Same as `apply` but __all__ arguments that weren't inferred are added to goal list. -/ meta def fapply (e : expr) : tactic (list (name × expr)) := apply e {new_goals := new_goals.all} /-- Same as `apply` but only goals that don't depend on other goals are added to goal list. -/ meta def eapply (e : expr) : tactic (list (name × expr)) := apply e {new_goals := new_goals.non_dep_only} /-- Try to solve the main goal using type class resolution. -/ meta def apply_instance : tactic unit := do tgt ← target >>= instantiate_mvars, b ← is_class tgt, if b then mk_instance tgt >>= exact else fail "apply_instance tactic fail, target is not a type class" /-- Create a list of universe meta-variables of the given size. -/ meta def mk_num_meta_univs : nat → tactic (list level) | 0 := return [] | (succ n) := do l ← mk_meta_univ, ls ← mk_num_meta_univs n, return (l::ls) /-- Return `expr.const c [l_1, ..., l_n]` where l_i's are fresh universe meta-variables. -/ meta def mk_const (c : name) : tactic expr := do env ← get_env, decl ← env.get c, let num := decl.univ_params.length, ls ← mk_num_meta_univs num, return (expr.const c ls) /-- Apply the constant `c` -/ meta def applyc (c : name) (cfg : apply_cfg := {}) : tactic unit := do c ← mk_const c, apply c cfg, skip meta def eapplyc (c : name) : tactic unit := do c ← mk_const c, eapply c, skip meta def save_const_type_info (n : name) {elab : bool} (ref : expr elab) : tactic unit := try (do c ← mk_const n, save_type_info c ref) /-- Create a fresh universe `?u`, a metavariable `?T : Type.{?u}`, and return metavariable `?M : ?T`. This action can be used to create a meta-variable when we don't know its type at creation time -/ meta def mk_mvar : tactic expr := do u ← mk_meta_univ, t ← mk_meta_var (expr.sort u), mk_meta_var t /-- Makes a sorry macro with a meta-variable as its type. -/ meta def mk_sorry : tactic expr := do u ← mk_meta_univ, t ← mk_meta_var (expr.sort u), return $ expr.mk_sorry t /-- Closes the main goal using sorry. -/ meta def admit : tactic unit := target >>= exact ∘ expr.mk_sorry meta def mk_local' (pp_name : name) (bi : binder_info) (type : expr) : tactic expr := do uniq_name ← mk_fresh_name, return $ expr.local_const uniq_name pp_name bi type meta def mk_local_def (pp_name : name) (type : expr) : tactic expr := mk_local' pp_name binder_info.default type meta def mk_local_pis : expr → tactic (list expr × expr) | (expr.pi n bi d b) := do p ← mk_local' n bi d, (ps, r) ← mk_local_pis (expr.instantiate_var b p), return ((p :: ps), r) | e := return ([], e) private meta def get_pi_arity_aux : expr → tactic nat | (expr.pi n bi d b) := do m ← mk_fresh_name, let l := expr.local_const m n bi d, new_b ← whnf (expr.instantiate_var b l), r ← get_pi_arity_aux new_b, return (r + 1) | e := return 0 /-- Compute the arity of the given (Pi-)type -/ meta def get_pi_arity (type : expr) : tactic nat := whnf type >>= get_pi_arity_aux /-- Compute the arity of the given function -/ meta def get_arity (fn : expr) : tactic nat := infer_type fn >>= get_pi_arity meta def triv : tactic unit := mk_const `trivial >>= exact notation `dec_trivial` := of_as_true (by tactic.triv) meta def by_contradiction (H : option name := none) : tactic expr := do tgt : expr ← target, (match_not tgt >> return ()) <|> (mk_mapp `decidable.by_contradiction [some tgt, none] >>= eapply >> skip) <|> fail "tactic by_contradiction failed, target is not a negation nor a decidable proposition (remark: when 'local attribute [instance] classical.prop_decidable' is used, all propositions are decidable)", match H with | some n := intro n | none := intro1 end private meta def generalizes_aux (md : transparency) : list expr → tactic unit | [] := skip | (e::es) := generalize e `x md >> generalizes_aux es meta def generalizes (es : list expr) (md := semireducible) : tactic unit := generalizes_aux md es private meta def kdependencies_core (e : expr) (md : transparency) : list expr → list expr → tactic (list expr) | [] r := return r | (h::hs) r := do type ← infer_type h, d ← kdepends_on type e md, if d then kdependencies_core hs (h::r) else kdependencies_core hs r /-- Return all hypotheses that depends on `e` The dependency test is performed using `kdepends_on` with the given transparency setting. -/ meta def kdependencies (e : expr) (md := reducible) : tactic (list expr) := do ctx ← local_context, kdependencies_core e md ctx [] /-- Revert all hypotheses that depend on `e` -/ meta def revert_kdependencies (e : expr) (md := reducible) : tactic nat := kdependencies e md >>= revert_lst meta def revert_kdeps (e : expr) (md := reducible) := revert_kdependencies e md /-- Similar to `cases_core`, but `e` doesn't need to be a hypothesis. Remark, it reverts dependencies using `revert_kdeps`. Two different transparency modes are used `md` and `dmd`. The mode `md` is used with `cases_core` and `dmd` with `generalize` and `revert_kdeps`. It returns the constructor names associated with each new goal and the newly introduced hypotheses. -/ meta def cases (e : expr) (ids : list name := []) (md := semireducible) (dmd := semireducible) : tactic (list (name × list expr)) := if e.is_local_constant then do r ← cases_core e ids md, return $ r.map (λ ⟨n, hs, _⟩, ⟨n, hs⟩) else do n ← revert_kdependencies e dmd, x ← get_unused_name, (tactic.generalize e x dmd) <|> (do t ← infer_type e, tactic.assertv x t e, get_local x >>= tactic.revert, return ()), h ← tactic.intro1, focus1 $ do r ← cases_core h ids md, hs' ← all_goals (intron' n), return $ r.map₂ (λ ⟨n, hs, _⟩ hs', ⟨n, hs ++ hs'⟩) hs' /-- The same as `exact` except you can add proof holes. -/ meta def refine (e : pexpr) : tactic unit := do tgt : expr ← target, to_expr ``(%%e : %%tgt) tt >>= exact meta def by_cases (e : expr) (h : name) : tactic unit := do dec_e ← (mk_app `decidable [e] <|> fail "by_cases tactic failed, type is not a proposition"), inst ← (mk_instance dec_e <|> fail "by_cases tactic failed, type of given expression is not decidable"), t ← target, tm ← mk_mapp `dite [some e, some inst, some t], seq' (apply tm >> skip) (intro h >> skip) meta def funext_core : list name → bool → tactic unit | [] tt := return () | ids only_ids := try $ do some (lhs, rhs) ← expr.is_eq <$> (target >>= whnf), applyc `funext, id ← if ids.empty ∨ ids.head = `_ then do (expr.lam n _ _ _) ← whnf lhs | pure `_, return n else return ids.head, intro id, funext_core ids.tail only_ids meta def funext : tactic unit := funext_core [] ff meta def funext_lst (ids : list name) : tactic unit := funext_core ids tt private meta def get_undeclared_const (env : environment) (base : name) : ℕ → name | i := let n := base <.> ("_aux_" ++ repr i) in if ¬env.contains n then n else get_undeclared_const (i+1) meta def new_aux_decl_name : tactic name := do env ← get_env, n ← decl_name, return $ get_undeclared_const env n 1 private meta def mk_aux_decl_name : option name → tactic name | none := new_aux_decl_name | (some suffix) := do p ← decl_name, return $ p ++ suffix meta def abstract (tac : tactic unit) (suffix : option name := none) (zeta_reduce := tt) : tactic unit := do fail_if_no_goals, gs ← get_goals, type ← if zeta_reduce then target >>= zeta else target, is_lemma ← is_prop type, m ← mk_meta_var type, set_goals [m], tac, n ← num_goals, when (n ≠ 0) (fail "abstract tactic failed, there are unsolved goals"), set_goals gs, val ← instantiate_mvars m, val ← if zeta_reduce then zeta val else return val, c ← mk_aux_decl_name suffix, e ← add_aux_decl c type val is_lemma, exact e /-- `solve_aux type tac` synthesize an element of 'type' using tactic 'tac' -/ meta def solve_aux {α : Type} (type : expr) (tac : tactic α) : tactic (α × expr) := do m ← mk_meta_var type, gs ← get_goals, set_goals [m], a ← tac, set_goals gs, return (a, m) /-- Return tt iff 'd' is a declaration in one of the current open namespaces -/ meta def in_open_namespaces (d : name) : tactic bool := do ns ← open_namespaces, env ← get_env, return $ ns.any (λ n, n.is_prefix_of d) && env.contains d /-- Execute tac for 'max' "heartbeats". The heartbeat is approx. the maximum number of memory allocations (in thousands) performed by 'tac'. This is a deterministic way of interrupting long running tactics. -/ meta def try_for {α} (max : nat) (tac : tactic α) : tactic α := λ s, match _root_.try_for max (tac s) with | some r := r | none := mk_exception "try_for tactic failed, timeout" none s end meta def updateex_env (f : environment → exceptional environment) : tactic unit := do env ← get_env, env ← returnex $ f env, set_env env /- Add a new inductive datatype to the environment name, universe parameters, number of parameters, type, constructors (name and type), is_meta -/ meta def add_inductive (n : name) (ls : list name) (p : nat) (ty : expr) (is : list (name × expr)) (is_meta : bool := ff) : tactic unit := updateex_env $ λe, e.add_inductive n ls p ty is is_meta meta def add_meta_definition (n : name) (lvls : list name) (type value : expr) : tactic unit := add_decl (declaration.defn n lvls type value reducibility_hints.abbrev ff) /-- add declaration `d` as a protected declaration -/ meta def add_protected_decl (d : declaration) : tactic unit := updateex_env $ λ e, e.add_protected d /-- check if `n` is the name of a protected declaration -/ meta def is_protected_decl (n : name) : tactic bool := do env ← get_env, return $ env.is_protected n /-- `add_defn_equations` adds a definition specified by a list of equations. The arguments: * `lp`: list of universe parameters * `params`: list of parameters (binders before the colon); * `fn`: a local constant giving the name and type of the declaration (with `params` in the local context); * `eqns`: a list of equations, each of which is a list of patterns (constructors applied to new local constants) and the branch expression; * `is_meta`: is the definition meta? `add_defn_equations` can be used as: do my_add ← mk_local_def `my_add `(ℕ → ℕ), a ← mk_local_def `a ℕ, b ← mk_local_def `b ℕ, add_defn_equations [a] my_add [ ([``(nat.zero)], a), ([``(nat.succ %%b)], my_add b) ]) ff -- non-meta to create the following definition: def my_add (a : ℕ) : ℕ → ℕ | nat.zero := a | (nat.succ b) := my_add b -/ meta def add_defn_equations (lp : list name) (params : list expr) (fn : expr) (eqns : list (list pexpr × expr)) (is_meta : bool) : tactic unit := do opt ← get_options, updateex_env $ λ e, e.add_defn_eqns opt lp params fn eqns is_meta /-- Get the revertible part of the local context. These are the hypotheses that appear after the last frozen local instance in the local context. We call them revertible because `revert` can revert them, unlike those hypotheses which occur before a frozen instance. -/ meta def revertible_local_context : tactic (list expr) := do ctx ← local_context, frozen ← frozen_local_instances, pure $ match frozen with | none := ctx | some [] := ctx | some (h :: _) := ctx.after (eq h) end /-- Rename local hypotheses according to the given `name_map`. The `name_map` contains as keys those hypotheses that should be renamed; the associated values are the new names. This tactic can only rename hypotheses which occur after the last frozen local instance. If you need to rename earlier hypotheses, try `unfreeze_local_instances`. If `strict` is true, we fail if `name_map` refers to hypotheses that do not appear in the local context or that appear before a frozen local instance. Conversely, if `strict` is false, some entries of `name_map` may be silently ignored. If `use_unique_names` is true, the keys of `name_map` should be the unique names of hypotheses to be renamed. Otherwise, the keys should be display names. Note that we allow shadowing, so renamed hypotheses may have the same name as other hypotheses in the context. If `use_unique_names` is false and there are multiple hypotheses with the same display name in the context, they are all renamed. -/ meta def rename_many (renames : name_map name) (strict := tt) (use_unique_names := ff) : tactic unit := do let hyp_name : expr → name := if use_unique_names then expr.local_uniq_name else expr.local_pp_name, ctx ← revertible_local_context, -- The part of the context after (but including) the first hypthesis that -- must be renamed. let ctx_suffix := ctx.drop_while (λ h, (renames.find $ hyp_name h).is_none), when strict $ do { let ctx_names := rb_map.set_of_list (ctx_suffix.map hyp_name), let invalid_renames := (renames.to_list.map prod.fst).filter (λ h, ¬ ctx_names.contains h), when ¬ invalid_renames.empty $ fail $ format.join [ "Cannot rename these hypotheses:\n" , format.join $ (invalid_renames.map to_fmt).intersperse ", " , format.line , "This is because these hypotheses either do not occur in the\n" , "context or they occur before a frozen local instance.\n" , "In the latter case, try `tactic.unfreeze_local_instances`." ] }, -- The new names for all hypotheses in ctx_suffix. let new_names := ctx_suffix.map $ λ h, (renames.find $ hyp_name h).get_or_else h.local_pp_name, revert_lst ctx_suffix, intro_lst new_names, pure () /-- Rename a local hypothesis. This is a special case of `rename_many`; see there for caveats. -/ meta def rename (curr : name) (new : name) : tactic unit := rename_many (rb_map.of_list [⟨curr, new⟩]) /-- Rename a local hypothesis. Unlike `rename` and `rename_many`, this tactic does not preserve the order of hypotheses. Its implementation is simpler (and therefore probably faster) than that of `rename`. -/ meta def rename_unstable (curr : name) (new : name) : tactic unit := do h ← get_local curr, n ← revert h, intro new, intron (n - 1) /-- "Replace" hypothesis `h : type` with `h : new_type` where `eq_pr` is a proof that (type = new_type). The tactic actually creates a new hypothesis with the same user facing name, and (tries to) clear `h`. The `clear` step fails if `h` has forward dependencies. In this case, the old `h` will remain in the local context. The tactic returns the new hypothesis. -/ meta def replace_hyp (h : expr) (new_type : expr) (eq_pr : expr) : tactic expr := do h_type ← infer_type h, new_h ← assert h.local_pp_name new_type, mk_eq_mp eq_pr h >>= exact, try $ clear h, return new_h meta def main_goal : tactic expr := do g::gs ← get_goals, return g /- Goal tagging support -/ meta def with_enable_tags {α : Type} (t : tactic α) (b := tt) : tactic α := do old ← tags_enabled, enable_tags b, r ← t, enable_tags old, return r meta def get_main_tag : tactic tag := main_goal >>= get_tag meta def set_main_tag (t : tag) : tactic unit := do g ← main_goal, set_tag g t meta def subst (h : expr) : tactic unit := (do guard h.is_local_constant, some (α, lhs, β, rhs) ← expr.is_heq <$> infer_type h, is_def_eq α β, new_h_type ← mk_app `eq [lhs, rhs], new_h_pr ← mk_app `eq_of_heq [h], new_h ← assertv h.local_pp_name new_h_type new_h_pr, try (clear h), subst_core new_h) <|> subst_core h end tactic notation [parsing_only] `command`:max := tactic unit open tactic namespace list meta def for_each {α} : list α → (α → tactic unit) → tactic unit | [] fn := skip | (e::es) fn := do fn e, for_each es fn meta def any_of {α β} : list α → (α → tactic β) → tactic β | [] fn := failed | (e::es) fn := do opt_b ← try_core (fn e), match opt_b with | some b := return b | none := any_of es fn end end list /- Install monad laws tactic and use it to prove some instances. -/ /-- Try to prove with `iff.refl`.-/ meta def order_laws_tac := whnf_target >> intros >> to_expr ``(iff.refl _) >>= exact meta def monad_from_pure_bind {m : Type u → Type v} (pure : Π {α : Type u}, α → m α) (bind : Π {α β : Type u}, m α → (α → m β) → m β) : monad m := {pure := @pure, bind := @bind} meta instance : monad task := {map := @task.map, bind := @task.bind, pure := @task.pure} namespace tactic meta def mk_id_proof (prop : expr) (pr : expr) : expr := expr.app (expr.app (expr.const ``id [level.zero]) prop) pr meta def mk_id_eq (lhs : expr) (rhs : expr) (pr : expr) : tactic expr := do prop ← mk_app `eq [lhs, rhs], return $ mk_id_proof prop pr meta def replace_target (new_target : expr) (pr : expr) : tactic unit := do t ← target, assert `htarget new_target, swap, ht ← get_local `htarget, locked_pr ← mk_id_eq t new_target pr, mk_eq_mpr locked_pr ht >>= exact end tactic
33af82cf56876f68809a7467920e620b7ff36ea2
4727251e0cd73359b15b664c3170e5d754078599
/archive/100-theorems-list/83_friendship_graphs.lean
0e4f03120b2345b77390743d7440f21733d101b4
[ "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
13,809
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson, Jalex Stark, Kyle Miller -/ import combinatorics.simple_graph.adj_matrix import linear_algebra.matrix.charpoly.finite_field import data.int.modeq import data.zmod.basic import tactic.interval_cases /-! # The Friendship Theorem ## Definitions and Statement - A `friendship` graph is one in which any two distinct vertices have exactly one neighbor in common - A `politician`, at least in the context of this problem, is a vertex in a graph which is adjacent to every other vertex. - The friendship theorem (Erdős, Rényi, Sós 1966) states that every finite friendship graph has a politician. ## Proof outline The proof revolves around the theory of adjacency matrices, although some steps could equivalently be phrased in terms of counting walks. - Assume `G` is a finite friendship graph. - First we show that any two nonadjacent vertices have the same degree - Assume for contradiction that `G` does not have a politician. - Conclude from the last two points that `G` is `d`-regular for some `d : ℕ`. - Show that `G` has `d ^ 2 - d + 1` vertices. - By casework, show that if `d = 0, 1, 2`, then `G` has a politician. - If `3 ≤ d`, let `p` be a prime factor of `d - 1`. - If `A` is the adjacency matrix of `G` with entries in `ℤ/pℤ`, we show that `A ^ p` has trace `1`. - This gives a contradiction, as `A` has trace `0`, and thus `A ^ p` has trace `0`. ## References - [P. Erdős, A. Rényi, V. Sós, *On A Problem of Graph Theory*][erdosrenyisos] - [C. Huneke, *The Friendship Theorem*][huneke2002] -/ open_locale classical big_operators noncomputable theory open finset simple_graph matrix universes u v variables {V : Type u} {R : Type v} [semiring R] section friendship_def variables (G : simple_graph V) /-- This property of a graph is the hypothesis of the friendship theorem: every pair of nonadjacent vertices has exactly one common friend, a vertex to which both are adjacent. -/ def friendship [fintype V] : Prop := ∀ ⦃v w : V⦄, v ≠ w → fintype.card (G.common_neighbors v w) = 1 /-- A politician is a vertex that is adjacent to all other vertices. -/ def exists_politician : Prop := ∃ (v : V), ∀ (w : V), v ≠ w → G.adj v w end friendship_def variables [fintype V] {G : simple_graph V} {d : ℕ} (hG : friendship G) include hG namespace friendship variables (R) /-- One characterization of a friendship graph is that there is exactly one walk of length 2 between distinct vertices. These walks are counted in off-diagonal entries of the square of the adjacency matrix, so for a friendship graph, those entries are all 1. -/ theorem adj_matrix_sq_of_ne {v w : V} (hvw : v ≠ w) : ((G.adj_matrix R) ^ 2) v w = 1 := begin rw [sq, ← nat.cast_one, ← hG hvw], simp [common_neighbors, neighbor_finset_eq_filter, finset.filter_filter, finset.filter_inter, and_comm, ← neighbor_finset_def], end /-- This calculation amounts to counting the number of length 3 walks between nonadjacent vertices. We use it to show that nonadjacent vertices have equal degrees. -/ lemma adj_matrix_pow_three_of_not_adj {v w : V} (non_adj : ¬ G.adj v w) : ((G.adj_matrix R) ^ 3) v w = degree G v := begin rw [pow_succ, mul_eq_mul, adj_matrix_mul_apply, degree, card_eq_sum_ones, nat.cast_sum], apply sum_congr rfl, intros x hx, rw [adj_matrix_sq_of_ne _ hG, nat.cast_one], rintro ⟨rfl⟩, rw mem_neighbor_finset at hx, exact non_adj hx, end variable {R} /-- As `v` and `w` not being adjacent implies `degree G v = ((G.adj_matrix R) ^ 3) v w` and `degree G w = ((G.adj_matrix R) ^ 3) v w`, the degrees are equal if `((G.adj_matrix R) ^ 3) v w = ((G.adj_matrix R) ^ 3) w v` This is true as the adjacency matrix is symmetric. -/ lemma degree_eq_of_not_adj {v w : V} (hvw : ¬ G.adj v w) : degree G v = degree G w := begin rw [← nat.cast_id (G.degree v), ← nat.cast_id (G.degree w), ← adj_matrix_pow_three_of_not_adj ℕ hG hvw, ← adj_matrix_pow_three_of_not_adj ℕ hG (λ h, hvw (G.symm h))], conv_lhs {rw ← transpose_adj_matrix}, simp only [pow_succ, sq, mul_eq_mul, ← transpose_mul, transpose_apply], simp only [← mul_eq_mul, mul_assoc], end /-- Let `A` be the adjacency matrix of a graph `G`. If `G` is a friendship graph, then all of the off-diagonal entries of `A^2` are 1. If `G` is `d`-regular, then all of the diagonal entries of `A^2` are `d`. Putting these together determines `A^2` exactly for a `d`-regular friendship graph. -/ theorem adj_matrix_sq_of_regular (hd : G.is_regular_of_degree d) : ((G.adj_matrix R) ^ 2) = λ v w, if v = w then d else 1 := begin ext v w, by_cases h : v = w, { rw [h, sq, mul_eq_mul, adj_matrix_mul_self_apply_self, hd], simp, }, { rw [adj_matrix_sq_of_ne R hG h, if_neg h], }, end lemma adj_matrix_sq_mod_p_of_regular {p : ℕ} (dmod : (d : zmod p) = 1) (hd : G.is_regular_of_degree d) : (G.adj_matrix (zmod p)) ^ 2 = λ _ _, 1 := by simp [adj_matrix_sq_of_regular hG hd, dmod] section nonempty variable [nonempty V] /-- If `G` is a friendship graph without a politician (a vertex adjacent to all others), then it is regular. We have shown that nonadjacent vertices of a friendship graph have the same degree, and if there isn't a politician, we can show this for adjacent vertices by finding a vertex neither is adjacent to, and then using transitivity. -/ theorem is_regular_of_not_exists_politician (hG' : ¬exists_politician G) : ∃ (d : ℕ), G.is_regular_of_degree d := begin have v := classical.arbitrary V, use G.degree v, intro x, by_cases hvx : G.adj v x, swap, { exact (degree_eq_of_not_adj hG hvx).symm, }, dunfold exists_politician at hG', push_neg at hG', rcases hG' v with ⟨w, hvw', hvw⟩, rcases hG' x with ⟨y, hxy', hxy⟩, by_cases hxw : G.adj x w, swap, { rw degree_eq_of_not_adj hG hvw, exact degree_eq_of_not_adj hG hxw }, rw degree_eq_of_not_adj hG hxy, by_cases hvy : G.adj v y, swap, { exact (degree_eq_of_not_adj hG hvy).symm }, rw degree_eq_of_not_adj hG hvw, apply degree_eq_of_not_adj hG, intro hcontra, rcases finset.card_eq_one.mp (hG hvw') with ⟨⟨a, ha⟩, h⟩, have key : ∀ {x}, x ∈ G.common_neighbors v w → x = a, { intros x hx, have h' := mem_univ (subtype.mk x hx), rw [h, mem_singleton] at h', injection h', }, apply hxy', rw [key ((mem_common_neighbors G).mpr ⟨hvx, G.symm hxw⟩), key ((mem_common_neighbors G).mpr ⟨hvy, G.symm hcontra⟩)], end /-- Let `A` be the adjacency matrix of a `d`-regular friendship graph, and let `v` be a vector all of whose components are `1`. Then `v` is an eigenvector of `A ^ 2`, and we can compute the eigenvalue to be `d * d`, or as `d + (fintype.card V - 1)`, so those quantities must be equal. This essentially means that the graph has `d ^ 2 - d + 1` vertices. -/ lemma card_of_regular (hd : G.is_regular_of_degree d) : d + (fintype.card V - 1) = d * d := begin have v := classical.arbitrary V, transitivity ((G.adj_matrix ℕ) ^ 2).mul_vec (λ _, 1) v, { rw [adj_matrix_sq_of_regular hG hd, mul_vec, dot_product, ← insert_erase (mem_univ v)], simp only [sum_insert, mul_one, if_true, nat.cast_id, eq_self_iff_true, mem_erase, not_true, ne.def, not_false_iff, add_right_inj, false_and], rw [finset.sum_const_nat, card_erase_of_mem (mem_univ v), mul_one], { refl }, intros x hx, simp [(ne_of_mem_erase hx).symm], }, { rw [sq, mul_eq_mul, ← mul_vec_mul_vec], simp [adj_matrix_mul_vec_const_apply_of_regular hd, neighbor_finset, card_neighbor_set_eq_degree, hd v], } end /-- The size of a `d`-regular friendship graph is `1 mod (d-1)`, and thus `1 mod p` for a factor `p ∣ d-1`. -/ lemma card_mod_p_of_regular {p : ℕ} (dmod : (d : zmod p) = 1) (hd : G.is_regular_of_degree d) : (fintype.card V : zmod p) = 1 := begin have hpos : 0 < fintype.card V := fintype.card_pos_iff.mpr infer_instance, rw [← nat.succ_pred_eq_of_pos hpos, nat.succ_eq_add_one, nat.pred_eq_sub_one], simp only [add_left_eq_self, nat.cast_add, nat.cast_one], have h := congr_arg (λ n, (↑n : zmod p)) (card_of_regular hG hd), revert h, simp [dmod], end end nonempty omit hG lemma adj_matrix_sq_mul_const_one_of_regular (hd : G.is_regular_of_degree d) : (G.adj_matrix R) * (λ _ _, 1) = λ _ _, d := by { ext x, simp [← hd x, degree] } lemma adj_matrix_mul_const_one_mod_p_of_regular {p : ℕ} (dmod : (d : zmod p) = 1) (hd : G.is_regular_of_degree d) : (G.adj_matrix (zmod p)) * (λ _ _, 1) = λ _ _, 1 := by rw [adj_matrix_sq_mul_const_one_of_regular hd, dmod] include hG /-- Modulo a factor of `d-1`, the square and all higher powers of the adjacency matrix of a `d`-regular friendship graph reduce to the matrix whose entries are all 1. -/ lemma adj_matrix_pow_mod_p_of_regular {p : ℕ} (dmod : (d : zmod p) = 1) (hd : G.is_regular_of_degree d) {k : ℕ} (hk : 2 ≤ k) : (G.adj_matrix (zmod p)) ^ k = λ _ _, 1 := begin iterate 2 {cases k with k, { exfalso, linarith, }, }, induction k with k hind, { exact adj_matrix_sq_mod_p_of_regular hG dmod hd, }, rw [pow_succ, hind (nat.le_add_left 2 k)], exact adj_matrix_mul_const_one_mod_p_of_regular dmod hd, end variable [nonempty V] /-- This is the main proof. Assuming that `3 ≤ d`, we take `p` to be a prime factor of `d-1`. Then the `p`th power of the adjacency matrix of a `d`-regular friendship graph must have trace 1 mod `p`, but we can also show that the trace must be the `p`th power of the trace of the original adjacency matrix, which is 0, a contradiction. -/ lemma false_of_three_le_degree (hd : G.is_regular_of_degree d) (h : 3 ≤ d) : false := begin -- get a prime factor of d - 1 let p : ℕ := (d - 1).min_fac, have p_dvd_d_pred := (zmod.nat_coe_zmod_eq_zero_iff_dvd _ _).mpr (d - 1).min_fac_dvd, have dpos : 0 < d := by linarith, have d_cast : ↑(d - 1) = (d : ℤ) - 1 := by norm_cast, haveI : fact p.prime := ⟨nat.min_fac_prime (by linarith)⟩, have hp2 : 2 ≤ p := (fact.out p.prime).two_le, have dmod : (d : zmod p) = 1, { rw [← nat.succ_pred_eq_of_pos dpos, nat.succ_eq_add_one, nat.pred_eq_sub_one], simp only [add_left_eq_self, nat.cast_add, nat.cast_one], exact p_dvd_d_pred, }, have Vmod := card_mod_p_of_regular hG dmod hd, -- now we reduce to a trace calculation have := zmod.trace_pow_card (G.adj_matrix (zmod p)), contrapose! this, clear this, -- the trace is 0 mod p when computed one way rw [trace_adj_matrix, zero_pow (fact.out p.prime).pos], -- but the trace is 1 mod p when computed the other way rw adj_matrix_pow_mod_p_of_regular hG dmod hd hp2, dunfold fintype.card at Vmod, simp only [matrix.trace, matrix.diag, mul_one, nsmul_eq_mul, linear_map.coe_mk, sum_const], rw [Vmod, ← nat.cast_one, zmod.nat_coe_zmod_eq_zero_iff_dvd, nat.dvd_one, nat.min_fac_eq_one_iff], linarith, end /-- If `d ≤ 1`, a `d`-regular friendship graph has at most one vertex, which is trivially a politician. -/ lemma exists_politician_of_degree_le_one (hd : G.is_regular_of_degree d) (hd1 : d ≤ 1) : exists_politician G := begin have sq : d * d = d := by { interval_cases d; norm_num }, have h := card_of_regular hG hd, rw sq at h, have : fintype.card V ≤ 1, { cases fintype.card V with n, { exact zero_le _, }, { have : n = 0, { rw [nat.succ_sub_succ_eq_sub, tsub_zero] at h, linarith }, subst n, } }, use classical.arbitrary V, intros w h, exfalso, apply h, apply fintype.card_le_one_iff.mp this, end /-- If `d = 2`, a `d`-regular friendship graph has 3 vertices, so it must be complete graph, and all the vertices are politicians. -/ lemma neighbor_finset_eq_of_degree_eq_two (hd : G.is_regular_of_degree 2) (v : V) : G.neighbor_finset v = finset.univ.erase v := begin apply finset.eq_of_subset_of_card_le, { rw finset.subset_iff, intro x, rw [mem_neighbor_finset, finset.mem_erase], exact λ h, ⟨(G.ne_of_adj h).symm, finset.mem_univ _⟩ }, convert_to 2 ≤ _, { convert_to _ = fintype.card V - 1, { have hfr:= card_of_regular hG hd, linarith }, { exact finset.card_erase_of_mem (finset.mem_univ _), }, }, { dsimp [is_regular_of_degree, degree] at hd, rw hd, } end lemma exists_politician_of_degree_eq_two (hd : G.is_regular_of_degree 2) : exists_politician G := begin have v := classical.arbitrary V, use v, intros w hvw, rw [← mem_neighbor_finset, neighbor_finset_eq_of_degree_eq_two hG hd v, finset.mem_erase], exact ⟨hvw.symm, finset.mem_univ _⟩, end lemma exists_politician_of_degree_le_two (hd : G.is_regular_of_degree d) (h : d ≤ 2) : exists_politician G := begin interval_cases d, iterate 2 { apply exists_politician_of_degree_le_one hG hd, norm_num }, { exact exists_politician_of_degree_eq_two hG hd }, end end friendship /-- **Friendship theorem**: We wish to show that a friendship graph has a politician (a vertex adjacent to all others). We proceed by contradiction, and assume the graph has no politician. We have already proven that a friendship graph with no politician is `d`-regular for some `d`, and now we do casework on `d`. If the degree is at most 2, we observe by casework that it has a politician anyway. If the degree is at least 3, the graph cannot exist. -/ theorem friendship_theorem [nonempty V] : exists_politician G := begin by_contradiction npG, rcases hG.is_regular_of_not_exists_politician npG with ⟨d, dreg⟩, cases lt_or_le d 3 with dle2 dge3, { exact npG (hG.exists_politician_of_degree_le_two dreg (nat.lt_succ_iff.mp dle2)) }, { exact hG.false_of_three_le_degree dreg dge3 }, end
0c6c1583769d2c50e326572796a0ec2602266911
f3849be5d845a1cb97680f0bbbe03b85518312f0
/tests/lean/pp_all.lean
a5802b291fbc2140cdd5a1955a0bbe1195597c41
[ "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
152
lean
-- open nat variables {a : nat} definition b : num := 2 #check (λ x, x) a + of_num b = 10 set_option pp.all true #check (λ x, x) a + of_num b = 10
c32a04e02b72fb6a63a2f91f6c7465cbf161cd53
556aeb81a103e9e0ac4e1fe0ce1bc6e6161c3c5e
/src/starkware/cairo/lean/semantics/air_encoding/step.lean
edd1824fc817a4e6654ab0787b235592623bc733
[ "Apache-2.0" ]
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
12,954
lean
/- The constraints that govern the one-step machine transition. -/ import starkware.cairo.lean.semantics.cpu import starkware.cairo.lean.semantics.air_encoding.constraints variables {F : Type*} [field F] /- from trace_data (indexed by step) -/ variables {off_op0_tilde off_op1_tilde off_dst_tilde : F} variable {f_tilde : tilde_type F} variables {fp ap pc : F} variables {next_fp next_ap next_pc : F} variables {dst_addr op0_addr op1_addr : F} variables {dst op0 op1 mul res t0 t1 : F} /- from instruction constraints -/ variable {inst : instruction} /- from memory constraints -/ variable {mem : F → F} /- from instruction constraints -/ variable h_off_dst_tilde : off_dst_tilde = ↑inst.off_dst.to_natr variable h_off_op0_tilde : off_op0_tilde = ↑inst.off_op0.to_natr variable h_off_op1_tilde : off_op1_tilde = ↑inst.off_op1.to_natr variable h_flags : ∀ i, f_tilde.to_f i = ↑(inst.flags.nth i).to_nat /- from memory constraints -/ variable h_mem_pc : mem pc = inst.to_nat variable h_mem_dst_addr : mem dst_addr = dst variable h_mem_op0_addr : mem op0_addr = op0 variable h_mem_op1_addr : mem op1_addr = op1 /- step constraints -/ variable h_dst_addr : dst_addr = f_tilde.f_dst_reg * fp + (1 - f_tilde.f_dst_reg) * ap + (off_dst_tilde - 2^15) variable h_op0_addr : op0_addr = f_tilde.f_op0_reg * fp + (1 - f_tilde.f_op0_reg) * ap + (off_op0_tilde - 2^15) variable h_op1_addr : op1_addr = f_tilde.f_op1_imm * pc + f_tilde.f_op1_ap * ap + f_tilde.f_op1_fp * fp + (1 - f_tilde.f_op1_imm - f_tilde.f_op1_ap - f_tilde.f_op1_fp) * op0 + (off_op1_tilde - 2^15) variable h_mul : mul = op0 * op1 variable h_res : (1 - f_tilde.f_pc_jnz) * res = f_tilde.f_res_add * (op0 + op1) + f_tilde.f_res_mul * mul + (1 - f_tilde.f_res_add - f_tilde.f_res_mul - f_tilde.f_pc_jnz) * op1 variable h_t0_eq : t0 = f_tilde.f_pc_jnz * dst variable h_t1_eq : t1 = t0 * res variable h_next_pc_eq : (t1 - f_tilde.f_pc_jnz) * (next_pc - (pc + (f_tilde.f_op1_imm + 1))) = 0 variable h_next_pc_eq' : t0 * (next_pc - (pc + op1)) + (1 - f_tilde.f_pc_jnz) * next_pc - ((1 - f_tilde.f_pc_jump_abs - f_tilde.f_pc_jump_rel - f_tilde.f_pc_jnz) * (pc + (f_tilde.f_op1_imm + 1)) + f_tilde.f_pc_jump_abs * res + f_tilde.f_pc_jump_rel * (pc + res)) = 0 variable h_opcode_call : f_tilde.f_opcode_call * (dst - fp) = 0 variable h_opcode_call' : f_tilde.f_opcode_call * (op0 - (pc + (f_tilde.f_op1_imm + 1))) = 0 variable h_opcode_assert_eq : f_tilde.f_opcode_assert_eq * (dst - res) = 0 variable h_next_ap : next_ap = ap + f_tilde.f_ap_add * res + f_tilde.f_ap_add1 + f_tilde.f_opcode_call * 2 variable h_next_fp : next_fp = f_tilde.f_opcode_ret * dst + f_tilde.f_opcode_call * (ap + 2) + (1 - f_tilde.f_opcode_ret - f_tilde.f_opcode_call) * fp /- The correctness theorems. -/ section include h_off_op0_tilde h_flags h_mem_op0_addr h_op0_addr theorem op0_eq : op0 = inst.op0 mem ⟨pc, ap, fp⟩ := begin have : f_tilde.f_op0_reg = ↑(inst.op0_reg.to_nat) := h_flags _, rw [instruction.op0, ←h_mem_op0_addr, h_op0_addr, h_off_op0_tilde, bitvec.to_biased_16, this], cases inst.op0_reg; simp end end section include h_off_op0_tilde h_off_op1_tilde h_flags include h_mem_op0_addr h_mem_op1_addr h_op0_addr h_op1_addr theorem op1_agrees : (inst.op1 mem ⟨pc, ap, fp⟩).agrees op1 := begin have h1 : f_tilde.f_op1_imm = ↑(inst.op1_imm.to_nat) := h_flags _, have h2 : f_tilde.f_op1_ap = ↑(inst.op1_ap.to_nat) := h_flags _, have h3 : f_tilde.f_op1_fp = ↑(inst.op1_fp.to_nat) := h_flags _, have h4 := @op0_eq _ _ _ _ _ _ pc _ _ _ _ h_off_op0_tilde h_flags h_mem_op0_addr h_op0_addr, rw [←h_mem_op1_addr, h_op1_addr, h_off_op1_tilde, instruction.op1, h1, h2, h3, h4], cases inst.op1_imm; cases inst.op1_fp; cases inst.op1_ap; simp [instruction.op1._match_1, option.agrees, bitvec.to_biased_16] end end section include h_off_op0_tilde h_off_op1_tilde h_flags include h_mem_op0_addr h_mem_op1_addr h_op0_addr h_op1_addr h_mul h_res theorem res_aux_agrees : f_tilde.f_pc_jnz = ff.to_nat → (inst.res_aux mem ⟨pc, ap, fp⟩).agrees res := begin intro h, revert h_res, rw h, simp, have h1 : f_tilde.f_res_add = ↑(inst.res_add.to_nat) := h_flags _, have h2 : f_tilde.f_res_mul = ↑(inst.res_mul.to_nat) := h_flags _, have h3 := @op0_eq _ _ _ _ _ _ pc _ _ _ _ h_off_op0_tilde h_flags h_mem_op0_addr h_op0_addr, have h4 := op1_agrees h_off_op0_tilde h_off_op1_tilde h_flags h_mem_op0_addr h_mem_op1_addr h_op0_addr h_op1_addr, revert h4, rw [instruction.res_aux, h1, h2], cases inst.op1 mem _ with op1; cases inst.res_add; cases inst.res_mul; simp [instruction.res_aux._match_1, option.agrees]; intros h5 h6; simp [h3, h5, h6, h_mul] end theorem res_agrees : (inst.res mem ⟨pc, ap, fp⟩).agrees res := begin have h1 : f_tilde.f_pc_jnz = ↑(inst.pc_jnz.to_nat) := h_flags _, have h2 := res_aux_agrees h_off_op0_tilde h_off_op1_tilde h_flags h_mem_op0_addr h_mem_op1_addr h_op0_addr h_op1_addr h_mul h_res, revert h2, rw [instruction.res, h1], cases inst.pc_jump_abs; cases inst.pc_jump_rel; cases inst.pc_jnz; simp [instruction.res._match_1, option.agrees], end end section include h_off_dst_tilde h_flags h_mem_dst_addr h_dst_addr theorem dst_eq : dst = inst.dst mem ⟨pc, ap, fp⟩ := begin have : f_tilde.f_dst_reg = ↑(inst.dst_reg.to_nat) := h_flags _, rw [instruction.dst, ←h_mem_dst_addr, h_dst_addr, h_off_dst_tilde, bitvec.to_biased_16, this], cases inst.dst_reg; simp end end section variable [decidable_eq F] include h_off_dst_tilde h_off_op0_tilde h_off_op1_tilde h_flags include h_mem_dst_addr h_mem_op0_addr h_mem_op1_addr include h_dst_addr h_op0_addr h_op1_addr h_mul h_res include h_t0_eq h_t1_eq h_next_pc_eq h_next_pc_eq' theorem next_pc_agrees : (inst.next_pc mem ⟨pc, ap, fp⟩).agrees next_pc := begin have h1 : f_tilde.f_pc_jump_abs = ↑(inst.pc_jump_abs.to_nat) := h_flags _, have h2 : f_tilde.f_pc_jump_rel = ↑(inst.pc_jump_rel.to_nat) := h_flags _, have h3 : f_tilde.f_pc_jnz = ↑(inst.pc_jnz.to_nat) := h_flags _, have h4 : f_tilde.f_dst_reg = ↑(inst.dst_reg.to_nat) := h_flags _, have h5 : f_tilde.f_res_mul = ↑(inst.res_mul.to_nat) := h_flags _, have h6 : f_tilde.f_res_add = ↑(inst.res_add.to_nat) := h_flags _, have h7 : f_tilde.f_op1_imm = ↑(inst.op1_imm.to_nat) := h_flags _, have h8 := @dst_eq _ _ _ _ _ _ pc _ _ _ _ h_off_dst_tilde h_flags h_mem_dst_addr h_dst_addr, have h9 := op1_agrees h_off_op0_tilde h_off_op1_tilde h_flags h_mem_op0_addr h_mem_op1_addr h_op0_addr h_op1_addr, have h10 := res_agrees h_off_op0_tilde h_off_op1_tilde h_flags h_mem_op0_addr h_mem_op1_addr h_op0_addr h_op1_addr h_mul h_res, rw h_t0_eq at h_t1_eq h_next_pc_eq', rw h_t1_eq at h_next_pc_eq, revert h_next_pc_eq h_next_pc_eq' , rw [instruction.next_pc, h1, h2, h3], cases inst.pc_jump_abs; cases inst.pc_jump_rel; cases inst.pc_jnz; simp [instruction.next_pc._match_1, option.agrees], { rw [instruction.size, h7], intro h, symmetry, exact eq_of_sub_eq_zero h }, { intros h_next_pc_eq h_next_pc_eq', by_cases h : inst.dst mem ⟨pc, ap, fp⟩ = 0, { rw [if_pos h], cases h_next_pc_eq with h' h', { simp [h8, h] at h', contradiction }, rw [option.agrees], rw h7 at h', symmetry, exact eq_of_sub_eq_zero h' }, cases h_next_pc_eq' with h' h', { rw h8 at h', contradiction }, { rw [if_neg h], revert h9, cases inst.op1 mem ⟨pc, ap, fp⟩; simp [option.agrees, instruction.next_pc._match_3], rintro rfl, symmetry, exact eq_of_sub_eq_zero h' } }, { revert h10, cases inst.res mem ⟨pc, ap, fp⟩; simp [option.agrees, instruction.next_pc._match_2], rintro rfl, intro h', symmetry, exact eq_of_sub_eq_zero h' }, { intro h, revert h10, cases inst.res mem ⟨pc, ap, fp⟩; simp [option.agrees], rintro rfl, symmetry, exact eq_of_sub_eq_zero h } end end section include h_off_op0_tilde h_off_op1_tilde h_flags include h_mem_op0_addr h_mem_op1_addr h_op0_addr h_op1_addr h_mul h_res h_next_ap theorem next_ap_agrees_aux (h : f_tilde.f_opcode_call = 0) : (inst.next_ap_aux mem ⟨pc, ap, fp⟩).agrees next_ap := begin have h1 : f_tilde.f_ap_add = ↑(inst.ap_add.to_nat) := h_flags _, have h2 : f_tilde.f_ap_add1 = ↑(inst.ap_add1.to_nat) := h_flags _, have h3 := res_agrees h_off_op0_tilde h_off_op1_tilde h_flags h_mem_op0_addr h_mem_op1_addr h_op0_addr h_op1_addr h_mul h_res, revert h_next_ap, rw [instruction.next_ap_aux, h1, h2, h], cases inst.ap_add; cases inst.ap_add1; simp [instruction.next_ap_aux._match_1, option.agrees]; intro h'; rw h', revert h3, cases inst.res mem ⟨pc, ap, fp⟩; simp [option.agrees, instruction.next_ap_aux._match_2] end end section include h_off_op0_tilde h_off_op1_tilde h_flags include h_mem_op0_addr h_mem_op1_addr include h_op0_addr h_op1_addr h_mul h_res h_next_ap theorem next_ap_agrees : (inst.next_ap mem ⟨pc, ap, fp⟩).agrees next_ap := begin have h1 : f_tilde.f_opcode_call = ↑(inst.opcode_call.to_nat) := h_flags _, have h2 : f_tilde.f_opcode_ret = ↑(inst.opcode_ret.to_nat) := h_flags _, have h3 : f_tilde.f_ap_add = ↑(inst.ap_add.to_nat) := h_flags _, have h4 : f_tilde.f_ap_add1 = ↑(inst.ap_add1.to_nat) := h_flags _, have h5 := next_ap_agrees_aux h_off_op0_tilde h_off_op1_tilde h_flags h_mem_op0_addr h_mem_op1_addr h_op0_addr h_op1_addr h_mul h_res h_next_ap, revert h5, rw [instruction.next_ap, h1], cases inst.opcode_call; cases inst.opcode_ret; cases inst.opcode_assert_eq; simp [instruction.next_ap._match_1, option.agrees], revert h_next_ap, rw [h1, h3, h4], cases inst.ap_add; cases inst.ap_add1; simp [instruction.next_ap._match_2, option.agrees], apply eq.symm end end section include h_off_dst_tilde h_flags h_mem_dst_addr h_dst_addr h_next_fp theorem next_fp_agrees : (inst.next_fp mem ⟨pc, ap, fp⟩).agrees next_fp := begin have h1 : f_tilde.f_opcode_call = ↑(inst.opcode_call.to_nat) := h_flags _, have h2 : f_tilde.f_opcode_ret = ↑(inst.opcode_ret.to_nat) := h_flags _, have h3 := @dst_eq _ _ _ _ _ _ pc _ _ _ _ h_off_dst_tilde h_flags h_mem_dst_addr h_dst_addr, revert next_fp, rw [instruction.next_fp, h1, h2], cases inst.opcode_call; cases inst.opcode_ret; cases inst.opcode_assert_eq; simp [instruction.next_fp._match_1, option.agrees, h3] end end section include h_off_dst_tilde h_off_op0_tilde h_off_op1_tilde h_flags include h_mem_dst_addr h_mem_op0_addr h_mem_op1_addr include h_dst_addr h_op0_addr h_op1_addr h_mul h_res include h_opcode_call h_opcode_call' h_opcode_assert_eq theorem asserts_hold : inst.asserts mem ⟨pc, ap, fp⟩ := begin have h1 : f_tilde.f_opcode_call = ↑(inst.opcode_call.to_nat) := h_flags _, have h2 : f_tilde.f_opcode_ret = ↑(inst.opcode_ret.to_nat) := h_flags _, have h3 : f_tilde.f_opcode_assert_eq = ↑(inst.opcode_assert_eq.to_nat) := h_flags _, have h4 : f_tilde.f_op1_imm = ↑(inst.op1_imm.to_nat) := h_flags _, have h5 := @dst_eq _ _ _ _ _ _ pc _ _ _ _ h_off_dst_tilde h_flags h_mem_dst_addr h_dst_addr, have h6 := @op0_eq _ _ _ _ _ _ pc _ _ _ _ h_off_op0_tilde h_flags h_mem_op0_addr h_op0_addr, have h7 := res_agrees h_off_op0_tilde h_off_op1_tilde h_flags h_mem_op0_addr h_mem_op1_addr h_op0_addr h_op1_addr h_mul h_res, revert h_opcode_call h_opcode_call' h_opcode_assert_eq, rw [instruction.asserts, h1, h3], cases inst.opcode_call; cases inst.opcode_ret; cases inst.opcode_assert_eq; simp [instruction.asserts._match_1, option.agrees, h3, ←h5, ←h6]; intro h; rw [eq_of_sub_eq_zero h], { exact h7 }, { simp [instruction.size, h4], intro h; rw [eq_of_sub_eq_zero h] } end end /- The main theorem: the constraints imply that the next state is as expected. -/ variable [decidable_eq F] theorem next_state_eq : next_state mem ⟨pc, ap, fp⟩ ⟨next_pc, next_ap, next_fp⟩ := ⟨ inst, h_mem_pc, next_pc_agrees h_off_dst_tilde h_off_op0_tilde h_off_op1_tilde h_flags h_mem_dst_addr h_mem_op0_addr h_mem_op1_addr h_dst_addr h_op0_addr h_op1_addr h_mul h_res h_t0_eq h_t1_eq h_next_pc_eq h_next_pc_eq', next_ap_agrees h_off_op0_tilde h_off_op1_tilde h_flags h_mem_op0_addr h_mem_op1_addr h_op0_addr h_op1_addr h_mul h_res h_next_ap, next_fp_agrees h_off_dst_tilde h_flags h_mem_dst_addr h_dst_addr h_next_fp, asserts_hold h_off_dst_tilde h_off_op0_tilde h_off_op1_tilde h_flags h_mem_dst_addr h_mem_op0_addr h_mem_op1_addr h_dst_addr h_op0_addr h_op1_addr h_mul h_res h_opcode_call h_opcode_call' h_opcode_assert_eq ⟩ -- We can use the linter to confirm that there are no extraneous dependencies. -- #lint
b2929865d734c2871947296bee48b0e384d35882
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Lean/Compiler/IR/ExpandResetReuse.lean
e49ca410536162e9a8f868fb91c60930580a1ffe
[ "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
9,855
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.Compiler.IR.CompilerM import Lean.Compiler.IR.NormIds import Lean.Compiler.IR.FreeVars namespace Lean.IR.ExpandResetReuse /-- Mapping from variable to projections -/ abbrev ProjMap := Std.HashMap VarId Expr namespace CollectProjMap abbrev Collector := ProjMap → ProjMap @[inline] def collectVDecl (x : VarId) (v : Expr) : Collector := fun m => match v with | .proj .. => m.insert x v | .sproj .. => m.insert x v | .uproj .. => m.insert x v | _ => m partial def collectFnBody : FnBody → Collector | .vdecl x _ v b => collectVDecl x v ∘ collectFnBody b | .jdecl _ _ v b => collectFnBody v ∘ collectFnBody b | .case _ _ _ alts => fun s => alts.foldl (fun s alt => collectFnBody alt.body s) s | e => if e.isTerminal then id else collectFnBody e.body end CollectProjMap /-- Create a mapping from variables to projections. This function assumes variable ids have been normalized -/ def mkProjMap (d : Decl) : ProjMap := match d with | .fdecl (body := b) .. => CollectProjMap.collectFnBody b {} | _ => {} structure Context where projMap : ProjMap /-- Return true iff `x` is consumed in all branches of the current block. Here consumption means the block contains a `dec x` or `reuse x ...`. -/ partial def consumed (x : VarId) : FnBody → Bool | .vdecl _ _ v b => match v with | Expr.reuse y _ _ _ => x == y || consumed x b | _ => consumed x b | .dec y _ _ _ b => x == y || consumed x b | .case _ _ _ alts => alts.all fun alt => consumed x alt.body | e => !e.isTerminal && consumed x e.body abbrev Mask := Array (Option VarId) /-- Auxiliary function for eraseProjIncFor -/ partial def eraseProjIncForAux (y : VarId) (bs : Array FnBody) (mask : Mask) (keep : Array FnBody) : Array FnBody × Mask := let done (_ : Unit) := (bs ++ keep.reverse, mask) let keepInstr (b : FnBody) := eraseProjIncForAux y bs.pop mask (keep.push b) if bs.size < 2 then done () else let b := bs.back match b with | .vdecl _ _ (.sproj _ _ _) _ => keepInstr b | .vdecl _ _ (.uproj _ _) _ => keepInstr b | .inc z n c p _ => if n == 0 then done () else let b' := bs[bs.size - 2]! match b' with | .vdecl w _ (.proj i x) _ => if w == z && y == x then /- Found ``` let z := proj[i] y inc z n c ``` We keep `proj`, and `inc` when `n > 1` -/ let bs := bs.pop.pop let mask := mask.set! i (some z) let keep := keep.push b' let keep := if n == 1 then keep else keep.push (FnBody.inc z (n-1) c p FnBody.nil) eraseProjIncForAux y bs mask keep else done () | _ => done () | _ => done () /-- Try to erase `inc` instructions on projections of `y` occurring in the tail of `bs`. Return the updated `bs` and a bit mask specifying which `inc`s have been removed. -/ def eraseProjIncFor (n : Nat) (y : VarId) (bs : Array FnBody) : Array FnBody × Mask := eraseProjIncForAux y bs (mkArray n none) #[] /-- Replace `reuse x ctor ...` with `ctor ...`, and remoce `dec x` -/ partial def reuseToCtor (x : VarId) : FnBody → FnBody | FnBody.dec y n c p b => if x == y then b -- n must be 1 since `x := reset ...` else FnBody.dec y n c p (reuseToCtor x b) | FnBody.vdecl z t v b => match v with | Expr.reuse y c _ xs => if x == y then FnBody.vdecl z t (Expr.ctor c xs) b else FnBody.vdecl z t v (reuseToCtor x b) | _ => FnBody.vdecl z t v (reuseToCtor x b) | FnBody.case tid y yType alts => let alts := alts.map fun alt => alt.modifyBody (reuseToCtor x) FnBody.case tid y yType alts | e => if e.isTerminal then e else let (instr, b) := e.split let b := reuseToCtor x b instr.setBody b /-- replace ``` x := reset y; b ``` with ``` inc z_1; ...; inc z_i; dec y; b' ``` where `z_i`'s are the variables in `mask`, and `b'` is `b` where we removed `dec x` and replaced `reuse x ctor_i ...` with `ctor_i ...`. -/ def mkSlowPath (x y : VarId) (mask : Mask) (b : FnBody) : FnBody := let b := reuseToCtor x b let b := FnBody.dec y 1 true false b mask.foldl (init := b) fun b m => match m with | some z => FnBody.inc z 1 true false b | none => b abbrev M := ReaderT Context (StateM Nat) def mkFresh : M VarId := modifyGet fun n => ({ idx := n }, n + 1) def releaseUnreadFields (y : VarId) (mask : Mask) (b : FnBody) : M FnBody := mask.size.foldM (init := b) fun i b => match mask.get! i with | some _ => pure b -- code took ownership of this field | none => do let fld ← mkFresh pure (FnBody.vdecl fld IRType.object (Expr.proj i y) (FnBody.dec fld 1 true false b)) def setFields (y : VarId) (zs : Array Arg) (b : FnBody) : FnBody := zs.size.fold (init := b) fun i b => FnBody.set y i (zs.get! i) b /-- Given `set x[i] := y`, return true iff `y := proj[i] x` -/ def isSelfSet (ctx : Context) (x : VarId) (i : Nat) (y : Arg) : Bool := match y with | Arg.var y => match ctx.projMap.find? y with | some (Expr.proj j w) => j == i && w == x | _ => false | _ => false /-- Given `uset x[i] := y`, return true iff `y := uproj[i] x` -/ def isSelfUSet (ctx : Context) (x : VarId) (i : Nat) (y : VarId) : Bool := match ctx.projMap.find? y with | some (Expr.uproj j w) => j == i && w == x | _ => false /-- Given `sset x[n, i] := y`, return true iff `y := sproj[n, i] x` -/ def isSelfSSet (ctx : Context) (x : VarId) (n : Nat) (i : Nat) (y : VarId) : Bool := match ctx.projMap.find? y with | some (Expr.sproj m j w) => n == m && j == i && w == x | _ => false /-- Remove unnecessary `set/uset/sset` operations -/ partial def removeSelfSet (ctx : Context) : FnBody → FnBody | FnBody.set x i y b => if isSelfSet ctx x i y then removeSelfSet ctx b else FnBody.set x i y (removeSelfSet ctx b) | FnBody.uset x i y b => if isSelfUSet ctx x i y then removeSelfSet ctx b else FnBody.uset x i y (removeSelfSet ctx b) | FnBody.sset x n i y t b => if isSelfSSet ctx x n i y then removeSelfSet ctx b else FnBody.sset x n i y t (removeSelfSet ctx b) | FnBody.case tid y yType alts => let alts := alts.map fun alt => alt.modifyBody (removeSelfSet ctx) FnBody.case tid y yType alts | e => if e.isTerminal then e else let (instr, b) := e.split let b := removeSelfSet ctx b instr.setBody b partial def reuseToSet (ctx : Context) (x y : VarId) : FnBody → FnBody | FnBody.dec z n c p b => if x == z then FnBody.del y b else FnBody.dec z n c p (reuseToSet ctx x y b) | FnBody.vdecl z t v b => match v with | Expr.reuse w c u zs => if x == w then let b := setFields y zs (b.replaceVar z y) let b := if u then FnBody.setTag y c.cidx b else b removeSelfSet ctx b else FnBody.vdecl z t v (reuseToSet ctx x y b) | _ => FnBody.vdecl z t v (reuseToSet ctx x y b) | FnBody.case tid z zType alts => let alts := alts.map fun alt => alt.modifyBody (reuseToSet ctx x y) FnBody.case tid z zType alts | e => if e.isTerminal then e else let (instr, b) := e.split let b := reuseToSet ctx x y b instr.setBody b /-- replace ``` x := reset y; b ``` with ``` let f_i_1 := proj[i_1] y; ... let f_i_k := proj[i_k] y; b' ``` where `i_j`s are the field indexes that the code did not touch immediately before the reset. That is `mask[j] == none`. `b'` is `b` where `y` `dec x` is replaced with `del y`, and `z := reuse x ctor_i ws; F` is replaced with `set x i ws[i]` operations, and we replace `z` with `x` in `F` -/ def mkFastPath (x y : VarId) (mask : Mask) (b : FnBody) : M FnBody := do let ctx ← read let b := reuseToSet ctx x y b releaseUnreadFields y mask b -- Expand `bs; x := reset[n] y; b` partial def expand (mainFn : FnBody → Array FnBody → M FnBody) (bs : Array FnBody) (x : VarId) (n : Nat) (y : VarId) (b : FnBody) : M FnBody := do let (bs, mask) := eraseProjIncFor n y bs /- Remark: we may be duplicting variable/JP indices. That is, `bSlow` and `bFast` may have duplicate indices. We run `normalizeIds` to fix the ids after we have expand them. -/ let bSlow := mkSlowPath x y mask b let bFast ← mkFastPath x y mask b /- We only optimize recursively the fast. -/ let bFast ← mainFn bFast #[] let c ← mkFresh let b := FnBody.vdecl c IRType.uint8 (Expr.isShared y) (mkIf c bSlow bFast) return reshape bs b partial def searchAndExpand : FnBody → Array FnBody → M FnBody | d@(FnBody.vdecl x _ (Expr.reset n y) b), bs => if consumed x b then do expand searchAndExpand bs x n y b else searchAndExpand b (push bs d) | FnBody.jdecl j xs v b, bs => do let v ← searchAndExpand v #[] searchAndExpand b (push bs (FnBody.jdecl j xs v FnBody.nil)) | FnBody.case tid x xType alts, bs => do let alts ← alts.mapM fun alt => alt.mmodifyBody fun b => searchAndExpand b #[] return reshape bs (FnBody.case tid x xType alts) | b, bs => if b.isTerminal then return reshape bs b else searchAndExpand b.body (push bs b) def main (d : Decl) : Decl := match d with | .fdecl (body := b) .. => let m := mkProjMap d let nextIdx := d.maxIndex + 1 let bNew := (searchAndExpand b #[] { projMap := m }).run' nextIdx d.updateBody! bNew | d => d end ExpandResetReuse /-- (Try to) expand `reset` and `reuse` instructions. -/ def Decl.expandResetReuse (d : Decl) : Decl := (ExpandResetReuse.main d).normalizeIds end Lean.IR
dfa5e026aeabb3c93bfb1f84f1bd1510ad35ae69
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/string/basic.lean
11b9289d66277902a748e41a19902878098d21d9
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
4,610
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.list.lex import data.char /-! # Strings > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Supplementary theorems about the `string` type. -/ namespace string /-- `<` on string iterators. This coincides with `<` on strings as lists. -/ def ltb : iterator → iterator → bool | s₁ s₂ := begin cases s₂.has_next, {exact ff}, cases h₁ : s₁.has_next, {exact tt}, exact if s₁.curr = s₂.curr then have s₁.next.2.length < s₁.2.length, from match s₁, h₁ with ⟨_, a::l⟩, h := nat.lt_succ_self _ end, ltb s₁.next s₂.next else s₁.curr < s₂.curr, end using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ s, s.1.2.length)⟩]} instance has_lt' : has_lt string := ⟨λ s₁ s₂, ltb s₁.mk_iterator s₂.mk_iterator⟩ instance decidable_lt : @decidable_rel string (<) := by apply_instance -- short-circuit type class inference @[simp] theorem lt_iff_to_list_lt : ∀ {s₁ s₂ : string}, s₁ < s₂ ↔ s₁.to_list < s₂.to_list | ⟨i₁⟩ ⟨i₂⟩ := suffices ∀ {p₁ p₂ s₁ s₂}, ltb ⟨p₁, s₁⟩ ⟨p₂, s₂⟩ ↔ s₁ < s₂, from this, begin intros, induction s₁ with a s₁ IH generalizing p₁ p₂ s₂; cases s₂ with b s₂; rw ltb; simp [iterator.has_next], { refl, }, { exact iff_of_true rfl list.lex.nil }, { exact iff_of_false bool.ff_ne_tt (not_lt_of_lt list.lex.nil) }, { dsimp [iterator.has_next, iterator.curr, iterator.next], split_ifs, { subst b, exact IH.trans list.lex.cons_iff.symm }, { simp, refine ⟨list.lex.rel, λ e, _⟩, cases e, {cases h rfl}, assumption } } end instance has_le : has_le string := ⟨λ s₁ s₂, ¬ s₂ < s₁⟩ instance decidable_le : @decidable_rel string (≤) := by apply_instance -- short-circuit type class inference @[simp] theorem le_iff_to_list_le {s₁ s₂ : string} : s₁ ≤ s₂ ↔ s₁.to_list ≤ s₂.to_list := (not_congr lt_iff_to_list_lt).trans not_lt theorem to_list_inj : ∀ {s₁ s₂}, to_list s₁ = to_list s₂ ↔ s₁ = s₂ | ⟨s₁⟩ ⟨s₂⟩ := ⟨congr_arg _, congr_arg _⟩ lemma nil_as_string_eq_empty : [].as_string = "" := rfl @[simp] lemma to_list_empty : "".to_list = [] := rfl lemma as_string_inv_to_list (s : string) : s.to_list.as_string = s := by { cases s, refl } @[simp] lemma to_list_singleton (c : char) : (string.singleton c).to_list = [c] := rfl lemma to_list_nonempty : ∀ {s : string}, s ≠ string.empty → s.to_list = s.head :: (s.popn 1).to_list | ⟨s⟩ h := by cases s; [cases h rfl, refl] @[simp] lemma head_empty : "".head = default := rfl @[simp] lemma popn_empty {n : ℕ} : "".popn n = "" := begin induction n with n hn, { refl }, { rcases hs : "" with ⟨_ | ⟨hd, tl⟩⟩, { rw hs at hn, conv_rhs { rw ←hn }, simp only [popn, mk_iterator, iterator.nextn, iterator.next] }, { simpa only [←to_list_inj] using hs } } end instance : linear_order string := { lt := (<), le := (≤), decidable_lt := by apply_instance, decidable_le := string.decidable_le, decidable_eq := by apply_instance, le_refl := λ a, le_iff_to_list_le.2 le_rfl, le_trans := λ a b c, by { simp only [le_iff_to_list_le], exact λ h₁ h₂, h₁.trans h₂ }, le_total := λ a b, by { simp only [le_iff_to_list_le], exact le_total _ _ }, le_antisymm := λ a b, by { simp only [le_iff_to_list_le, ← to_list_inj], apply le_antisymm }, lt_iff_le_not_le := λ a b, by simp only [le_iff_to_list_le, lt_iff_to_list_lt, lt_iff_le_not_le] } end string open string lemma list.to_list_inv_as_string (l : list char) : l.as_string.to_list = l := by { cases hl : l.as_string, exact string_imp.mk.inj hl.symm } @[simp] lemma list.length_as_string (l : list char) : l.as_string.length = l.length := rfl @[simp] lemma list.as_string_inj {l l' : list char} : l.as_string = l'.as_string ↔ l = l' := ⟨λ h, by rw [←list.to_list_inv_as_string l, ←list.to_list_inv_as_string l', to_list_inj, h], λ h, h ▸ rfl⟩ @[simp] lemma string.length_to_list (s : string) : s.to_list.length = s.length := by rw [←string.as_string_inv_to_list s, list.to_list_inv_as_string, list.length_as_string] lemma list.as_string_eq {l : list char} {s : string} : l.as_string = s ↔ l = s.to_list := by rw [←as_string_inv_to_list s, list.as_string_inj, as_string_inv_to_list s]
035fc1f36e62a399b065d763cf7ccd6ee6cfcd80
9dc8cecdf3c4634764a18254e94d43da07142918
/src/number_theory/arithmetic_function.lean
80539f7af0fc3b0f1863c4607a8fcd455146d6c4
[ "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
37,411
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import algebra.big_operators.ring import number_theory.divisors import data.nat.squarefree import algebra.invertible import data.nat.factorization.basic /-! # Arithmetic Functions and Dirichlet Convolution This file defines arithmetic functions, which are functions from `ℕ` to a specified type that map 0 to 0. In the literature, they are often instead defined as functions from `ℕ+`. These arithmetic functions are endowed with a multiplication, given by Dirichlet convolution, and pointwise addition, to form the Dirichlet ring. ## Main Definitions * `arithmetic_function R` consists of functions `f : ℕ → R` such that `f 0 = 0`. * An arithmetic function `f` `is_multiplicative` when `x.coprime y → f (x * y) = f x * f y`. * The pointwise operations `pmul` and `ppow` differ from the multiplication and power instances on `arithmetic_function R`, which use Dirichlet multiplication. * `ζ` is the arithmetic function such that `ζ x = 1` for `0 < x`. * `σ k` is the arithmetic function such that `σ k x = ∑ y in divisors x, y ^ k` for `0 < x`. * `pow k` is the arithmetic function such that `pow k x = x ^ k` for `0 < x`. * `id` is the identity arithmetic function on `ℕ`. * `ω n` is the number of distinct prime factors of `n`. * `Ω n` is the number of prime factors of `n` counted with multiplicity. * `μ` is the Möbius function (spelled `moebius` in code). ## Main Results * Several forms of Möbius inversion: * `sum_eq_iff_sum_mul_moebius_eq` for functions to a `comm_ring` * `sum_eq_iff_sum_smul_moebius_eq` for functions to an `add_comm_group` * `prod_eq_iff_prod_pow_moebius_eq` for functions to a `comm_group` * `prod_eq_iff_prod_pow_moebius_eq_of_nonzero` for functions to a `comm_group_with_zero` ## Notation The arithmetic functions `ζ` and `σ` have Greek letter names, which are localized notation in the namespace `arithmetic_function`. ## Tags arithmetic functions, dirichlet convolution, divisors -/ open finset open_locale big_operators namespace nat variable (R : Type*) /-- An arithmetic function is a function from `ℕ` that maps 0 to 0. In the literature, they are often instead defined as functions from `ℕ+`. Multiplication on `arithmetic_functions` is by Dirichlet convolution. -/ @[derive [has_zero, inhabited]] def arithmetic_function [has_zero R] := zero_hom ℕ R variable {R} namespace arithmetic_function section has_zero variable [has_zero R] instance : has_coe_to_fun (arithmetic_function R) (λ _, ℕ → R) := zero_hom.has_coe_to_fun @[simp] lemma to_fun_eq (f : arithmetic_function R) : f.to_fun = f := rfl @[simp] lemma map_zero {f : arithmetic_function R} : f 0 = 0 := zero_hom.map_zero' f theorem coe_inj {f g : arithmetic_function R} : (f : ℕ → R) = g ↔ f = g := ⟨λ h, zero_hom.coe_inj h, λ h, h ▸ rfl⟩ @[simp] lemma zero_apply {x : ℕ} : (0 : arithmetic_function R) x = 0 := zero_hom.zero_apply x @[ext] theorem ext ⦃f g : arithmetic_function R⦄ (h : ∀ x, f x = g x) : f = g := zero_hom.ext h theorem ext_iff {f g : arithmetic_function R} : f = g ↔ ∀ x, f x = g x := zero_hom.ext_iff section has_one variable [has_one R] instance : has_one (arithmetic_function R) := ⟨⟨λ x, ite (x = 1) 1 0, rfl⟩⟩ lemma one_apply {x : ℕ} : (1 : arithmetic_function R) x = ite (x = 1) 1 0 := rfl @[simp] lemma one_one : (1 : arithmetic_function R) 1 = 1 := rfl @[simp] lemma one_apply_ne {x : ℕ} (h : x ≠ 1) : (1 : arithmetic_function R) x = 0 := if_neg h end has_one end has_zero instance nat_coe [add_monoid_with_one R] : has_coe (arithmetic_function ℕ) (arithmetic_function R) := ⟨λ f, ⟨↑(f : ℕ → ℕ), by { transitivity ↑(f 0), refl, simp }⟩⟩ @[simp] lemma nat_coe_nat (f : arithmetic_function ℕ) : (↑f : arithmetic_function ℕ) = f := ext $ λ _, cast_id _ @[simp] lemma nat_coe_apply [add_monoid_with_one R] {f : arithmetic_function ℕ} {x : ℕ} : (f : arithmetic_function R) x = f x := rfl instance int_coe [add_group_with_one R] : has_coe (arithmetic_function ℤ) (arithmetic_function R) := ⟨λ f, ⟨↑(f : ℕ → ℤ), by { transitivity ↑(f 0), refl, simp }⟩⟩ @[simp] lemma int_coe_int (f : arithmetic_function ℤ) : (↑f : arithmetic_function ℤ) = f := ext $ λ _, int.cast_id _ @[simp] lemma int_coe_apply [add_group_with_one R] {f : arithmetic_function ℤ} {x : ℕ} : (f : arithmetic_function R) x = f x := rfl @[simp] lemma coe_coe [add_group_with_one R] {f : arithmetic_function ℕ} : ((f : arithmetic_function ℤ) : arithmetic_function R) = f := by { ext, simp, } @[simp] lemma nat_coe_one [add_monoid_with_one R] : ((1 : arithmetic_function ℕ) : arithmetic_function R) = 1 := by { ext n, simp [one_apply] } @[simp] lemma int_coe_one [add_group_with_one R] : ((1 : arithmetic_function ℤ) : arithmetic_function R) = 1 := by { ext n, simp [one_apply] } section add_monoid variable [add_monoid R] instance : has_add (arithmetic_function R) := ⟨λ f g, ⟨λ n, f n + g n, by simp⟩⟩ @[simp] lemma add_apply {f g : arithmetic_function R} {n : ℕ} : (f + g) n = f n + g n := rfl instance : add_monoid (arithmetic_function R) := { add_assoc := λ _ _ _, ext (λ _, add_assoc _ _ _), zero_add := λ _, ext (λ _, zero_add _), add_zero := λ _, ext (λ _, add_zero _), .. arithmetic_function.has_zero R, .. arithmetic_function.has_add } end add_monoid instance [add_monoid_with_one R] : add_monoid_with_one (arithmetic_function R) := { nat_cast := λ n, ⟨λ x, if x = 1 then (n : R) else 0, by simp⟩, nat_cast_zero := by ext; simp [nat.cast], nat_cast_succ := λ _, by ext; by_cases x = 1; simp [nat.cast, *], .. arithmetic_function.add_monoid, .. arithmetic_function.has_one } instance [add_comm_monoid R] : add_comm_monoid (arithmetic_function R) := { add_comm := λ _ _, ext (λ _, add_comm _ _), .. arithmetic_function.add_monoid } instance [add_group R] : add_group (arithmetic_function R) := { neg := λ f, ⟨λ n, - f n, by simp⟩, add_left_neg := λ _, ext (λ _, add_left_neg _), .. arithmetic_function.add_monoid } instance [add_comm_group R] : add_comm_group (arithmetic_function R) := { .. arithmetic_function.add_comm_monoid, .. arithmetic_function.add_group } section has_smul variables {M : Type*} [has_zero R] [add_comm_monoid M] [has_smul R M] /-- The Dirichlet convolution of two arithmetic functions `f` and `g` is another arithmetic function such that `(f * g) n` is the sum of `f x * g y` over all `(x,y)` such that `x * y = n`. -/ instance : has_smul (arithmetic_function R) (arithmetic_function M) := ⟨λ f g, ⟨λ n, ∑ x in divisors_antidiagonal n, f x.fst • g x.snd, by simp⟩⟩ @[simp] lemma smul_apply {f : arithmetic_function R} {g : arithmetic_function M} {n : ℕ} : (f • g) n = ∑ x in divisors_antidiagonal n, f x.fst • g x.snd := rfl end has_smul /-- The Dirichlet convolution of two arithmetic functions `f` and `g` is another arithmetic function such that `(f * g) n` is the sum of `f x * g y` over all `(x,y)` such that `x * y = n`. -/ instance [semiring R] : has_mul (arithmetic_function R) := ⟨(•)⟩ @[simp] lemma mul_apply [semiring R] {f g : arithmetic_function R} {n : ℕ} : (f * g) n = ∑ x in divisors_antidiagonal n, f x.fst * g x.snd := rfl lemma mul_apply_one [semiring R] {f g : arithmetic_function R} : (f * g) 1 = f 1 * g 1 := by simp @[simp, norm_cast] lemma nat_coe_mul [semiring R] {f g : arithmetic_function ℕ} : (↑(f * g) : arithmetic_function R) = f * g := by { ext n, simp } @[simp, norm_cast] lemma int_coe_mul [ring R] {f g : arithmetic_function ℤ} : (↑(f * g) : arithmetic_function R) = f * g := by { ext n, simp } section module variables {M : Type*} [semiring R] [add_comm_monoid M] [module R M] lemma mul_smul' (f g : arithmetic_function R) (h : arithmetic_function M) : (f * g) • h = f • g • h := begin ext n, simp only [mul_apply, smul_apply, sum_smul, mul_smul, smul_sum, finset.sum_sigma'], apply finset.sum_bij, swap 5, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, exact ⟨(k, l*j), (l, j)⟩ }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, simp only [finset.mem_sigma, mem_divisors_antidiagonal] at H ⊢, rcases H with ⟨⟨rfl, n0⟩, rfl, i0⟩, refine ⟨⟨(mul_assoc _ _ _).symm, n0⟩, rfl, _⟩, rw mul_ne_zero_iff at *, exact ⟨i0.2, n0.2⟩, }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, simp only [mul_assoc] }, { rintros ⟨⟨a,b⟩, ⟨c,d⟩⟩ ⟨⟨i,j⟩, ⟨k,l⟩⟩ H₁ H₂, simp only [finset.mem_sigma, mem_divisors_antidiagonal, and_imp, prod.mk.inj_iff, add_comm, heq_iff_eq] at H₁ H₂ ⊢, rintros rfl h2 rfl rfl, exact ⟨⟨eq.trans H₁.2.1.symm H₂.2.1, rfl⟩, rfl, rfl⟩ }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, refine ⟨⟨(i*k, l), (i, k)⟩, _, _⟩, { simp only [finset.mem_sigma, mem_divisors_antidiagonal] at H ⊢, rcases H with ⟨⟨rfl, n0⟩, rfl, j0⟩, refine ⟨⟨mul_assoc _ _ _, n0⟩, rfl, _⟩, rw mul_ne_zero_iff at *, exact ⟨n0.1, j0.1⟩ }, { simp only [true_and, mem_divisors_antidiagonal, and_true, prod.mk.inj_iff, eq_self_iff_true, ne.def, mem_sigma, heq_iff_eq] at H ⊢, rw H.2.1 } } end lemma one_smul' (b : arithmetic_function M) : (1 : arithmetic_function R) • b = b := begin ext, rw smul_apply, by_cases x0 : x = 0, {simp [x0]}, have h : {(1,x)} ⊆ divisors_antidiagonal x := by simp [x0], rw ← sum_subset h, {simp}, intros y ymem ynmem, have y1ne : y.fst ≠ 1, { intro con, simp only [con, mem_divisors_antidiagonal, one_mul, ne.def] at ymem, simp only [mem_singleton, prod.ext_iff] at ynmem, tauto }, simp [y1ne], end end module section semiring variable [semiring R] instance : monoid (arithmetic_function R) := { one_mul := one_smul', mul_one := λ f, begin ext, rw mul_apply, by_cases x0 : x = 0, {simp [x0]}, have h : {(x,1)} ⊆ divisors_antidiagonal x := by simp [x0], rw ← sum_subset h, {simp}, intros y ymem ynmem, have y2ne : y.snd ≠ 1, { intro con, simp only [con, mem_divisors_antidiagonal, mul_one, ne.def] at ymem, simp only [mem_singleton, prod.ext_iff] at ynmem, tauto }, simp [y2ne], end, mul_assoc := mul_smul', .. arithmetic_function.has_one, .. arithmetic_function.has_mul } instance : semiring (arithmetic_function R) := { zero_mul := λ f, by { ext, simp only [mul_apply, zero_mul, sum_const_zero, zero_apply] }, mul_zero := λ f, by { ext, simp only [mul_apply, sum_const_zero, mul_zero, zero_apply] }, left_distrib := λ a b c, by { ext, simp only [←sum_add_distrib, mul_add, mul_apply, add_apply] }, right_distrib := λ a b c, by { ext, simp only [←sum_add_distrib, add_mul, mul_apply, add_apply] }, .. arithmetic_function.has_zero R, .. arithmetic_function.has_mul, .. arithmetic_function.has_add, .. arithmetic_function.add_comm_monoid, .. arithmetic_function.add_monoid_with_one, .. arithmetic_function.monoid } end semiring instance [comm_semiring R] : comm_semiring (arithmetic_function R) := { mul_comm := λ f g, by { ext, rw [mul_apply, ← map_swap_divisors_antidiagonal, sum_map], simp [mul_comm] }, .. arithmetic_function.semiring } instance [comm_ring R] : comm_ring (arithmetic_function R) := { .. arithmetic_function.add_comm_group, .. arithmetic_function.comm_semiring } instance {M : Type*} [semiring R] [add_comm_monoid M] [module R M] : module (arithmetic_function R) (arithmetic_function M) := { one_smul := one_smul', mul_smul := mul_smul', smul_add := λ r x y, by { ext, simp only [sum_add_distrib, smul_add, smul_apply, add_apply] }, smul_zero := λ r, by { ext, simp only [smul_apply, sum_const_zero, smul_zero, zero_apply] }, add_smul := λ r s x, by { ext, simp only [add_smul, sum_add_distrib, smul_apply, add_apply] }, zero_smul := λ r, by { ext, simp only [smul_apply, sum_const_zero, zero_smul, zero_apply] }, } section zeta /-- `ζ 0 = 0`, otherwise `ζ x = 1`. The Dirichlet Series is the Riemann ζ. -/ def zeta : arithmetic_function ℕ := ⟨λ x, ite (x = 0) 0 1, rfl⟩ localized "notation (name := arithmetic_function.zeta) `ζ` := nat.arithmetic_function.zeta" in arithmetic_function @[simp] lemma zeta_apply {x : ℕ} : ζ x = if (x = 0) then 0 else 1 := rfl lemma zeta_apply_ne {x : ℕ} (h : x ≠ 0) : ζ x = 1 := if_neg h @[simp] theorem coe_zeta_mul_apply [semiring R] {f : arithmetic_function R} {x : ℕ} : (↑ζ * f) x = ∑ i in divisors x, f i := begin rw mul_apply, transitivity ∑ i in divisors_antidiagonal x, f i.snd, { apply sum_congr rfl, intros i hi, rcases mem_divisors_antidiagonal.1 hi with ⟨rfl, h⟩, rw [nat_coe_apply, zeta_apply_ne (left_ne_zero_of_mul h), cast_one, one_mul] }, { apply sum_bij (λ i h, prod.snd i), { rintros ⟨a, b⟩ h, simp [snd_mem_divisors_of_mem_antidiagonal h] }, { rintros ⟨a, b⟩ h, refl }, { rintros ⟨a1, b1⟩ ⟨a2, b2⟩ h1 h2 h, dsimp at h, rw h at *, rw mem_divisors_antidiagonal at *, ext, swap, {refl}, simp only [prod.fst, prod.snd] at *, apply nat.eq_of_mul_eq_mul_right _ (eq.trans h1.1 h2.1.symm), rcases h1 with ⟨rfl, h⟩, apply nat.pos_of_ne_zero (right_ne_zero_of_mul h) }, { intros a ha, rcases mem_divisors.1 ha with ⟨⟨b, rfl⟩, ne0⟩, use (b, a), simp [ne0, mul_comm] } } end theorem coe_zeta_smul_apply {M : Type*} [comm_ring R] [add_comm_group M] [module R M] {f : arithmetic_function M} {x : ℕ} : ((↑ζ : arithmetic_function R) • f) x = ∑ i in divisors x, f i := begin rw smul_apply, transitivity ∑ i in divisors_antidiagonal x, f i.snd, { apply sum_congr rfl, intros i hi, rcases mem_divisors_antidiagonal.1 hi with ⟨rfl, h⟩, rw [nat_coe_apply, zeta_apply_ne (left_ne_zero_of_mul h), cast_one, one_smul] }, { apply sum_bij (λ i h, prod.snd i), { rintros ⟨a, b⟩ h, simp [snd_mem_divisors_of_mem_antidiagonal h] }, { rintros ⟨a, b⟩ h, refl }, { rintros ⟨a1, b1⟩ ⟨a2, b2⟩ h1 h2 h, dsimp at h, rw h at *, rw mem_divisors_antidiagonal at *, ext, swap, {refl}, simp only [prod.fst, prod.snd] at *, apply nat.eq_of_mul_eq_mul_right _ (eq.trans h1.1 h2.1.symm), rcases h1 with ⟨rfl, h⟩, apply nat.pos_of_ne_zero (right_ne_zero_of_mul h) }, { intros a ha, rcases mem_divisors.1 ha with ⟨⟨b, rfl⟩, ne0⟩, use (b, a), simp [ne0, mul_comm] } } end @[simp] theorem coe_mul_zeta_apply [semiring R] {f : arithmetic_function R} {x : ℕ} : (f * ζ) x = ∑ i in divisors x, f i := begin apply mul_opposite.op_injective, rw [op_sum], convert @coe_zeta_mul_apply Rᵐᵒᵖ _ { to_fun := mul_opposite.op ∘ f, map_zero' := by simp} x, rw [mul_apply, mul_apply, op_sum], conv_lhs { rw ← map_swap_divisors_antidiagonal, }, rw sum_map, apply sum_congr rfl, intros y hy, by_cases h1 : y.fst = 0, { simp [function.comp_apply, h1] }, { simp only [h1, mul_one, one_mul, prod.fst_swap, function.embedding.coe_fn_mk, prod.snd_swap, if_false, zeta_apply, zero_hom.coe_mk, nat_coe_apply, cast_one] } end theorem zeta_mul_apply {f : arithmetic_function ℕ} {x : ℕ} : (ζ * f) x = ∑ i in divisors x, f i := by rw [← nat_coe_nat ζ, coe_zeta_mul_apply] theorem mul_zeta_apply {f : arithmetic_function ℕ} {x : ℕ} : (f * ζ) x = ∑ i in divisors x, f i := by rw [← nat_coe_nat ζ, coe_mul_zeta_apply] end zeta open_locale arithmetic_function section pmul /-- This is the pointwise product of `arithmetic_function`s. -/ def pmul [mul_zero_class R] (f g : arithmetic_function R) : arithmetic_function R := ⟨λ x, f x * g x, by simp⟩ @[simp] lemma pmul_apply [mul_zero_class R] {f g : arithmetic_function R} {x : ℕ} : f.pmul g x = f x * g x := rfl lemma pmul_comm [comm_monoid_with_zero R] (f g : arithmetic_function R) : f.pmul g = g.pmul f := by { ext, simp [mul_comm] } section non_assoc_semiring variable [non_assoc_semiring R] @[simp] lemma pmul_zeta (f : arithmetic_function R) : f.pmul ↑ζ = f := begin ext x, cases x; simp [nat.succ_ne_zero], end @[simp] lemma zeta_pmul (f : arithmetic_function R) : (ζ : arithmetic_function R).pmul f = f := begin ext x, cases x; simp [nat.succ_ne_zero], end end non_assoc_semiring variables [semiring R] /-- This is the pointwise power of `arithmetic_function`s. -/ def ppow (f : arithmetic_function R) (k : ℕ) : arithmetic_function R := if h0 : k = 0 then ζ else ⟨λ x, (f x) ^ k, by { rw [map_zero], exact zero_pow (nat.pos_of_ne_zero h0) }⟩ @[simp] lemma ppow_zero {f : arithmetic_function R} : f.ppow 0 = ζ := by rw [ppow, dif_pos rfl] @[simp] lemma ppow_apply {f : arithmetic_function R} {k x : ℕ} (kpos : 0 < k) : f.ppow k x = (f x) ^ k := by { rw [ppow, dif_neg (ne_of_gt kpos)], refl } lemma ppow_succ {f : arithmetic_function R} {k : ℕ} : f.ppow (k + 1) = f.pmul (f.ppow k) := begin ext x, rw [ppow_apply (nat.succ_pos k), pow_succ], induction k; simp, end lemma ppow_succ' {f : arithmetic_function R} {k : ℕ} {kpos : 0 < k} : f.ppow (k + 1) = (f.ppow k).pmul f := begin ext x, rw [ppow_apply (nat.succ_pos k), pow_succ'], induction k; simp, end end pmul /-- Multiplicative functions -/ def is_multiplicative [monoid_with_zero R] (f : arithmetic_function R) : Prop := f 1 = 1 ∧ (∀ {m n : ℕ}, m.coprime n → f (m * n) = f m * f n) namespace is_multiplicative section monoid_with_zero variable [monoid_with_zero R] @[simp] lemma map_one {f : arithmetic_function R} (h : f.is_multiplicative) : f 1 = 1 := h.1 @[simp] lemma map_mul_of_coprime {f : arithmetic_function R} (hf : f.is_multiplicative) {m n : ℕ} (h : m.coprime n) : f (m * n) = f m * f n := hf.2 h end monoid_with_zero lemma map_prod {ι : Type*} [comm_monoid_with_zero R] (g : ι → ℕ) {f : nat.arithmetic_function R} (hf : f.is_multiplicative) (s : finset ι) (hs : (s : set ι).pairwise (coprime on g)): f (∏ i in s, g i) = ∏ i in s, f (g i) := begin classical, induction s using finset.induction_on with a s has ih hs, { simp [hf] }, rw [coe_insert, set.pairwise_insert_of_symmetric (coprime.symmetric.comap g)] at hs, rw [prod_insert has, prod_insert has, hf.map_mul_of_coprime, ih hs.1], exact nat.coprime_prod_right (λ i hi, hs.2 _ hi (hi.ne_of_not_mem has).symm), end lemma nat_cast {f : arithmetic_function ℕ} [semiring R] (h : f.is_multiplicative) : is_multiplicative (f : arithmetic_function R) := ⟨by simp [h], λ m n cop, by simp [cop, h]⟩ lemma int_cast {f : arithmetic_function ℤ} [ring R] (h : f.is_multiplicative) : is_multiplicative (f : arithmetic_function R) := ⟨by simp [h], λ m n cop, by simp [cop, h]⟩ lemma mul [comm_semiring R] {f g : arithmetic_function R} (hf : f.is_multiplicative) (hg : g.is_multiplicative) : is_multiplicative (f * g) := ⟨by { simp [hf, hg], }, begin simp only [mul_apply], intros m n cop, rw sum_mul_sum, symmetry, apply sum_bij (λ (x : (ℕ × ℕ) × ℕ × ℕ) h, (x.1.1 * x.2.1, x.1.2 * x.2.2)), { rintros ⟨⟨a1, a2⟩, ⟨b1, b2⟩⟩ h, simp only [mem_divisors_antidiagonal, ne.def, mem_product] at h, rcases h with ⟨⟨rfl, ha⟩, ⟨rfl, hb⟩⟩, simp only [mem_divisors_antidiagonal, nat.mul_eq_zero, ne.def], split, {ring}, rw nat.mul_eq_zero at *, apply not_or ha hb }, { rintros ⟨⟨a1, a2⟩, ⟨b1, b2⟩⟩ h, simp only [mem_divisors_antidiagonal, ne.def, mem_product] at h, rcases h with ⟨⟨rfl, ha⟩, ⟨rfl, hb⟩⟩, dsimp only, rw [hf.map_mul_of_coprime cop.coprime_mul_right.coprime_mul_right_right, hg.map_mul_of_coprime cop.coprime_mul_left.coprime_mul_left_right], ring, }, { rintros ⟨⟨a1, a2⟩, ⟨b1, b2⟩⟩ ⟨⟨c1, c2⟩, ⟨d1, d2⟩⟩ hab hcd h, simp only [mem_divisors_antidiagonal, ne.def, mem_product] at hab, rcases hab with ⟨⟨rfl, ha⟩, ⟨rfl, hb⟩⟩, simp only [mem_divisors_antidiagonal, ne.def, mem_product] at hcd, simp only [prod.mk.inj_iff] at h, ext; dsimp only, { transitivity nat.gcd (a1 * a2) (a1 * b1), { rw [nat.gcd_mul_left, cop.coprime_mul_left.coprime_mul_right_right.gcd_eq_one, mul_one] }, { rw [← hcd.1.1, ← hcd.2.1] at cop, rw [← hcd.1.1, h.1, nat.gcd_mul_left, cop.coprime_mul_left.coprime_mul_right_right.gcd_eq_one, mul_one] } }, { transitivity nat.gcd (a1 * a2) (a2 * b2), { rw [mul_comm, nat.gcd_mul_left, cop.coprime_mul_right.coprime_mul_left_right.gcd_eq_one, mul_one] }, { rw [← hcd.1.1, ← hcd.2.1] at cop, rw [← hcd.1.1, h.2, mul_comm, nat.gcd_mul_left, cop.coprime_mul_right.coprime_mul_left_right.gcd_eq_one, mul_one] } }, { transitivity nat.gcd (b1 * b2) (a1 * b1), { rw [mul_comm, nat.gcd_mul_right, cop.coprime_mul_right.coprime_mul_left_right.symm.gcd_eq_one, one_mul] }, { rw [← hcd.1.1, ← hcd.2.1] at cop, rw [← hcd.2.1, h.1, mul_comm c1 d1, nat.gcd_mul_left, cop.coprime_mul_right.coprime_mul_left_right.symm.gcd_eq_one, mul_one] } }, { transitivity nat.gcd (b1 * b2) (a2 * b2), { rw [nat.gcd_mul_right, cop.coprime_mul_left.coprime_mul_right_right.symm.gcd_eq_one, one_mul] }, { rw [← hcd.1.1, ← hcd.2.1] at cop, rw [← hcd.2.1, h.2, nat.gcd_mul_right, cop.coprime_mul_left.coprime_mul_right_right.symm.gcd_eq_one, one_mul] } } }, { rintros ⟨b1, b2⟩ h, simp only [mem_divisors_antidiagonal, ne.def, mem_product] at h, use ((b1.gcd m, b2.gcd m), (b1.gcd n, b2.gcd n)), simp only [exists_prop, prod.mk.inj_iff, ne.def, mem_product, mem_divisors_antidiagonal], rw [← cop.gcd_mul _, ← cop.gcd_mul _, ← h.1, nat.gcd_mul_gcd_of_coprime_of_mul_eq_mul cop h.1, nat.gcd_mul_gcd_of_coprime_of_mul_eq_mul cop.symm _], { rw [nat.mul_eq_zero, decidable.not_or_iff_and_not] at h, simp [h.2.1, h.2.2] }, rw [mul_comm n m, h.1] } end⟩ lemma pmul [comm_semiring R] {f g : arithmetic_function R} (hf : f.is_multiplicative) (hg : g.is_multiplicative) : is_multiplicative (f.pmul g) := ⟨by { simp [hf, hg], }, λ m n cop, begin simp only [pmul_apply, hf.map_mul_of_coprime cop, hg.map_mul_of_coprime cop], ring, end⟩ /-- For any multiplicative function `f` and any `n > 0`, we can evaluate `f n` by evaluating `f` at `p ^ k` over the factorization of `n` -/ lemma multiplicative_factorization [comm_monoid_with_zero R] (f : arithmetic_function R) (hf : f.is_multiplicative) {n : ℕ} (hn : n ≠ 0) : f n = n.factorization.prod (λ p k, f (p ^ k)) := multiplicative_factorization f (λ _ _, hf.2) hf.1 hn /-- A recapitulation of the definition of multiplicative that is simpler for proofs -/ lemma iff_ne_zero [monoid_with_zero R] {f : arithmetic_function R} : is_multiplicative f ↔ f 1 = 1 ∧ (∀ {m n : ℕ}, m ≠ 0 → n ≠ 0 → m.coprime n → f (m * n) = f m * f n) := begin refine and_congr_right' (forall₂_congr (λ m n, ⟨λ h _ _, h, λ h hmn, _⟩)), rcases eq_or_ne m 0 with rfl | hm, { simp }, rcases eq_or_ne n 0 with rfl | hn, { simp }, exact h hm hn hmn, end /-- Two multiplicative functions `f` and `g` are equal if and only if they agree on prime powers -/ lemma eq_iff_eq_on_prime_powers [comm_monoid_with_zero R] (f : arithmetic_function R) (hf : f.is_multiplicative) (g : arithmetic_function R) (hg : g.is_multiplicative) : f = g ↔ ∀ (p i : ℕ), nat.prime p → f (p ^ i) = g (p ^ i) := begin split, { intros h p i _, rw [h] }, intros h, ext n, by_cases hn : n = 0, { rw [hn, arithmetic_function.map_zero, arithmetic_function.map_zero] }, rw [multiplicative_factorization f hf hn, multiplicative_factorization g hg hn], refine finset.prod_congr rfl _, simp only [support_factorization, list.mem_to_finset], intros p hp, exact h p _ (nat.prime_of_mem_factors hp), end end is_multiplicative section special_functions /-- The identity on `ℕ` as an `arithmetic_function`. -/ def id : arithmetic_function ℕ := ⟨id, rfl⟩ @[simp] lemma id_apply {x : ℕ} : id x = x := rfl /-- `pow k n = n ^ k`, except `pow 0 0 = 0`. -/ def pow (k : ℕ) : arithmetic_function ℕ := id.ppow k @[simp] lemma pow_apply {k n : ℕ} : pow k n = if (k = 0 ∧ n = 0) then 0 else n ^ k := begin cases k, { simp [pow] }, simp [pow, (ne_of_lt (nat.succ_pos k)).symm], end lemma pow_zero_eq_zeta : pow 0 = ζ := by { ext n, simp } /-- `σ k n` is the sum of the `k`th powers of the divisors of `n` -/ def sigma (k : ℕ) : arithmetic_function ℕ := ⟨λ n, ∑ d in divisors n, d ^ k, by simp⟩ localized "notation (name := arithmetic_function.sigma) `σ` := nat.arithmetic_function.sigma" in arithmetic_function lemma sigma_apply {k n : ℕ} : σ k n = ∑ d in divisors n, d ^ k := rfl lemma sigma_one_apply (n : ℕ) : σ 1 n = ∑ d in divisors n, d := by simp [sigma_apply] lemma sigma_zero_apply (n : ℕ) : σ 0 n = (divisors n).card := by simp [sigma_apply] lemma sigma_zero_apply_prime_pow {p i : ℕ} (hp : p.prime) : σ 0 (p ^ i) = i + 1 := by rw [sigma_zero_apply, divisors_prime_pow hp, card_map, card_range] lemma zeta_mul_pow_eq_sigma {k : ℕ} : ζ * pow k = σ k := begin ext, rw [sigma, zeta_mul_apply], apply sum_congr rfl, intros x hx, rw [pow_apply, if_neg (not_and_of_not_right _ _)], contrapose! hx, simp [hx], end lemma is_multiplicative_one [monoid_with_zero R] : is_multiplicative (1 : arithmetic_function R) := is_multiplicative.iff_ne_zero.2 ⟨by simp, begin intros m n hm hn hmn, rcases eq_or_ne m 1 with rfl | hm', { simp }, rw [one_apply_ne, one_apply_ne hm', zero_mul], rw [ne.def, nat.mul_eq_one_iff, not_and_distrib], exact or.inl hm' end⟩ lemma is_multiplicative_zeta : is_multiplicative ζ := is_multiplicative.iff_ne_zero.2 ⟨by simp, by simp {contextual := tt}⟩ lemma is_multiplicative_id : is_multiplicative arithmetic_function.id := ⟨rfl, λ _ _ _, rfl⟩ lemma is_multiplicative.ppow [comm_semiring R] {f : arithmetic_function R} (hf : f.is_multiplicative) {k : ℕ} : is_multiplicative (f.ppow k) := begin induction k with k hi, { exact is_multiplicative_zeta.nat_cast }, { rw ppow_succ, apply hf.pmul hi }, end lemma is_multiplicative_pow {k : ℕ} : is_multiplicative (pow k) := is_multiplicative_id.ppow lemma is_multiplicative_sigma {k : ℕ} : is_multiplicative (σ k) := begin rw [← zeta_mul_pow_eq_sigma], apply ((is_multiplicative_zeta).mul is_multiplicative_pow) end /-- `Ω n` is the number of prime factors of `n`. -/ def card_factors : arithmetic_function ℕ := ⟨λ n, n.factors.length, by simp⟩ localized "notation (name := card_factors) `Ω` := nat.arithmetic_function.card_factors" in arithmetic_function lemma card_factors_apply {n : ℕ} : Ω n = n.factors.length := rfl @[simp] lemma card_factors_one : Ω 1 = 0 := by simp [card_factors] lemma card_factors_eq_one_iff_prime {n : ℕ} : Ω n = 1 ↔ n.prime := begin refine ⟨λ h, _, λ h, list.length_eq_one.2 ⟨n, factors_prime h⟩⟩, cases n, { contrapose! h, simp }, rcases list.length_eq_one.1 h with ⟨x, hx⟩, rw [← prod_factors n.succ_ne_zero, hx, list.prod_singleton], apply prime_of_mem_factors, rw [hx, list.mem_singleton] end lemma card_factors_mul {m n : ℕ} (m0 : m ≠ 0) (n0 : n ≠ 0) : Ω (m * n) = Ω m + Ω n := by rw [card_factors_apply, card_factors_apply, card_factors_apply, ← multiset.coe_card, ← factors_eq, unique_factorization_monoid.normalized_factors_mul m0 n0, factors_eq, factors_eq, multiset.card_add, multiset.coe_card, multiset.coe_card] lemma card_factors_multiset_prod {s : multiset ℕ} (h0 : s.prod ≠ 0) : Ω s.prod = (multiset.map Ω s).sum := begin revert h0, apply s.induction_on, by simp, intros a t h h0, rw [multiset.prod_cons, mul_ne_zero_iff] at h0, simp [h0, card_factors_mul, h], end @[simp] lemma card_factors_apply_prime {p : ℕ} (hp : p.prime) : Ω p = 1 := card_factors_eq_one_iff_prime.2 hp @[simp] lemma card_factors_apply_prime_pow {p k : ℕ} (hp : p.prime) : Ω (p ^ k) = k := by rw [card_factors_apply, hp.factors_pow, list.length_repeat] /-- `ω n` is the number of distinct prime factors of `n`. -/ def card_distinct_factors : arithmetic_function ℕ := ⟨λ n, n.factors.dedup.length, by simp⟩ localized "notation (name := card_distinct_factors) `ω` := nat.arithmetic_function.card_distinct_factors" in arithmetic_function lemma card_distinct_factors_zero : ω 0 = 0 := by simp @[simp] lemma card_distinct_factors_one : ω 1 = 0 := by simp [card_distinct_factors] lemma card_distinct_factors_apply {n : ℕ} : ω n = n.factors.dedup.length := rfl lemma card_distinct_factors_eq_card_factors_iff_squarefree {n : ℕ} (h0 : n ≠ 0) : ω n = Ω n ↔ squarefree n := begin rw [squarefree_iff_nodup_factors h0, card_distinct_factors_apply], split; intro h, { rw ← list.eq_of_sublist_of_length_eq n.factors.dedup_sublist h, apply list.nodup_dedup }, { rw h.dedup, refl } end @[simp] lemma card_distinct_factors_apply_prime_pow {p k : ℕ} (hp : p.prime) (hk : k ≠ 0) : ω (p ^ k) = 1 := by rw [card_distinct_factors_apply, hp.factors_pow, list.repeat_dedup hk, list.length_singleton] @[simp] lemma card_distinct_factors_apply_prime {p : ℕ} (hp : p.prime) : ω p = 1 := by rw [←pow_one p, card_distinct_factors_apply_prime_pow hp one_ne_zero] /-- `μ` is the Möbius function. If `n` is squarefree with an even number of distinct prime factors, `μ n = 1`. If `n` is squarefree with an odd number of distinct prime factors, `μ n = -1`. If `n` is not squarefree, `μ n = 0`. -/ def moebius : arithmetic_function ℤ := ⟨λ n, if squarefree n then (-1) ^ (card_factors n) else 0, by simp⟩ localized "notation (name := moebius) `μ` := nat.arithmetic_function.moebius" in arithmetic_function @[simp] lemma moebius_apply_of_squarefree {n : ℕ} (h : squarefree n) : μ n = (-1) ^ card_factors n := if_pos h @[simp] lemma moebius_eq_zero_of_not_squarefree {n : ℕ} (h : ¬ squarefree n) : μ n = 0 := if_neg h lemma moebius_apply_one : μ 1 = 1 := by simp lemma moebius_ne_zero_iff_squarefree {n : ℕ} : μ n ≠ 0 ↔ squarefree n := begin split; intro h, { contrapose! h, simp [h] }, { simp [h, pow_ne_zero] } end lemma moebius_ne_zero_iff_eq_or {n : ℕ} : μ n ≠ 0 ↔ μ n = 1 ∨ μ n = -1 := begin split; intro h, { rw moebius_ne_zero_iff_squarefree at h, rw moebius_apply_of_squarefree h, apply neg_one_pow_eq_or }, { rcases h with h | h; simp [h] } end lemma moebius_apply_prime {p : ℕ} (hp : p.prime) : μ p = -1 := by rw [moebius_apply_of_squarefree hp.squarefree, card_factors_apply_prime hp, pow_one] lemma moebius_apply_prime_pow {p k : ℕ} (hp : p.prime) (hk : k ≠ 0) : μ (p ^ k) = if k = 1 then -1 else 0 := begin split_ifs, { rw [h, pow_one, moebius_apply_prime hp] }, rw [moebius_eq_zero_of_not_squarefree], rw [squarefree_pow_iff hp.ne_one hk, not_and_distrib], exact or.inr h, end lemma moebius_apply_is_prime_pow_not_prime {n : ℕ} (hn : is_prime_pow n) (hn' : ¬ n.prime) : μ n = 0 := begin obtain ⟨p, k, hp, hk, rfl⟩ := (is_prime_pow_nat_iff _).1 hn, rw [moebius_apply_prime_pow hp hk.ne', if_neg], rintro rfl, exact hn' (by simpa), end lemma is_multiplicative_moebius : is_multiplicative μ := begin rw is_multiplicative.iff_ne_zero, refine ⟨by simp, λ n m hn hm hnm, _⟩, simp only [moebius, zero_hom.coe_mk, squarefree_mul hnm, ite_and, card_factors_mul hn hm], rw [pow_add, mul_comm, ite_mul_zero_left, ite_mul_zero_right, mul_comm], end open unique_factorization_monoid @[simp] lemma moebius_mul_coe_zeta : (μ * ζ : arithmetic_function ℤ) = 1 := begin ext n, refine rec_on_pos_prime_pos_coprime _ _ _ _ n, { intros p n hp hn, rw [coe_mul_zeta_apply, sum_divisors_prime_pow hp, sum_range_succ'], simp_rw [function.embedding.coe_fn_mk, pow_zero, moebius_apply_one, moebius_apply_prime_pow hp (nat.succ_ne_zero _), nat.succ_inj', sum_ite_eq', mem_range, if_pos hn, add_left_neg], rw one_apply_ne, rw [ne.def, pow_eq_one_iff], { exact hp.ne_one }, { exact hn.ne' } }, { rw [zero_hom.map_zero, zero_hom.map_zero] }, { simp }, { intros a b ha hb hab ha' hb', rw [is_multiplicative.map_mul_of_coprime _ hab, ha', hb', is_multiplicative.map_mul_of_coprime is_multiplicative_one hab], exact is_multiplicative_moebius.mul is_multiplicative_zeta.nat_cast } end @[simp] lemma coe_zeta_mul_moebius : (ζ * μ : arithmetic_function ℤ) = 1 := by rw [mul_comm, moebius_mul_coe_zeta] @[simp] lemma coe_moebius_mul_coe_zeta [ring R] : (μ * ζ : arithmetic_function R) = 1 := by rw [←coe_coe, ←int_coe_mul, moebius_mul_coe_zeta, int_coe_one] @[simp] lemma coe_zeta_mul_coe_moebius [ring R] : (ζ * μ : arithmetic_function R) = 1 := by rw [←coe_coe, ←int_coe_mul, coe_zeta_mul_moebius, int_coe_one] section comm_ring variable [comm_ring R] instance : invertible (ζ : arithmetic_function R) := { inv_of := μ, inv_of_mul_self := coe_moebius_mul_coe_zeta, mul_inv_of_self := coe_zeta_mul_coe_moebius} /-- A unit in `arithmetic_function R` that evaluates to `ζ`, with inverse `μ`. -/ def zeta_unit : (arithmetic_function R)ˣ := ⟨ζ, μ, coe_zeta_mul_coe_moebius, coe_moebius_mul_coe_zeta⟩ @[simp] lemma coe_zeta_unit : ((zeta_unit : (arithmetic_function R)ˣ) : arithmetic_function R) = ζ := rfl @[simp] lemma inv_zeta_unit : ((zeta_unit⁻¹ : (arithmetic_function R)ˣ) : arithmetic_function R) = μ := rfl end comm_ring /-- Möbius inversion for functions to an `add_comm_group`. -/ theorem sum_eq_iff_sum_smul_moebius_eq [add_comm_group R] {f g : ℕ → R} : (∀ (n : ℕ), 0 < n → ∑ i in (n.divisors), f i = g n) ↔ ∀ (n : ℕ), 0 < n → ∑ (x : ℕ × ℕ) in n.divisors_antidiagonal, μ x.fst • g x.snd = f n := begin let f' : arithmetic_function R := ⟨λ x, if x = 0 then 0 else f x, if_pos rfl⟩, let g' : arithmetic_function R := ⟨λ x, if x = 0 then 0 else g x, if_pos rfl⟩, transitivity (ζ : arithmetic_function ℤ) • f' = g', { rw ext_iff, apply forall_congr, intro n, cases n, { simp }, rw coe_zeta_smul_apply, simp only [n.succ_ne_zero, forall_prop_of_true, succ_pos', if_false, zero_hom.coe_mk], rw sum_congr rfl (λ x hx, _), rw (if_neg (ne_of_gt (nat.pos_of_mem_divisors hx))) }, transitivity μ • g' = f', { split; intro h, { rw [← h, ← mul_smul, moebius_mul_coe_zeta, one_smul] }, { rw [← h, ← mul_smul, coe_zeta_mul_moebius, one_smul] } }, { rw ext_iff, apply forall_congr, intro n, cases n, { simp }, simp only [n.succ_ne_zero, forall_prop_of_true, succ_pos', smul_apply, if_false, zero_hom.coe_mk], rw sum_congr rfl (λ x hx, _), rw (if_neg (ne_of_gt (nat.pos_of_mem_divisors (snd_mem_divisors_of_mem_antidiagonal hx)))) }, end /-- Möbius inversion for functions to a `ring`. -/ theorem sum_eq_iff_sum_mul_moebius_eq [ring R] {f g : ℕ → R} : (∀ (n : ℕ), 0 < n → ∑ i in (n.divisors), f i = g n) ↔ ∀ (n : ℕ), 0 < n → ∑ (x : ℕ × ℕ) in n.divisors_antidiagonal, (μ x.fst : R) * g x.snd = f n := begin rw sum_eq_iff_sum_smul_moebius_eq, apply forall_congr, refine λ a, imp_congr_right (λ _, (sum_congr rfl $ λ x hx, _).congr_left), rw [zsmul_eq_mul], end /-- Möbius inversion for functions to a `comm_group`. -/ theorem prod_eq_iff_prod_pow_moebius_eq [comm_group R] {f g : ℕ → R} : (∀ (n : ℕ), 0 < n → ∏ i in (n.divisors), f i = g n) ↔ ∀ (n : ℕ), 0 < n → ∏ (x : ℕ × ℕ) in n.divisors_antidiagonal, g x.snd ^ (μ x.fst) = f n := @sum_eq_iff_sum_smul_moebius_eq (additive R) _ _ _ /-- Möbius inversion for functions to a `comm_group_with_zero`. -/ theorem prod_eq_iff_prod_pow_moebius_eq_of_nonzero [comm_group_with_zero R] {f g : ℕ → R} (hf : ∀ (n : ℕ), 0 < n → f n ≠ 0) (hg : ∀ (n : ℕ), 0 < n → g n ≠ 0) : (∀ (n : ℕ), 0 < n → ∏ i in (n.divisors), f i = g n) ↔ ∀ (n : ℕ), 0 < n → ∏ (x : ℕ × ℕ) in n.divisors_antidiagonal, g x.snd ^ (μ x.fst) = f n := begin refine iff.trans (iff.trans (forall_congr (λ n, _)) (@prod_eq_iff_prod_pow_moebius_eq Rˣ _ (λ n, if h : 0 < n then units.mk0 (f n) (hf n h) else 1) (λ n, if h : 0 < n then units.mk0 (g n) (hg n h) else 1))) (forall_congr (λ n, _)); refine imp_congr_right (λ hn, _), { dsimp, rw [dif_pos hn, ← units.eq_iff, ← units.coe_hom_apply, monoid_hom.map_prod, units.coe_mk0, prod_congr rfl _], intros x hx, rw [dif_pos (nat.pos_of_mem_divisors hx), units.coe_hom_apply, units.coe_mk0] }, { dsimp, rw [dif_pos hn, ← units.eq_iff, ← units.coe_hom_apply, monoid_hom.map_prod, units.coe_mk0, prod_congr rfl _], intros x hx, rw [dif_pos (nat.pos_of_mem_divisors (nat.snd_mem_divisors_of_mem_antidiagonal hx)), units.coe_hom_apply, units.coe_zpow, units.coe_mk0] } end end special_functions end arithmetic_function end nat
492ca6d0e3be545b338402a6385179fb429742d7
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/probability/martingale/upcrossing.lean
8f0acc6e431a736b894033e3d286e23ce1566e35
[ "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
41,504
lean
/- Copyright (c) 2022 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import data.set.intervals.monotone import probability.process.hitting_time import probability.martingale.basic /-! # Doob's upcrossing estimate > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Given a discrete real-valued submartingale $(f_n)_{n \in \mathbb{N}}$, denoting $U_N(a, b)$ the number of times $f_n$ crossed from below $a$ to above $b$ before time $N$, Doob's upcrossing estimate (also known as Doob's inequality) states that $$(b - a) \mathbb{E}[U_N(a, b)] \le \mathbb{E}[(f_N - a)^+].$$ Doob's upcrossing estimate is an important inequality and is central in proving the martingale convergence theorems. ## Main definitions * `measure_theory.upper_crossing_time a b f N n`: is the stopping time corresponding to `f` crossing above `b` the `n`-th time before time `N` (if this does not occur then the value is taken to be `N`). * `measure_theory.lower_crossing_time a b f N n`: is the stopping time corresponding to `f` crossing below `a` the `n`-th time before time `N` (if this does not occur then the value is taken to be `N`). * `measure_theory.upcrossing_strat a b f N`: is the predictable process which is 1 if `n` is between a consecutive pair of lower and upper crossing and is 0 otherwise. Intuitively one might think of the `upcrossing_strat` as the strategy of buying 1 share whenever the process crosses below `a` for the first time after selling and selling 1 share whenever the process crosses above `b` for the first time after buying. * `measure_theory.upcrossings_before a b f N`: is the number of times `f` crosses from below `a` to above `b` before time `N`. * `measure_theory.upcrossings a b f`: is the number of times `f` crosses from below `a` to above `b`. This takes value in `ℝ≥0∞` and so is allowed to be `∞`. ## Main results * `measure_theory.adapted.is_stopping_time_upper_crossing_time`: `upper_crossing_time` is a stopping time whenever the process it is associated to is adapted. * `measure_theory.adapted.is_stopping_time_lower_crossing_time`: `lower_crossing_time` is a stopping time whenever the process it is associated to is adapted. * `measure_theory.submartingale.mul_integral_upcrossings_before_le_integral_pos_part`: Doob's upcrossing estimate. * `measure_theory.submartingale.mul_lintegral_upcrossings_le_lintegral_pos_part`: the inequality obtained by taking the supremum on both sides of Doob's upcrossing estimate. ### References We mostly follow the proof from [Kallenberg, *Foundations of modern probability*][kallenberg2021] -/ open topological_space filter open_locale nnreal ennreal measure_theory probability_theory big_operators topology namespace measure_theory variables {Ω ι : Type*} {m0 : measurable_space Ω} {μ : measure Ω} /-! ## Proof outline In this section, we will denote $U_N(a, b)$ the number of upcrossings of $(f_n)$ from below $a$ to above $b$ before time $N$. To define $U_N(a, b)$, we will construct two stopping times corresponding to when $(f_n)$ crosses below $a$ and above $b$. Namely, we define $$ \sigma_n := \inf \{n \ge \tau_n \mid f_n \le a\} \wedge N; $$ $$ \tau_{n + 1} := \inf \{n \ge \sigma_n \mid f_n \ge b\} \wedge N. $$ These are `lower_crossing_time` and `upper_crossing_time` in our formalization which are defined using `measure_theory.hitting` allowing us to specify a starting and ending time. Then, we may simply define $U_N(a, b) := \sup \{n \mid \tau_n < N\}$. Fixing $a < b \in \mathbb{R}$, we will first prove the theorem in the special case that $0 \le f_0$ and $a \le f_N$. In particular, we will show $$ (b - a) \mathbb{E}[U_N(a, b)] \le \mathbb{E}[f_N]. $$ This is `measure_theory.integral_mul_upcrossings_before_le_integral` in our formalization. To prove this, we use the fact that given a non-negative, bounded, predictable process $(C_n)$ (i.e. $(C_{n + 1})$ is adapted), $(C \bullet f)_n := \sum_{k \le n} C_{k + 1}(f_{k + 1} - f_k)$ is a submartingale if $(f_n)$ is. Define $C_n := \sum_{k \le n} \mathbf{1}_{[\sigma_k, \tau_{k + 1})}(n)$. It is easy to see that $(1 - C_n)$ is non-negative, bounded and predictable, and hence, given a submartingale $(f_n)$, $(1 - C) \bullet f$ is also a submartingale. Thus, by the submartingale property, $0 \le \mathbb{E}[((1 - C) \bullet f)_0] \le \mathbb{E}[((1 - C) \bullet f)_N]$ implying $$ \mathbb{E}[(C \bullet f)_N] \le \mathbb{E}[(1 \bullet f)_N] = \mathbb{E}[f_N] - \mathbb{E}[f_0]. $$ Furthermore, \begin{align} (C \bullet f)_N & = \sum_{n \le N} \sum_{k \le N} \mathbf{1}_{[\sigma_k, \tau_{k + 1})}(n)(f_{n + 1} - f_n)\\ & = \sum_{k \le N} \sum_{n \le N} \mathbf{1}_{[\sigma_k, \tau_{k + 1})}(n)(f_{n + 1} - f_n)\\ & = \sum_{k \le N} (f_{\sigma_k + 1} - f_{\sigma_k} + f_{\sigma_k + 2} - f_{\sigma_k + 1} + \cdots + f_{\tau_{k + 1}} - f_{\tau_{k + 1} - 1})\\ & = \sum_{k \le N} (f_{\tau_{k + 1}} - f_{\sigma_k}) \ge \sum_{k < U_N(a, b)} (b - a) = (b - a) U_N(a, b) \end{align} where the inequality follows since for all $k < U_N(a, b)$, $f_{\tau_{k + 1}} - f_{\sigma_k} \ge b - a$ while for all $k > U_N(a, b)$, $f_{\tau_{k + 1}} = f_{\sigma_k} = f_N$ and $f_{\tau_{U_N(a, b) + 1}} - f_{\sigma_{U_N(a, b)}} = f_N - a \ge 0$. Hence, we have $$ (b - a) \mathbb{E}[U_N(a, b)] \le \mathbb{E}[(C \bullet f)_N] \le \mathbb{E}[f_N] - \mathbb{E}[f_0] \le \mathbb{E}[f_N], $$ as required. To obtain the general case, we simply apply the above to $((f_n - a)^+)_n$. -/ /-- `lower_crossing_time_aux a f c N` is the first time `f` reached below `a` after time `c` before time `N`. -/ noncomputable def lower_crossing_time_aux [preorder ι] [has_Inf ι] (a : ℝ) (f : ι → Ω → ℝ) (c N : ι) : Ω → ι := hitting f (set.Iic a) c N /-- `upper_crossing_time a b f N n` is the first time before time `N`, `f` reaches above `b` after `f` reached below `a` for the `n - 1`-th time. -/ noncomputable def upper_crossing_time [preorder ι] [order_bot ι] [has_Inf ι] (a b : ℝ) (f : ι → Ω → ℝ) (N : ι) : ℕ → Ω → ι | 0 := ⊥ | (n + 1) := λ ω, hitting f (set.Ici b) (lower_crossing_time_aux a f (upper_crossing_time n ω) N ω) N ω /-- `lower_crossing_time a b f N n` is the first time before time `N`, `f` reaches below `a` after `f` reached above `b` for the `n`-th time. -/ noncomputable def lower_crossing_time [preorder ι] [order_bot ι] [has_Inf ι] (a b : ℝ) (f : ι → Ω → ℝ) (N : ι) (n : ℕ) : Ω → ι := λ ω, hitting f (set.Iic a) (upper_crossing_time a b f N n ω) N ω section variables [preorder ι] [order_bot ι] [has_Inf ι] variables {a b : ℝ} {f : ι → Ω → ℝ} {N : ι} {n m : ℕ} {ω : Ω} @[simp] lemma upper_crossing_time_zero : upper_crossing_time a b f N 0 = ⊥ := rfl @[simp] lemma lower_crossing_time_zero : lower_crossing_time a b f N 0 = hitting f (set.Iic a) ⊥ N := rfl lemma upper_crossing_time_succ : upper_crossing_time a b f N (n + 1) ω = hitting f (set.Ici b) (lower_crossing_time_aux a f (upper_crossing_time a b f N n ω) N ω) N ω := by rw upper_crossing_time lemma upper_crossing_time_succ_eq (ω : Ω) : upper_crossing_time a b f N (n + 1) ω = hitting f (set.Ici b) (lower_crossing_time a b f N n ω) N ω := begin simp only [upper_crossing_time_succ], refl, end end section conditionally_complete_linear_order_bot variables [conditionally_complete_linear_order_bot ι] variables {a b : ℝ} {f : ι → Ω → ℝ} {N : ι} {n m : ℕ} {ω : Ω} lemma upper_crossing_time_le : upper_crossing_time a b f N n ω ≤ N := begin cases n, { simp only [upper_crossing_time_zero, pi.bot_apply, bot_le] }, { simp only [upper_crossing_time_succ, hitting_le] }, end @[simp] lemma upper_crossing_time_zero' : upper_crossing_time a b f ⊥ n ω = ⊥ := eq_bot_iff.2 upper_crossing_time_le lemma lower_crossing_time_le : lower_crossing_time a b f N n ω ≤ N := by simp only [lower_crossing_time, hitting_le ω] lemma upper_crossing_time_le_lower_crossing_time : upper_crossing_time a b f N n ω ≤ lower_crossing_time a b f N n ω := by simp only [lower_crossing_time, le_hitting upper_crossing_time_le ω] lemma lower_crossing_time_le_upper_crossing_time_succ : lower_crossing_time a b f N n ω ≤ upper_crossing_time a b f N (n + 1) ω := begin rw upper_crossing_time_succ, exact le_hitting lower_crossing_time_le ω, end lemma lower_crossing_time_mono (hnm : n ≤ m) : lower_crossing_time a b f N n ω ≤ lower_crossing_time a b f N m ω := begin suffices : monotone (λ n, lower_crossing_time a b f N n ω), { exact this hnm }, exact monotone_nat_of_le_succ (λ n, le_trans lower_crossing_time_le_upper_crossing_time_succ upper_crossing_time_le_lower_crossing_time) end lemma upper_crossing_time_mono (hnm : n ≤ m) : upper_crossing_time a b f N n ω ≤ upper_crossing_time a b f N m ω := begin suffices : monotone (λ n, upper_crossing_time a b f N n ω), { exact this hnm }, exact monotone_nat_of_le_succ (λ n, le_trans upper_crossing_time_le_lower_crossing_time lower_crossing_time_le_upper_crossing_time_succ), end end conditionally_complete_linear_order_bot variables {a b : ℝ} {f : ℕ → Ω → ℝ} {N : ℕ} {n m : ℕ} {ω : Ω} lemma stopped_value_lower_crossing_time (h : lower_crossing_time a b f N n ω ≠ N) : stopped_value f (lower_crossing_time a b f N n) ω ≤ a := begin obtain ⟨j, hj₁, hj₂⟩ := (hitting_le_iff_of_lt _ (lt_of_le_of_ne lower_crossing_time_le h)).1 le_rfl, exact stopped_value_hitting_mem ⟨j, ⟨hj₁.1, le_trans hj₁.2 lower_crossing_time_le⟩, hj₂⟩, end lemma stopped_value_upper_crossing_time (h : upper_crossing_time a b f N (n + 1) ω ≠ N) : b ≤ stopped_value f (upper_crossing_time a b f N (n + 1)) ω := begin obtain ⟨j, hj₁, hj₂⟩ := (hitting_le_iff_of_lt _ (lt_of_le_of_ne upper_crossing_time_le h)).1 le_rfl, exact stopped_value_hitting_mem ⟨j, ⟨hj₁.1, le_trans hj₁.2 (hitting_le _)⟩, hj₂⟩, end lemma upper_crossing_time_lt_lower_crossing_time (hab : a < b) (hn : lower_crossing_time a b f N (n + 1) ω ≠ N) : upper_crossing_time a b f N (n + 1) ω < lower_crossing_time a b f N (n + 1) ω := begin refine lt_of_le_of_ne upper_crossing_time_le_lower_crossing_time (λ h, not_le.2 hab $ le_trans _ (stopped_value_lower_crossing_time hn)), simp only [stopped_value], rw ← h, exact stopped_value_upper_crossing_time (h.symm ▸ hn), end lemma lower_crossing_time_lt_upper_crossing_time (hab : a < b) (hn : upper_crossing_time a b f N (n + 1) ω ≠ N) : lower_crossing_time a b f N n ω < upper_crossing_time a b f N (n + 1) ω := begin refine lt_of_le_of_ne lower_crossing_time_le_upper_crossing_time_succ (λ h, not_le.2 hab $ le_trans (stopped_value_upper_crossing_time hn) _), simp only [stopped_value], rw ← h, exact stopped_value_lower_crossing_time (h.symm ▸ hn), end lemma upper_crossing_time_lt_succ (hab : a < b) (hn : upper_crossing_time a b f N (n + 1) ω ≠ N) : upper_crossing_time a b f N n ω < upper_crossing_time a b f N (n + 1) ω := lt_of_le_of_lt upper_crossing_time_le_lower_crossing_time (lower_crossing_time_lt_upper_crossing_time hab hn) lemma lower_crossing_time_stabilize (hnm : n ≤ m) (hn : lower_crossing_time a b f N n ω = N) : lower_crossing_time a b f N m ω = N := le_antisymm lower_crossing_time_le (le_trans (le_of_eq hn.symm) (lower_crossing_time_mono hnm)) lemma upper_crossing_time_stabilize (hnm : n ≤ m) (hn : upper_crossing_time a b f N n ω = N) : upper_crossing_time a b f N m ω = N := le_antisymm upper_crossing_time_le (le_trans (le_of_eq hn.symm) (upper_crossing_time_mono hnm)) lemma lower_crossing_time_stabilize' (hnm : n ≤ m) (hn : N ≤ lower_crossing_time a b f N n ω) : lower_crossing_time a b f N m ω = N := lower_crossing_time_stabilize hnm (le_antisymm lower_crossing_time_le hn) lemma upper_crossing_time_stabilize' (hnm : n ≤ m) (hn : N ≤ upper_crossing_time a b f N n ω) : upper_crossing_time a b f N m ω = N := upper_crossing_time_stabilize hnm (le_antisymm upper_crossing_time_le hn) -- `upper_crossing_time_bound_eq` provides an explicit bound lemma exists_upper_crossing_time_eq (f : ℕ → Ω → ℝ) (N : ℕ) (ω : Ω) (hab : a < b) : ∃ n, upper_crossing_time a b f N n ω = N := begin by_contra h, push_neg at h, have : strict_mono (λ n, upper_crossing_time a b f N n ω) := strict_mono_nat_of_lt_succ (λ n, upper_crossing_time_lt_succ hab (h _)), obtain ⟨_, ⟨k, rfl⟩, hk⟩ : ∃ m (hm : m ∈ set.range (λ n, upper_crossing_time a b f N n ω)), N < m := ⟨upper_crossing_time a b f N (N + 1) ω, ⟨N + 1, rfl⟩, lt_of_lt_of_le (N.lt_succ_self) (strict_mono.id_le this (N + 1))⟩, exact not_le.2 hk upper_crossing_time_le end lemma upper_crossing_time_lt_bdd_above (hab : a < b) : bdd_above {n | upper_crossing_time a b f N n ω < N} := begin obtain ⟨k, hk⟩ := exists_upper_crossing_time_eq f N ω hab, refine ⟨k, λ n (hn : upper_crossing_time a b f N n ω < N), _⟩, by_contra hn', exact hn.ne (upper_crossing_time_stabilize (not_le.1 hn').le hk) end lemma upper_crossing_time_lt_nonempty (hN : 0 < N) : {n | upper_crossing_time a b f N n ω < N}.nonempty := ⟨0, hN⟩ lemma upper_crossing_time_bound_eq (f : ℕ → Ω → ℝ) (N : ℕ) (ω : Ω) (hab : a < b) : upper_crossing_time a b f N N ω = N := begin by_cases hN' : N < nat.find (exists_upper_crossing_time_eq f N ω hab), { refine le_antisymm upper_crossing_time_le _, have hmono : strict_mono_on (λ n, upper_crossing_time a b f N n ω) (set.Iic (nat.find (exists_upper_crossing_time_eq f N ω hab)).pred), { refine strict_mono_on_Iic_of_lt_succ (λ m hm, upper_crossing_time_lt_succ hab _), rw nat.lt_pred_iff at hm, convert nat.find_min _ hm }, convert strict_mono_on.Iic_id_le hmono N (nat.le_pred_of_lt hN') }, { rw not_lt at hN', exact upper_crossing_time_stabilize hN' (nat.find_spec (exists_upper_crossing_time_eq f N ω hab)) } end lemma upper_crossing_time_eq_of_bound_le (hab : a < b) (hn : N ≤ n) : upper_crossing_time a b f N n ω = N := le_antisymm upper_crossing_time_le ((le_trans (upper_crossing_time_bound_eq f N ω hab).symm.le (upper_crossing_time_mono hn))) variables {ℱ : filtration ℕ m0} lemma adapted.is_stopping_time_crossing (hf : adapted ℱ f) : is_stopping_time ℱ (upper_crossing_time a b f N n) ∧ is_stopping_time ℱ (lower_crossing_time a b f N n) := begin induction n with k ih, { refine ⟨is_stopping_time_const _ 0, _⟩, simp [hitting_is_stopping_time hf measurable_set_Iic] }, { obtain ⟨ih₁, ih₂⟩ := ih, have : is_stopping_time ℱ (upper_crossing_time a b f N (k + 1)), { intro n, simp_rw upper_crossing_time_succ_eq, exact is_stopping_time_hitting_is_stopping_time ih₂ (λ _, lower_crossing_time_le) measurable_set_Ici hf _ }, refine ⟨this, _⟩, { intro n, exact is_stopping_time_hitting_is_stopping_time this (λ _, upper_crossing_time_le) measurable_set_Iic hf _ } } end lemma adapted.is_stopping_time_upper_crossing_time (hf : adapted ℱ f) : is_stopping_time ℱ (upper_crossing_time a b f N n) := hf.is_stopping_time_crossing.1 lemma adapted.is_stopping_time_lower_crossing_time (hf : adapted ℱ f) : is_stopping_time ℱ (lower_crossing_time a b f N n) := hf.is_stopping_time_crossing.2 /-- `upcrossing_strat a b f N n` is 1 if `n` is between a consecutive pair of lower and upper crossings and is 0 otherwise. `upcrossing_strat` is shifted by one index so that it is adapted rather than predictable. -/ noncomputable def upcrossing_strat (a b : ℝ) (f : ℕ → Ω → ℝ) (N n : ℕ) (ω : Ω) : ℝ := ∑ k in finset.range N, (set.Ico (lower_crossing_time a b f N k ω) (upper_crossing_time a b f N (k + 1) ω)).indicator 1 n lemma upcrossing_strat_nonneg : 0 ≤ upcrossing_strat a b f N n ω := finset.sum_nonneg (λ i hi, set.indicator_nonneg (λ ω hω, zero_le_one) _) lemma upcrossing_strat_le_one : upcrossing_strat a b f N n ω ≤ 1 := begin rw [upcrossing_strat, ← set.indicator_finset_bUnion_apply], { exact set.indicator_le_self' (λ _ _, zero_le_one) _ }, { intros i hi j hj hij, rw set.Ico_disjoint_Ico, obtain (hij' | hij') := lt_or_gt_of_ne hij, { rw [min_eq_left ((upper_crossing_time_mono (nat.succ_le_succ hij'.le)) : upper_crossing_time a b f N _ ω ≤ upper_crossing_time a b f N _ ω), max_eq_right (lower_crossing_time_mono hij'.le : lower_crossing_time a b f N _ _ ≤ lower_crossing_time _ _ _ _ _ _)], refine le_trans upper_crossing_time_le_lower_crossing_time (lower_crossing_time_mono (nat.succ_le_of_lt hij')) }, { rw gt_iff_lt at hij', rw [min_eq_right ((upper_crossing_time_mono (nat.succ_le_succ hij'.le)) : upper_crossing_time a b f N _ ω ≤ upper_crossing_time a b f N _ ω), max_eq_left (lower_crossing_time_mono hij'.le : lower_crossing_time a b f N _ _ ≤ lower_crossing_time _ _ _ _ _ _)], refine le_trans upper_crossing_time_le_lower_crossing_time (lower_crossing_time_mono (nat.succ_le_of_lt hij')) } } end lemma adapted.upcrossing_strat_adapted (hf : adapted ℱ f) : adapted ℱ (upcrossing_strat a b f N) := begin intro n, change strongly_measurable[ℱ n] (λ ω, ∑ k in finset.range N, ({n | lower_crossing_time a b f N k ω ≤ n} ∩ {n | n < upper_crossing_time a b f N (k + 1) ω}).indicator 1 n), refine finset.strongly_measurable_sum _ (λ i hi, strongly_measurable_const.indicator ((hf.is_stopping_time_lower_crossing_time n).inter _)), simp_rw ← not_le, exact (hf.is_stopping_time_upper_crossing_time n).compl, end lemma submartingale.sum_upcrossing_strat_mul [is_finite_measure μ] (hf : submartingale f ℱ μ) (a b : ℝ) (N : ℕ) : submartingale (λ n : ℕ, ∑ k in finset.range n, upcrossing_strat a b f N k * (f (k + 1) - f k)) ℱ μ := hf.sum_mul_sub hf.adapted.upcrossing_strat_adapted (λ _ _, upcrossing_strat_le_one) (λ _ _, upcrossing_strat_nonneg) lemma submartingale.sum_sub_upcrossing_strat_mul [is_finite_measure μ] (hf : submartingale f ℱ μ) (a b : ℝ) (N : ℕ) : submartingale (λ n : ℕ, ∑ k in finset.range n, (1 - upcrossing_strat a b f N k) * (f (k + 1) - f k)) ℱ μ := begin refine hf.sum_mul_sub (λ n, (adapted_const ℱ 1 n).sub (hf.adapted.upcrossing_strat_adapted n)) (_ : ∀ n ω, (1 - upcrossing_strat a b f N n) ω ≤ 1) _, { exact λ n ω, sub_le_self _ upcrossing_strat_nonneg }, { intros n ω, simp [upcrossing_strat_le_one] } end lemma submartingale.sum_mul_upcrossing_strat_le [is_finite_measure μ] (hf : submartingale f ℱ μ) : μ[∑ k in finset.range n, upcrossing_strat a b f N k * (f (k + 1) - f k)] ≤ μ[f n] - μ[f 0] := begin have h₁ : (0 : ℝ) ≤ μ[∑ k in finset.range n, (1 - upcrossing_strat a b f N k) * (f (k + 1) - f k)], { have := (hf.sum_sub_upcrossing_strat_mul a b N).set_integral_le (zero_le n) measurable_set.univ, rw [integral_univ, integral_univ] at this, refine le_trans _ this, simp only [finset.range_zero, finset.sum_empty, integral_zero'] }, have h₂ : μ[∑ k in finset.range n, (1 - upcrossing_strat a b f N k) * (f (k + 1) - f k)] = μ[∑ k in finset.range n, (f (k + 1) - f k)] - μ[∑ k in finset.range n, upcrossing_strat a b f N k * (f (k + 1) - f k)], { simp only [sub_mul, one_mul, finset.sum_sub_distrib, pi.sub_apply, finset.sum_apply, pi.mul_apply], refine integral_sub (integrable.sub (integrable_finset_sum _ (λ i hi, hf.integrable _)) (integrable_finset_sum _ (λ i hi, hf.integrable _))) _, convert (hf.sum_upcrossing_strat_mul a b N).integrable n, ext, simp }, rw [h₂, sub_nonneg] at h₁, refine le_trans h₁ _, simp_rw [finset.sum_range_sub, integral_sub' (hf.integrable _) (hf.integrable _)], end /-- The number of upcrossings (strictly) before time `N`. -/ noncomputable def upcrossings_before [preorder ι] [order_bot ι] [has_Inf ι] (a b : ℝ) (f : ι → Ω → ℝ) (N : ι) (ω : Ω) : ℕ := Sup {n | upper_crossing_time a b f N n ω < N} @[simp] lemma upcrossings_before_bot [preorder ι] [order_bot ι] [has_Inf ι] {a b : ℝ} {f : ι → Ω → ℝ} {ω : Ω} : upcrossings_before a b f ⊥ ω = ⊥ := by simp [upcrossings_before] lemma upcrossings_before_zero : upcrossings_before a b f 0 ω = 0 := by simp [upcrossings_before] @[simp] lemma upcrossings_before_zero' : upcrossings_before a b f 0 = 0 := by { ext ω, exact upcrossings_before_zero } lemma upper_crossing_time_lt_of_le_upcrossings_before (hN : 0 < N) (hab : a < b) (hn : n ≤ upcrossings_before a b f N ω) : upper_crossing_time a b f N n ω < N := begin have : upper_crossing_time a b f N (upcrossings_before a b f N ω) ω < N := (upper_crossing_time_lt_nonempty hN).cSup_mem ((order_bot.bdd_below _).finite_of_bdd_above (upper_crossing_time_lt_bdd_above hab)), exact lt_of_le_of_lt (upper_crossing_time_mono hn) this, end lemma upper_crossing_time_eq_of_upcrossings_before_lt (hab : a < b) (hn : upcrossings_before a b f N ω < n) : upper_crossing_time a b f N n ω = N := begin refine le_antisymm upper_crossing_time_le (not_lt.1 _), convert not_mem_of_cSup_lt hn (upper_crossing_time_lt_bdd_above hab), end lemma upcrossings_before_le (f : ℕ → Ω → ℝ) (ω : Ω) (hab : a < b) : upcrossings_before a b f N ω ≤ N := begin by_cases hN : N = 0, { subst hN, rw upcrossings_before_zero }, { refine cSup_le ⟨0, zero_lt_iff.2 hN⟩ (λ n (hn : _ < _), _), by_contra hnN, exact hn.ne (upper_crossing_time_eq_of_bound_le hab (not_le.1 hnN).le) }, end lemma crossing_eq_crossing_of_lower_crossing_time_lt {M : ℕ} (hNM : N ≤ M) (h : lower_crossing_time a b f N n ω < N) : upper_crossing_time a b f M n ω = upper_crossing_time a b f N n ω ∧ lower_crossing_time a b f M n ω = lower_crossing_time a b f N n ω := begin have h' : upper_crossing_time a b f N n ω < N := lt_of_le_of_lt upper_crossing_time_le_lower_crossing_time h, induction n with k ih, { simp only [nat.nat_zero_eq_zero, upper_crossing_time_zero, bot_eq_zero', eq_self_iff_true, lower_crossing_time_zero, true_and, eq_comm], refine hitting_eq_hitting_of_exists hNM _, simp only [lower_crossing_time, hitting_lt_iff] at h, obtain ⟨j, hj₁, hj₂⟩ := h, exact ⟨j, ⟨hj₁.1, hj₁.2.le⟩, hj₂⟩ }, { specialize ih (lt_of_le_of_lt (lower_crossing_time_mono (nat.le_succ _)) h) (lt_of_le_of_lt (upper_crossing_time_mono (nat.le_succ _)) h'), have : upper_crossing_time a b f M k.succ ω = upper_crossing_time a b f N k.succ ω, { simp only [upper_crossing_time_succ_eq, hitting_lt_iff] at h' ⊢, obtain ⟨j, hj₁, hj₂⟩ := h', rw [eq_comm, ih.2], exact hitting_eq_hitting_of_exists hNM ⟨j, ⟨hj₁.1, hj₁.2.le⟩, hj₂⟩ }, refine ⟨this, _⟩, simp only [lower_crossing_time, eq_comm, this], refine hitting_eq_hitting_of_exists hNM _, rw [lower_crossing_time, hitting_lt_iff _ le_rfl] at h, swap, { apply_instance }, obtain ⟨j, hj₁, hj₂⟩ := h, exact ⟨j, ⟨hj₁.1, hj₁.2.le⟩, hj₂⟩ } end lemma crossing_eq_crossing_of_upper_crossing_time_lt {M : ℕ} (hNM : N ≤ M) (h : upper_crossing_time a b f N (n + 1) ω < N) : upper_crossing_time a b f M (n + 1) ω = upper_crossing_time a b f N (n + 1) ω ∧ lower_crossing_time a b f M n ω = lower_crossing_time a b f N n ω := begin have := (crossing_eq_crossing_of_lower_crossing_time_lt hNM (lt_of_le_of_lt lower_crossing_time_le_upper_crossing_time_succ h)).2, refine ⟨_, this⟩, rw [upper_crossing_time_succ_eq, upper_crossing_time_succ_eq, eq_comm, this], refine hitting_eq_hitting_of_exists hNM _, simp only [upper_crossing_time_succ_eq, hitting_lt_iff] at h, obtain ⟨j, hj₁, hj₂⟩ := h, exact ⟨j, ⟨hj₁.1, hj₁.2.le⟩, hj₂⟩ end lemma upper_crossing_time_eq_upper_crossing_time_of_lt {M : ℕ} (hNM : N ≤ M) (h : upper_crossing_time a b f N n ω < N) : upper_crossing_time a b f M n ω = upper_crossing_time a b f N n ω := begin cases n, { simp }, { exact (crossing_eq_crossing_of_upper_crossing_time_lt hNM h).1 } end lemma upcrossings_before_mono (hab : a < b) : monotone (λ N ω, upcrossings_before a b f N ω) := begin intros N M hNM ω, simp only [upcrossings_before], by_cases hemp : {n : ℕ | upper_crossing_time a b f N n ω < N}.nonempty, { refine cSup_le_cSup (upper_crossing_time_lt_bdd_above hab) hemp (λ n hn, _), rw [set.mem_set_of_eq, upper_crossing_time_eq_upper_crossing_time_of_lt hNM hn], exact lt_of_lt_of_le hn hNM }, { rw set.not_nonempty_iff_eq_empty at hemp, simp [hemp, cSup_empty, bot_eq_zero', zero_le'] } end lemma upcrossings_before_lt_of_exists_upcrossing (hab : a < b) {N₁ N₂ : ℕ} (hN₁: N ≤ N₁) (hN₁': f N₁ ω < a) (hN₂: N₁ ≤ N₂) (hN₂': b < f N₂ ω) : upcrossings_before a b f N ω < upcrossings_before a b f (N₂ + 1) ω := begin refine lt_of_lt_of_le (nat.lt_succ_self _) (le_cSup (upper_crossing_time_lt_bdd_above hab) _), rw [set.mem_set_of_eq, upper_crossing_time_succ_eq, hitting_lt_iff _ le_rfl], swap, { apply_instance }, { refine ⟨N₂, ⟨_, nat.lt_succ_self _⟩, hN₂'.le⟩, rw [lower_crossing_time, hitting_le_iff_of_lt _ (nat.lt_succ_self _)], refine ⟨N₁, ⟨le_trans _ hN₁, hN₂⟩, hN₁'.le⟩, by_cases hN : 0 < N, { have : upper_crossing_time a b f N (upcrossings_before a b f N ω) ω < N := nat.Sup_mem (upper_crossing_time_lt_nonempty hN) (upper_crossing_time_lt_bdd_above hab), rw upper_crossing_time_eq_upper_crossing_time_of_lt (hN₁.trans (hN₂.trans $ nat.le_succ _)) this, exact this.le }, { rw [not_lt, le_zero_iff] at hN, rw [hN, upcrossings_before_zero, upper_crossing_time_zero], refl } }, end lemma lower_crossing_time_lt_of_lt_upcrossings_before (hN : 0 < N) (hab : a < b) (hn : n < upcrossings_before a b f N ω) : lower_crossing_time a b f N n ω < N := lt_of_le_of_lt lower_crossing_time_le_upper_crossing_time_succ (upper_crossing_time_lt_of_le_upcrossings_before hN hab hn) lemma le_sub_of_le_upcrossings_before (hN : 0 < N) (hab : a < b) (hn : n < upcrossings_before a b f N ω) : b - a ≤ stopped_value f (upper_crossing_time a b f N (n + 1)) ω - stopped_value f (lower_crossing_time a b f N n) ω := sub_le_sub (stopped_value_upper_crossing_time (upper_crossing_time_lt_of_le_upcrossings_before hN hab hn).ne) (stopped_value_lower_crossing_time (lower_crossing_time_lt_of_lt_upcrossings_before hN hab hn).ne) lemma sub_eq_zero_of_upcrossings_before_lt (hab : a < b) (hn : upcrossings_before a b f N ω < n) : stopped_value f (upper_crossing_time a b f N (n + 1)) ω - stopped_value f (lower_crossing_time a b f N n) ω = 0 := begin have : N ≤ upper_crossing_time a b f N n ω, { rw upcrossings_before at hn, rw ← not_lt, exact λ h, not_le.2 hn (le_cSup (upper_crossing_time_lt_bdd_above hab) h) }, simp [stopped_value, upper_crossing_time_stabilize' (nat.le_succ n) this, lower_crossing_time_stabilize' le_rfl (le_trans this upper_crossing_time_le_lower_crossing_time)] end lemma mul_upcrossings_before_le (hf : a ≤ f N ω) (hab : a < b) : (b - a) * upcrossings_before a b f N ω ≤ ∑ k in finset.range N, upcrossing_strat a b f N k ω * (f (k + 1) - f k) ω := begin classical, by_cases hN : N = 0, { simp [hN] }, simp_rw [upcrossing_strat, finset.sum_mul, ← set.indicator_mul_left, pi.one_apply, pi.sub_apply, one_mul], rw finset.sum_comm, have h₁ : ∀ k, ∑ n in finset.range N, (set.Ico (lower_crossing_time a b f N k ω) (upper_crossing_time a b f N (k + 1) ω)).indicator (λ m, f (m + 1) ω - f m ω) n = stopped_value f (upper_crossing_time a b f N (k + 1)) ω - stopped_value f (lower_crossing_time a b f N k) ω, { intro k, rw [finset.sum_indicator_eq_sum_filter, (_ : (finset.filter (λ i, i ∈ set.Ico (lower_crossing_time a b f N k ω) (upper_crossing_time a b f N (k + 1) ω)) (finset.range N)) = finset.Ico (lower_crossing_time a b f N k ω) (upper_crossing_time a b f N (k + 1) ω)), finset.sum_Ico_eq_add_neg _ lower_crossing_time_le_upper_crossing_time_succ, finset.sum_range_sub (λ n, f n ω), finset.sum_range_sub (λ n, f n ω), neg_sub, sub_add_sub_cancel], { refl }, { ext i, simp only [set.mem_Ico, finset.mem_filter, finset.mem_range, finset.mem_Ico, and_iff_right_iff_imp, and_imp], exact λ _ h, lt_of_lt_of_le h upper_crossing_time_le } }, simp_rw [h₁], have h₂ : ∑ k in finset.range (upcrossings_before a b f N ω), (b - a) ≤ ∑ k in finset.range N, (stopped_value f (upper_crossing_time a b f N (k + 1)) ω - stopped_value f (lower_crossing_time a b f N k) ω), { calc ∑ k in finset.range (upcrossings_before a b f N ω), (b - a) ≤ ∑ k in finset.range (upcrossings_before a b f N ω), (stopped_value f (upper_crossing_time a b f N (k + 1)) ω - stopped_value f (lower_crossing_time a b f N k) ω) : begin refine finset.sum_le_sum (λ i hi, le_sub_of_le_upcrossings_before (zero_lt_iff.2 hN) hab _), rwa finset.mem_range at hi, end ...≤ ∑ k in finset.range N, (stopped_value f (upper_crossing_time a b f N (k + 1)) ω - stopped_value f (lower_crossing_time a b f N k) ω) : begin refine finset.sum_le_sum_of_subset_of_nonneg (finset.range_subset.2 (upcrossings_before_le f ω hab)) (λ i _ hi, _), by_cases hi' : i = upcrossings_before a b f N ω, { subst hi', simp only [stopped_value], rw upper_crossing_time_eq_of_upcrossings_before_lt hab (nat.lt_succ_self _), by_cases heq : lower_crossing_time a b f N (upcrossings_before a b f N ω) ω = N, { rw [heq, sub_self] }, { rw sub_nonneg, exact le_trans (stopped_value_lower_crossing_time heq) hf } }, { rw sub_eq_zero_of_upcrossings_before_lt hab, rw [finset.mem_range, not_lt] at hi, exact lt_of_le_of_ne hi (ne.symm hi') }, end }, refine le_trans _ h₂, rw [finset.sum_const, finset.card_range, nsmul_eq_mul, mul_comm], end lemma integral_mul_upcrossings_before_le_integral [is_finite_measure μ] (hf : submartingale f ℱ μ) (hfN : ∀ ω, a ≤ f N ω) (hfzero : 0 ≤ f 0) (hab : a < b) : (b - a) * μ[upcrossings_before a b f N] ≤ μ[f N] := calc (b - a) * μ[upcrossings_before a b f N] ≤ μ[∑ k in finset.range N, upcrossing_strat a b f N k * (f (k + 1) - f k)] : begin rw ← integral_mul_left, refine integral_mono_of_nonneg _ ((hf.sum_upcrossing_strat_mul a b N).integrable N) _, { exact eventually_of_forall (λ ω, mul_nonneg (sub_nonneg.2 hab.le) (nat.cast_nonneg _)) }, { refine eventually_of_forall (λ ω, _), simpa using mul_upcrossings_before_le (hfN ω) hab }, end ...≤ μ[f N] - μ[f 0] : hf.sum_mul_upcrossing_strat_le ...≤ μ[f N] : (sub_le_self_iff _).2 (integral_nonneg hfzero) lemma crossing_pos_eq (hab : a < b) : upper_crossing_time 0 (b - a) (λ n ω, (f n ω - a)⁺) N n = upper_crossing_time a b f N n ∧ lower_crossing_time 0 (b - a) (λ n ω, (f n ω - a)⁺) N n = lower_crossing_time a b f N n := begin have hab' : 0 < b - a := sub_pos.2 hab, have hf : ∀ ω i, b - a ≤ (f i ω - a)⁺ ↔ b ≤ f i ω, { intros i ω, refine ⟨λ h, _, λ h, _⟩, { rwa [← sub_le_sub_iff_right a, ← lattice_ordered_comm_group.pos_eq_self_of_pos_pos (lt_of_lt_of_le hab' h)] }, { rw ← sub_le_sub_iff_right a at h, rwa lattice_ordered_comm_group.pos_of_nonneg _ (le_trans hab'.le h) } }, have hf' : ∀ ω i, (f i ω - a)⁺ ≤ 0 ↔ f i ω ≤ a, { intros ω i, rw [lattice_ordered_comm_group.pos_nonpos_iff, sub_nonpos] }, induction n with k ih, { refine ⟨rfl, _⟩, simp only [lower_crossing_time_zero, hitting, set.mem_Icc, set.mem_Iic], ext ω, split_ifs with h₁ h₂ h₂, { simp_rw [hf'] }, { simp_rw [set.mem_Iic, ← hf' _ _] at h₂, exact false.elim (h₂ h₁) }, { simp_rw [set.mem_Iic, hf' _ _] at h₁, exact false.elim (h₁ h₂) }, { refl } }, { have : upper_crossing_time 0 (b - a) (λ n ω, (f n ω - a)⁺) N (k + 1) = upper_crossing_time a b f N (k + 1), { ext ω, simp only [upper_crossing_time_succ_eq, ← ih.2, hitting, set.mem_Ici, tsub_le_iff_right], split_ifs with h₁ h₂ h₂, { simp_rw [← sub_le_iff_le_add, hf ω] }, { simp_rw [set.mem_Ici, ← hf _ _] at h₂, exact false.elim (h₂ h₁) }, { simp_rw [set.mem_Ici, hf _ _] at h₁, exact false.elim (h₁ h₂) }, { refl } }, refine ⟨this, _⟩, ext ω, simp only [lower_crossing_time, this, hitting, set.mem_Iic], split_ifs with h₁ h₂ h₂, { simp_rw [hf' ω] }, { simp_rw [set.mem_Iic, ← hf' _ _] at h₂, exact false.elim (h₂ h₁) }, { simp_rw [set.mem_Iic, hf' _ _] at h₁, exact false.elim (h₁ h₂) }, { refl } } end lemma upcrossings_before_pos_eq (hab : a < b) : upcrossings_before 0 (b - a) (λ n ω, (f n ω - a)⁺) N ω = upcrossings_before a b f N ω := by simp_rw [upcrossings_before, (crossing_pos_eq hab).1] lemma mul_integral_upcrossings_before_le_integral_pos_part_aux [is_finite_measure μ] (hf : submartingale f ℱ μ) (hab : a < b) : (b - a) * μ[upcrossings_before a b f N] ≤ μ[λ ω, (f N ω - a)⁺] := begin refine le_trans (le_of_eq _) (integral_mul_upcrossings_before_le_integral (hf.sub_martingale (martingale_const _ _ _)).pos (λ ω, lattice_ordered_comm_group.pos_nonneg _) (λ ω, lattice_ordered_comm_group.pos_nonneg _) (sub_pos.2 hab)), simp_rw [sub_zero, ← upcrossings_before_pos_eq hab], refl, end /-- **Doob's upcrossing estimate**: given a real valued discrete submartingale `f` and real values `a` and `b`, we have `(b - a) * 𝔼[upcrossings_before a b f N] ≤ 𝔼[(f N - a)⁺]` where `upcrossings_before a b f N` is the number of times the process `f` crossed from below `a` to above `b` before the time `N`. -/ theorem submartingale.mul_integral_upcrossings_before_le_integral_pos_part [is_finite_measure μ] (a b : ℝ) (hf : submartingale f ℱ μ) (N : ℕ) : (b - a) * μ[upcrossings_before a b f N] ≤ μ[λ ω, (f N ω - a)⁺] := begin by_cases hab : a < b, { exact mul_integral_upcrossings_before_le_integral_pos_part_aux hf hab }, { rw [not_lt, ← sub_nonpos] at hab, exact le_trans (mul_nonpos_of_nonpos_of_nonneg hab (integral_nonneg (λ ω, nat.cast_nonneg _))) (integral_nonneg (λ ω, lattice_ordered_comm_group.pos_nonneg _)) } end /-! ### Variant of the upcrossing estimate Now, we would like to prove a variant of the upcrossing estimate obtained by taking the supremum over $N$ of the original upcrossing estimate. Namely, we want the inequality $$ (b - a) \sup_N \mathbb{E}[U_N(a, b)] \le \sup_N \mathbb{E}[f_N]. $$ This inequality is central for the martingale convergence theorem as it provides a uniform bound for the upcrossings. We note that on top of taking the supremum on both sides of the inequality, we had also used the monotone convergence theorem on the left hand side to take the supremum outside of the integral. To do this, we need to make sure $U_N(a, b)$ is measurable and integrable. Integrability is easy to check as $U_N(a, b) ≤ N$ and so it suffices to show measurability. Indeed, by noting that $$ U_N(a, b) = \sum_{i = 1}^N \mathbf{1}_{\{U_N(a, b) < N\}} $$ $U_N(a, b)$ is measurable as $\{U_N(a, b) < N\}$ is a measurable set since $U_N(a, b)$ is a stopping time. -/ lemma upcrossings_before_eq_sum (hab : a < b) : upcrossings_before a b f N ω = ∑ i in finset.Ico 1 (N + 1), {n | upper_crossing_time a b f N n ω < N}.indicator 1 i := begin by_cases hN : N = 0, { simp [hN] }, rw ← finset.sum_Ico_consecutive _ (nat.succ_le_succ zero_le') (nat.succ_le_succ (upcrossings_before_le f ω hab)), have h₁ : ∀ k ∈ finset.Ico 1 (upcrossings_before a b f N ω + 1), {n : ℕ | upper_crossing_time a b f N n ω < N}.indicator 1 k = 1, { rintro k hk, rw finset.mem_Ico at hk, rw set.indicator_of_mem, { refl }, { exact upper_crossing_time_lt_of_le_upcrossings_before (zero_lt_iff.2 hN) hab (nat.lt_succ_iff.1 hk.2) } }, have h₂ : ∀ k ∈ finset.Ico (upcrossings_before a b f N ω + 1) (N + 1), {n : ℕ | upper_crossing_time a b f N n ω < N}.indicator 1 k = 0, { rintro k hk, rw [finset.mem_Ico, nat.succ_le_iff] at hk, rw set.indicator_of_not_mem, simp only [set.mem_set_of_eq, not_lt], exact (upper_crossing_time_eq_of_upcrossings_before_lt hab hk.1).symm.le }, rw [finset.sum_congr rfl h₁, finset.sum_congr rfl h₂, finset.sum_const, finset.sum_const, smul_eq_mul, mul_one, smul_eq_mul, mul_zero, nat.card_Ico, nat.add_succ_sub_one, add_zero, add_zero], end lemma adapted.measurable_upcrossings_before (hf : adapted ℱ f) (hab : a < b) : measurable (upcrossings_before a b f N) := begin have : upcrossings_before a b f N = λ ω, ∑ i in finset.Ico 1 (N + 1), {n | upper_crossing_time a b f N n ω < N}.indicator 1 i, { ext ω, exact upcrossings_before_eq_sum hab }, rw this, exact finset.measurable_sum _ (λ i hi, measurable.indicator measurable_const $ ℱ.le N _ (hf.is_stopping_time_upper_crossing_time.measurable_set_lt_of_pred N)) end lemma adapted.integrable_upcrossings_before [is_finite_measure μ] (hf : adapted ℱ f) (hab : a < b) : integrable (λ ω, (upcrossings_before a b f N ω : ℝ)) μ := begin have : ∀ᵐ ω ∂μ, ‖(upcrossings_before a b f N ω : ℝ)‖ ≤ N, { refine eventually_of_forall (λ ω, _), rw [real.norm_eq_abs, nat.abs_cast, nat.cast_le], refine upcrossings_before_le _ _ hab }, exact ⟨measurable.ae_strongly_measurable (measurable_from_top.comp (hf.measurable_upcrossings_before hab)), has_finite_integral_of_bounded this⟩ end /-- The number of upcrossings of a realization of a stochastic process (`upcrossing` takes value in `ℝ≥0∞` and so is allowed to be `∞`). -/ noncomputable def upcrossings [preorder ι] [order_bot ι] [has_Inf ι] (a b : ℝ) (f : ι → Ω → ℝ) (ω : Ω) : ℝ≥0∞ := ⨆ N, (upcrossings_before a b f N ω : ℝ≥0∞) lemma adapted.measurable_upcrossings (hf : adapted ℱ f) (hab : a < b) : measurable (upcrossings a b f) := measurable_supr (λ N, measurable_from_top.comp (hf.measurable_upcrossings_before hab)) lemma upcrossings_lt_top_iff : upcrossings a b f ω < ∞ ↔ ∃ k, ∀ N, upcrossings_before a b f N ω ≤ k := begin have : upcrossings a b f ω < ∞ ↔ ∃ k : ℝ≥0, upcrossings a b f ω ≤ k, { split, { intro h, lift upcrossings a b f ω to ℝ≥0 using h.ne with r hr, exact ⟨r, le_rfl⟩ }, { rintro ⟨k, hk⟩, exact lt_of_le_of_lt hk ennreal.coe_lt_top } }, simp_rw [this, upcrossings, supr_le_iff], split; rintro ⟨k, hk⟩, { obtain ⟨m, hm⟩ := exists_nat_ge k, refine ⟨m, λ N, nat.cast_le.1 ((hk N).trans _)⟩, rwa [← ennreal.coe_nat, ennreal.coe_le_coe] }, { refine ⟨k, λ N, _⟩, simp only [ennreal.coe_nat, nat.cast_le, hk N] } end /-- A variant of Doob's upcrossing estimate obtained by taking the supremum on both sides. -/ lemma submartingale.mul_lintegral_upcrossings_le_lintegral_pos_part [is_finite_measure μ] (a b : ℝ) (hf : submartingale f ℱ μ) : ennreal.of_real (b - a) * ∫⁻ ω, upcrossings a b f ω ∂μ ≤ ⨆ N, ∫⁻ ω, ennreal.of_real ((f N ω - a)⁺) ∂μ := begin by_cases hab : a < b, { simp_rw [upcrossings], have : ∀ N, ∫⁻ ω, ennreal.of_real ((f N ω - a)⁺) ∂μ = ennreal.of_real (∫ ω, (f N ω - a)⁺ ∂μ), { intro N, rw of_real_integral_eq_lintegral_of_real, { exact (hf.sub_martingale (martingale_const _ _ _)).pos.integrable _ }, { exact eventually_of_forall (λ ω, lattice_ordered_comm_group.pos_nonneg _) } }, rw lintegral_supr', { simp_rw [this, ennreal.mul_supr, supr_le_iff], intro N, rw [(by simp : ∫⁻ ω, upcrossings_before a b f N ω ∂μ = ∫⁻ ω, ↑(upcrossings_before a b f N ω : ℝ≥0) ∂μ), lintegral_coe_eq_integral, ← ennreal.of_real_mul (sub_pos.2 hab).le], { simp_rw [nnreal.coe_nat_cast], exact (ennreal.of_real_le_of_real (hf.mul_integral_upcrossings_before_le_integral_pos_part a b N)).trans (le_supr _ N) }, { simp only [nnreal.coe_nat_cast, hf.adapted.integrable_upcrossings_before hab] } }, { exact λ n, measurable_from_top.comp_ae_measurable (hf.adapted.measurable_upcrossings_before hab).ae_measurable }, { refine eventually_of_forall (λ ω N M hNM, _), rw nat.cast_le, exact upcrossings_before_mono hab hNM ω } }, { rw [not_lt, ← sub_nonpos] at hab, rw [ennreal.of_real_of_nonpos hab, zero_mul], exact zero_le _ } end end measure_theory
3ca4997d2bd58b0204ed86a2948dd93efc84b910
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/group_theory/is_free_group.lean
182863cda9e1134c96ed10a863ab0b4b78c84fa5
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
5,515
lean
/- Copyright (c) 2021 David Wärn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Wärn, Eric Wieser, Joachim Breitner -/ import group_theory.free_group /-! # Free groups structures on arbitrary types > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines a type class for type that are free groups, together with the usual operations. The type class can be instantiated by providing an isomorphim to the canonical free group, or by proving that the universal property holds. For the explicit construction of free groups, see `group_theory/free_group`. ## Main definitions * `is_free_group G` - a typeclass to indicate that `G` is free over some generators * `is_free_group.of` - the canonical injection of `G`'s generators into `G` * `is_free_group.lift` - the universal property of the free group ## Main results * `is_free_group.to_free_group` - any free group with generators `A` is equivalent to `free_group A`. * `is_free_group.unique_lift` - the universal property of a free group * `is_free_group.of_unique_lift` - constructing `is_free_group` from the universal property -/ universes u /-- `is_free_group G` means that `G` isomorphic to a free group. -/ class is_free_group (G : Type u) [group G] := (generators : Type u) (mul_equiv [] : free_group generators ≃* G) instance (X : Type*) : is_free_group (free_group X) := { generators := X, mul_equiv := mul_equiv.refl _ } namespace is_free_group variables (G : Type*) [group G] [is_free_group G] /-- Any free group is isomorphic to "the" free group. -/ @[simps] def to_free_group : G ≃* free_group (generators G) := (mul_equiv G).symm variable {G} /-- The canonical injection of G's generators into G -/ def of : generators G → G := (mul_equiv G).to_fun ∘ free_group.of @[simp] lemma of_eq_free_group_of {A : Type u} : (@of (free_group A) _ _ ) = free_group.of := rfl variables {H : Type*} [group H] /-- The equivalence between functions on the generators and group homomorphisms from a free group given by those generators. -/ def lift : (generators G → H) ≃ (G →* H) := free_group.lift.trans { to_fun := λ f, f.comp (mul_equiv G).symm.to_monoid_hom, inv_fun := λ f, f.comp (mul_equiv G).to_monoid_hom, left_inv := λ f, by { ext, simp, }, right_inv := λ f, by { ext, simp, }, } @[simp] lemma lift'_eq_free_group_lift {A : Type u} : (@lift (free_group A) _ _ H _) = free_group.lift := rfl @[simp] lemma lift_of (f : generators G → H) (a : generators G) : lift f (of a) = f a := congr_fun (lift.symm_apply_apply f) a @[simp] lemma lift_symm_apply (f : G →* H) (a : generators G) : (lift.symm f) a = f (of a) := rfl @[ext] lemma ext_hom ⦃f g : G →* H⦄ (h : ∀ (a : generators G), f (of a) = g (of a)) : f = g := lift.symm.injective (funext h) /-- The universal property of a free group: A functions from the generators of `G` to another group extends in a unique way to a homomorphism from `G`. Note that since `is_free_group.lift` is expressed as a bijection, it already expresses the universal property. -/ lemma unique_lift (f : generators G → H) : ∃! F : G →* H, ∀ a, F (of a) = f a := by simpa only [function.funext_iff] using lift.symm.bijective.exists_unique f /-- If a group satisfies the universal property of a free group, then it is a free group, where the universal property is expressed as in `is_free_group.lift` and its properties. -/ def of_lift {G : Type u} [group G] (X : Type u) (of : X → G) (lift : ∀ {H : Type u} [group H], by exactI (X → H) ≃ (G →* H)) (lift_of : ∀ {H : Type u} [group H], by exactI ∀ (f : X → H) a, lift f (of a) = f a) : is_free_group G := { generators := X, mul_equiv := monoid_hom.to_mul_equiv (free_group.lift of) (lift free_group.of) begin apply free_group.ext_hom, intro x, simp only [monoid_hom.coe_comp, function.comp_app, monoid_hom.id_apply, free_group.lift.of, lift_of], end begin let lift_symm_of : ∀ {H : Type u} [group H], by exactI ∀ (f : G →* H) a, lift.symm f a = f (of a) := by introsI H _ f a; simp [← lift_of (lift.symm f)], apply lift.symm.injective, ext x, simp only [monoid_hom.coe_comp, function.comp_app, monoid_hom.id_apply, free_group.lift.of, lift_of, lift_symm_of], end } /-- If a group satisfies the universal property of a free group, then it is a free group, where the universal property is expressed as in `is_free_group.unique_lift`. -/ noncomputable def of_unique_lift {G : Type u} [group G] (X : Type u) (of : X → G) (h : ∀ {H : Type u} [group H] (f : X → H), by exactI ∃! F : G →* H, ∀ a, F (of a) = f a) : is_free_group G := let lift {H : Type u} [group H] : by exactI (X → H) ≃ (G →* H) := by exactI { to_fun := λ f, classical.some (h f), inv_fun := λ F, F ∘ of, left_inv := λ f, funext (classical.some_spec (h f)).left, right_inv := λ F, ((classical.some_spec (h (F ∘ of))).right F (λ _, rfl)).symm } in let lift_of {H : Type u} [group H] (f : X → H) (a : X) : by exactI lift f (of a) = f a := by exactI congr_fun (lift.symm_apply_apply f) a in of_lift X of @lift @lift_of /-- Being a free group transports across group isomorphisms. -/ def of_mul_equiv {H : Type*} [group H] (h : G ≃* H) : is_free_group H := { generators := generators G, mul_equiv := (mul_equiv G).trans h } end is_free_group
92269ba7386f876f40786031a7161e93eeaf7760
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/analysis/special_functions/pow.lean
c4d7e1ce921a95e9d638e124ef0d6a617285986b
[ "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
71,315
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Sébastien Gouëzel, Rémy Degenne -/ import analysis.special_functions.trigonometric import analysis.calculus.extend_deriv /-! # Power function on `ℂ`, `ℝ`, `ℝ≥0`, and `ℝ≥0∞` We construct the power functions `x ^ y` where * `x` and `y` are complex numbers, * or `x` and `y` are real numbers, * or `x` is a nonnegative real number and `y` is a real number; * or `x` is a number from `[0, +∞]` (a.k.a. `ℝ≥0∞`) and `y` is a real number. We also prove basic properties of these functions. -/ noncomputable theory open_locale classical real topological_space nnreal ennreal filter open filter namespace complex /-- The complex power function `x^y`, given by `x^y = exp(y log x)` (where `log` is the principal determination of the logarithm), unless `x = 0` where one sets `0^0 = 1` and `0^y = 0` for `y ≠ 0`. -/ noncomputable def cpow (x y : ℂ) : ℂ := if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) noncomputable instance : has_pow ℂ ℂ := ⟨cpow⟩ @[simp] lemma cpow_eq_pow (x y : ℂ) : cpow x y = x ^ y := rfl lemma cpow_def (x y : ℂ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) := rfl lemma cpow_def_of_ne_zero {x : ℂ} (hx : x ≠ 0) (y : ℂ) : x ^ y = exp (log x * y) := if_neg hx @[simp] lemma cpow_zero (x : ℂ) : x ^ (0 : ℂ) = 1 := by simp [cpow_def] @[simp] lemma cpow_eq_zero_iff (x y : ℂ) : x ^ y = 0 ↔ x = 0 ∧ y ≠ 0 := by { simp only [cpow_def], split_ifs; simp [*, exp_ne_zero] } @[simp] lemma zero_cpow {x : ℂ} (h : x ≠ 0) : (0 : ℂ) ^ x = 0 := by simp [cpow_def, *] @[simp] lemma cpow_one (x : ℂ) : x ^ (1 : ℂ) = x := if hx : x = 0 then by simp [hx, cpow_def] else by rw [cpow_def, if_neg (one_ne_zero : (1 : ℂ) ≠ 0), if_neg hx, mul_one, exp_log hx] @[simp] lemma one_cpow (x : ℂ) : (1 : ℂ) ^ x = 1 := by rw cpow_def; split_ifs; simp [one_ne_zero, *] at * lemma cpow_add {x : ℂ} (y z : ℂ) (hx : x ≠ 0) : x ^ (y + z) = x ^ y * x ^ z := by simp [cpow_def]; split_ifs; simp [*, exp_add, mul_add] at * lemma cpow_mul {x y : ℂ} (z : ℂ) (h₁ : -π < (log x * y).im) (h₂ : (log x * y).im ≤ π) : x ^ (y * z) = (x ^ y) ^ z := begin simp only [cpow_def], split_ifs; simp [*, exp_ne_zero, log_exp h₁ h₂, mul_assoc] at * end lemma cpow_neg (x y : ℂ) : x ^ -y = (x ^ y)⁻¹ := by simp [cpow_def]; split_ifs; simp [exp_neg] lemma cpow_sub {x : ℂ} (y z : ℂ) (hx : x ≠ 0) : x ^ (y - z) = x ^ y / x ^ z := by rw [sub_eq_add_neg, cpow_add _ _ hx, cpow_neg, div_eq_mul_inv] lemma cpow_neg_one (x : ℂ) : x ^ (-1 : ℂ) = x⁻¹ := by simpa using cpow_neg x 1 @[simp] lemma cpow_nat_cast (x : ℂ) : ∀ (n : ℕ), x ^ (n : ℂ) = x ^ n | 0 := by simp | (n + 1) := if hx : x = 0 then by simp only [hx, pow_succ, complex.zero_cpow (nat.cast_ne_zero.2 (nat.succ_ne_zero _)), zero_mul] else by simp [cpow_add, hx, pow_add, cpow_nat_cast n] @[simp] lemma cpow_int_cast (x : ℂ) : ∀ (n : ℤ), x ^ (n : ℂ) = x ^ n | (n : ℕ) := by simp; refl | -[1+ n] := by rw gpow_neg_succ_of_nat; simp only [int.neg_succ_of_nat_coe, int.cast_neg, complex.cpow_neg, inv_eq_one_div, int.cast_coe_nat, cpow_nat_cast] lemma cpow_nat_inv_pow (x : ℂ) {n : ℕ} (hn : 0 < n) : (x ^ (n⁻¹ : ℂ)) ^ n = x := begin suffices : im (log x * n⁻¹) ∈ set.Ioc (-π) π, { rw [← cpow_nat_cast, ← cpow_mul _ this.1 this.2, inv_mul_cancel, cpow_one], exact_mod_cast hn.ne' }, rw [mul_comm, ← of_real_nat_cast, ← of_real_inv, of_real_mul_im, ← div_eq_inv_mul], have hn' : 0 < (n : ℝ), by assumption_mod_cast, have hn1 : 1 ≤ (n : ℝ), by exact_mod_cast (nat.succ_le_iff.2 hn), split, { rw lt_div_iff hn', calc -π * n ≤ -π * 1 : mul_le_mul_of_nonpos_left hn1 (neg_nonpos.2 real.pi_pos.le) ... = -π : mul_one _ ... < im (log x) : neg_pi_lt_log_im _ }, { rw div_le_iff hn', calc im (log x) ≤ π : log_im_le_pi _ ... = π * 1 : (mul_one π).symm ... ≤ π * n : mul_le_mul_of_nonneg_left hn1 real.pi_pos.le } end lemma has_strict_fderiv_at_cpow {p : ℂ × ℂ} (hp : 0 < p.1.re ∨ p.1.im ≠ 0) : has_strict_fderiv_at (λ x : ℂ × ℂ, x.1 ^ x.2) ((p.2 * p.1 ^ (p.2 - 1)) • continuous_linear_map.fst ℂ ℂ ℂ + (p.1 ^ p.2 * log p.1) • continuous_linear_map.snd ℂ ℂ ℂ) p := begin have A : p.1 ≠ 0, by { intro h, simpa [h, lt_irrefl] using hp }, have : (λ x : ℂ × ℂ, x.1 ^ x.2) =ᶠ[𝓝 p] (λ x, exp (log x.1 * x.2)), from ((is_open_ne.preimage continuous_fst).eventually_mem A).mono (λ p hp, cpow_def_of_ne_zero hp _), rw [cpow_sub _ _ A, cpow_one, mul_div_comm, mul_smul, mul_smul, ← smul_add], refine has_strict_fderiv_at.congr_of_eventually_eq _ this.symm, simpa only [cpow_def_of_ne_zero A, div_eq_mul_inv, smul_smul, add_comm] using ((has_strict_fderiv_at_fst.clog hp).mul has_strict_fderiv_at_snd).cexp end lemma has_strict_deriv_at_const_cpow {x y : ℂ} (h : x ≠ 0 ∨ y ≠ 0) : has_strict_deriv_at (λ y, x ^ y) (x ^ y * log x) y := begin rcases em (x = 0) with rfl|hx, { replace h := h.neg_resolve_left rfl, rw [log_zero, mul_zero], refine (has_strict_deriv_at_const _ 0).congr_of_eventually_eq _, exact (is_open_ne.eventually_mem h).mono (λ y hy, (zero_cpow hy).symm) }, { simpa only [cpow_def_of_ne_zero hx, mul_one] using ((has_strict_deriv_at_id y).const_mul (log x)).cexp } end lemma has_fderiv_at_cpow {p : ℂ × ℂ} (hp : 0 < p.1.re ∨ p.1.im ≠ 0) : has_fderiv_at (λ x : ℂ × ℂ, x.1 ^ x.2) ((p.2 * p.1 ^ (p.2 - 1)) • continuous_linear_map.fst ℂ ℂ ℂ + (p.1 ^ p.2 * log p.1) • continuous_linear_map.snd ℂ ℂ ℂ) p := (has_strict_fderiv_at_cpow hp).has_fderiv_at end complex section lim open complex variables {α : Type*} lemma filter.tendsto.cpow {l : filter α} {f g : α → ℂ} {a b : ℂ} (hf : tendsto f l (𝓝 a)) (hg : tendsto g l (𝓝 b)) (ha : 0 < a.re ∨ a.im ≠ 0) : tendsto (λ x, f x ^ g x) l (𝓝 (a ^ b)) := (@has_fderiv_at_cpow (a, b) ha).continuous_at.tendsto.comp (hf.prod_mk_nhds hg) lemma filter.tendsto.const_cpow {l : filter α} {f : α → ℂ} {a b : ℂ} (hf : tendsto f l (𝓝 b)) (h : a ≠ 0 ∨ b ≠ 0) : tendsto (λ x, a ^ f x) l (𝓝 (a ^ b)) := (has_strict_deriv_at_const_cpow h).continuous_at.tendsto.comp hf variables [topological_space α] {f g : α → ℂ} {s : set α} {a : α} lemma continuous_within_at.cpow (hf : continuous_within_at f s a) (hg : continuous_within_at g s a) (h0 : 0 < (f a).re ∨ (f a).im ≠ 0) : continuous_within_at (λ x, f x ^ g x) s a := hf.cpow hg h0 lemma continuous_within_at.const_cpow {b : ℂ} (hf : continuous_within_at f s a) (h : b ≠ 0 ∨ f a ≠ 0) : continuous_within_at (λ x, b ^ f x) s a := hf.const_cpow h lemma continuous_at.cpow (hf : continuous_at f a) (hg : continuous_at g a) (h0 : 0 < (f a).re ∨ (f a).im ≠ 0) : continuous_at (λ x, f x ^ g x) a := hf.cpow hg h0 lemma continuous_at.const_cpow {b : ℂ} (hf : continuous_at f a) (h : b ≠ 0 ∨ f a ≠ 0) : continuous_at (λ x, b ^ f x) a := hf.const_cpow h lemma continuous_on.cpow (hf : continuous_on f s) (hg : continuous_on g s) (h0 : ∀ a ∈ s, 0 < (f a).re ∨ (f a).im ≠ 0) : continuous_on (λ x, f x ^ g x) s := λ a ha, (hf a ha).cpow (hg a ha) (h0 a ha) lemma continuous_on.const_cpow {b : ℂ} (hf : continuous_on f s) (h : b ≠ 0 ∨ ∀ a ∈ s, f a ≠ 0) : continuous_on (λ x, b ^ f x) s := λ a ha, (hf a ha).const_cpow (h.imp id $ λ h, h a ha) lemma continuous.cpow (hf : continuous f) (hg : continuous g) (h0 : ∀ a, 0 < (f a).re ∨ (f a).im ≠ 0) : continuous (λ x, f x ^ g x) := continuous_iff_continuous_at.2 $ λ a, (hf.continuous_at.cpow hg.continuous_at (h0 a)) lemma continuous.const_cpow {b : ℂ} (hf : continuous f) (h : b ≠ 0 ∨ ∀ a, f a ≠ 0) : continuous (λ x, b ^ f x) := continuous_iff_continuous_at.2 $ λ a, (hf.continuous_at.const_cpow $ h.imp id $ λ h, h a) end lim section fderiv open complex variables {E : Type*} [normed_group E] [normed_space ℂ E] {f g : E → ℂ} {f' g' : E →L[ℂ] ℂ} {x : E} {s : set E} {c : ℂ} lemma has_strict_fderiv_at.cpow (hf : has_strict_fderiv_at f f' x) (hg : has_strict_fderiv_at g g' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_strict_fderiv_at (λ x, f x ^ g x) ((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * log (f x)) • g') x := by convert (@has_strict_fderiv_at_cpow ((λ x, (f x, g x)) x) h0).comp x (hf.prod hg) lemma has_strict_fderiv_at.const_cpow (hf : has_strict_fderiv_at f f' x) (h0 : c ≠ 0 ∨ f x ≠ 0) : has_strict_fderiv_at (λ x, c ^ f x) ((c ^ f x * log c) • f') x := (has_strict_deriv_at_const_cpow h0).comp_has_strict_fderiv_at x hf lemma has_fderiv_at.cpow (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_fderiv_at (λ x, f x ^ g x) ((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * log (f x)) • g') x := by convert (@complex.has_fderiv_at_cpow ((λ x, (f x, g x)) x) h0).comp x (hf.prod hg) lemma has_fderiv_at.const_cpow (hf : has_fderiv_at f f' x) (h0 : c ≠ 0 ∨ f x ≠ 0) : has_fderiv_at (λ x, c ^ f x) ((c ^ f x * log c) • f') x := (has_strict_deriv_at_const_cpow h0).has_deriv_at.comp_has_fderiv_at x hf lemma has_fderiv_within_at.cpow (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_fderiv_within_at (λ x, f x ^ g x) ((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * log (f x)) • g') s x := by convert (@complex.has_fderiv_at_cpow ((λ x, (f x, g x)) x) h0).comp_has_fderiv_within_at x (hf.prod hg) lemma has_fderiv_within_at.const_cpow (hf : has_fderiv_within_at f f' s x) (h0 : c ≠ 0 ∨ f x ≠ 0) : has_fderiv_within_at (λ x, c ^ f x) ((c ^ f x * log c) • f') s x := (has_strict_deriv_at_const_cpow h0).has_deriv_at.comp_has_fderiv_within_at x hf lemma differentiable_at.cpow (hf : differentiable_at ℂ f x) (hg : differentiable_at ℂ g x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : differentiable_at ℂ (λ x, f x ^ g x) x := (hf.has_fderiv_at.cpow hg.has_fderiv_at h0).differentiable_at lemma differentiable_at.const_cpow (hf : differentiable_at ℂ f x) (h0 : c ≠ 0 ∨ f x ≠ 0) : differentiable_at ℂ (λ x, c ^ f x) x := (hf.has_fderiv_at.const_cpow h0).differentiable_at lemma differentiable_within_at.cpow (hf : differentiable_within_at ℂ f s x) (hg : differentiable_within_at ℂ g s x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : differentiable_within_at ℂ (λ x, f x ^ g x) s x := (hf.has_fderiv_within_at.cpow hg.has_fderiv_within_at h0).differentiable_within_at lemma differentiable_within_at.const_cpow (hf : differentiable_within_at ℂ f s x) (h0 : c ≠ 0 ∨ f x ≠ 0) : differentiable_within_at ℂ (λ x, c ^ f x) s x := (hf.has_fderiv_within_at.const_cpow h0).differentiable_within_at end fderiv section deriv open complex variables {f g : ℂ → ℂ} {s : set ℂ} {f' g' x c : ℂ} /-- A private lemma that rewrites the output of lemmas like `has_fderiv_at.cpow` to the form expected by lemmas like `has_deriv_at.cpow`. -/ private lemma aux : ((g x * f x ^ (g x - 1)) • (1 : ℂ →L[ℂ] ℂ).smul_right f' + (f x ^ g x * log (f x)) • (1 : ℂ →L[ℂ] ℂ).smul_right g') 1 = g x * f x ^ (g x - 1) * f' + f x ^ g x * log (f x) * g' := by simp only [algebra.id.smul_eq_mul, one_mul, continuous_linear_map.one_apply, continuous_linear_map.smul_right_apply, continuous_linear_map.add_apply, pi.smul_apply, continuous_linear_map.coe_smul'] lemma has_strict_deriv_at.cpow (hf : has_strict_deriv_at f f' x) (hg : has_strict_deriv_at g g' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_strict_deriv_at (λ x, f x ^ g x) (g x * f x ^ (g x - 1) * f' + f x ^ g x * log (f x) * g') x := by simpa only [aux] using (hf.cpow hg h0).has_strict_deriv_at lemma has_strict_deriv_at.const_cpow (hf : has_strict_deriv_at f f' x) (h : c ≠ 0 ∨ f x ≠ 0) : has_strict_deriv_at (λ x, c ^ f x) (c ^ f x * log c * f') x := (has_strict_deriv_at_const_cpow h).comp x hf lemma complex.has_strict_deriv_at_cpow_const (h : 0 < x.re ∨ x.im ≠ 0) : has_strict_deriv_at (λ z : ℂ, z ^ c) (c * x ^ (c - 1)) x := by simpa only [mul_zero, add_zero, mul_one] using (has_strict_deriv_at_id x).cpow (has_strict_deriv_at_const x c) h lemma has_strict_deriv_at.cpow_const (hf : has_strict_deriv_at f f' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_strict_deriv_at (λ x, f x ^ c) (c * f x ^ (c - 1) * f') x := (complex.has_strict_deriv_at_cpow_const h0).comp x hf lemma has_deriv_at.cpow (hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_deriv_at (λ x, f x ^ g x) (g x * f x ^ (g x - 1) * f' + f x ^ g x * log (f x) * g') x := by simpa only [aux] using (hf.has_fderiv_at.cpow hg h0).has_deriv_at lemma has_deriv_at.const_cpow (hf : has_deriv_at f f' x) (h0 : c ≠ 0 ∨ f x ≠ 0) : has_deriv_at (λ x, c ^ f x) (c ^ f x * log c * f') x := (has_strict_deriv_at_const_cpow h0).has_deriv_at.comp x hf lemma has_deriv_at.cpow_const (hf : has_deriv_at f f' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_deriv_at (λ x, f x ^ c) (c * f x ^ (c - 1) * f') x := (complex.has_strict_deriv_at_cpow_const h0).has_deriv_at.comp x hf lemma has_deriv_within_at.cpow (hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_deriv_within_at (λ x, f x ^ g x) (g x * f x ^ (g x - 1) * f' + f x ^ g x * log (f x) * g') s x := by simpa only [aux] using (hf.has_fderiv_within_at.cpow hg h0).has_deriv_within_at lemma has_deriv_within_at.const_cpow (hf : has_deriv_within_at f f' s x) (h0 : c ≠ 0 ∨ f x ≠ 0) : has_deriv_within_at (λ x, c ^ f x) (c ^ f x * log c * f') s x := (has_strict_deriv_at_const_cpow h0).has_deriv_at.comp_has_deriv_within_at x hf lemma has_deriv_within_at.cpow_const (hf : has_deriv_within_at f f' s x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_deriv_within_at (λ x, f x ^ c) (c * f x ^ (c - 1) * f') s x := (complex.has_strict_deriv_at_cpow_const h0).has_deriv_at.comp_has_deriv_within_at x hf end deriv namespace real /-- The real power function `x^y`, defined as the real part of the complex power function. For `x > 0`, it is equal to `exp(y log x)`. For `x = 0`, one sets `0^0=1` and `0^y=0` for `y ≠ 0`. For `x < 0`, the definition is somewhat arbitary as it depends on the choice of a complex determination of the logarithm. With our conventions, it is equal to `exp (y log x) cos (πy)`. -/ noncomputable def rpow (x y : ℝ) := ((x : ℂ) ^ (y : ℂ)).re noncomputable instance : has_pow ℝ ℝ := ⟨rpow⟩ @[simp] lemma rpow_eq_pow (x y : ℝ) : rpow x y = x ^ y := rfl lemma rpow_def (x y : ℝ) : x ^ y = ((x : ℂ) ^ (y : ℂ)).re := rfl lemma rpow_def_of_nonneg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) := by simp only [rpow_def, complex.cpow_def]; split_ifs; simp [*, (complex.of_real_log hx).symm, -complex.of_real_mul, -is_R_or_C.of_real_mul, (complex.of_real_mul _ _).symm, complex.exp_of_real_re] at * lemma rpow_def_of_pos {x : ℝ} (hx : 0 < x) (y : ℝ) : x ^ y = exp (log x * y) := by rw [rpow_def_of_nonneg (le_of_lt hx), if_neg (ne_of_gt hx)] lemma exp_mul (x y : ℝ) : exp (x * y) = (exp x) ^ y := by rw [rpow_def_of_pos (exp_pos _), log_exp] lemma rpow_eq_zero_iff_of_nonneg {x y : ℝ} (hx : 0 ≤ x) : x ^ y = 0 ↔ x = 0 ∧ y ≠ 0 := by { simp only [rpow_def_of_nonneg hx], split_ifs; simp [*, exp_ne_zero] } open_locale real lemma rpow_def_of_neg {x : ℝ} (hx : x < 0) (y : ℝ) : x ^ y = exp (log x * y) * cos (y * π) := begin rw [rpow_def, complex.cpow_def, if_neg], have : complex.log x * y = ↑(log(-x) * y) + ↑(y * π) * complex.I, { simp only [complex.log, abs_of_neg hx, complex.arg_of_real_of_neg hx, complex.abs_of_real, complex.of_real_mul], ring }, { rw [this, complex.exp_add_mul_I, ← complex.of_real_exp, ← complex.of_real_cos, ← complex.of_real_sin, mul_add, ← complex.of_real_mul, ← mul_assoc, ← complex.of_real_mul, complex.add_re, complex.of_real_re, complex.mul_re, complex.I_re, complex.of_real_im, real.log_neg_eq_log], ring }, { rw complex.of_real_eq_zero, exact ne_of_lt hx } end lemma rpow_def_of_nonpos {x : ℝ} (hx : x ≤ 0) (y : ℝ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) * cos (y * π) := by split_ifs; simp [rpow_def, *]; exact rpow_def_of_neg (lt_of_le_of_ne hx h) _ lemma rpow_pos_of_pos {x : ℝ} (hx : 0 < x) (y : ℝ) : 0 < x ^ y := by rw rpow_def_of_pos hx; apply exp_pos @[simp] lemma rpow_zero (x : ℝ) : x ^ (0 : ℝ) = 1 := by simp [rpow_def] @[simp] lemma zero_rpow {x : ℝ} (h : x ≠ 0) : (0 : ℝ) ^ x = 0 := by simp [rpow_def, *] @[simp] lemma rpow_one (x : ℝ) : x ^ (1 : ℝ) = x := by simp [rpow_def] @[simp] lemma one_rpow (x : ℝ) : (1 : ℝ) ^ x = 1 := by simp [rpow_def] lemma zero_rpow_le_one (x : ℝ) : (0 : ℝ) ^ x ≤ 1 := by { by_cases h : x = 0; simp [h, zero_le_one] } lemma zero_rpow_nonneg (x : ℝ) : 0 ≤ (0 : ℝ) ^ x := by { by_cases h : x = 0; simp [h, zero_le_one] } lemma rpow_nonneg_of_nonneg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : 0 ≤ x ^ y := by rw [rpow_def_of_nonneg hx]; split_ifs; simp only [zero_le_one, le_refl, le_of_lt (exp_pos _)] lemma abs_rpow_le_abs_rpow (x y : ℝ) : abs (x ^ y) ≤ abs (x) ^ y := begin rcases lt_trichotomy 0 x with (hx|rfl|hx), { rw [abs_of_pos hx, abs_of_pos (rpow_pos_of_pos hx _)] }, { rw [abs_zero, abs_of_nonneg (rpow_nonneg_of_nonneg le_rfl _)] }, { rw [abs_of_neg hx, rpow_def_of_neg hx, rpow_def_of_pos (neg_pos.2 hx), log_neg_eq_log, abs_mul, abs_of_pos (exp_pos _)], exact mul_le_of_le_one_right (exp_pos _).le (abs_cos_le_one _) } end lemma abs_rpow_of_nonneg {x y : ℝ} (hx_nonneg : 0 ≤ x) : abs (x ^ y) = (abs x) ^ y := begin have h_rpow_nonneg : 0 ≤ x ^ y, from real.rpow_nonneg_of_nonneg hx_nonneg _, rw [abs_eq_self.mpr hx_nonneg, abs_eq_self.mpr h_rpow_nonneg], end lemma norm_rpow_of_nonneg {x y : ℝ} (hx_nonneg : 0 ≤ x) : ∥x ^ y∥ = ∥x∥ ^ y := by { simp_rw real.norm_eq_abs, exact abs_rpow_of_nonneg hx_nonneg, } end real namespace complex lemma of_real_cpow {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : ((x ^ y : ℝ) : ℂ) = (x : ℂ) ^ (y : ℂ) := by simp [real.rpow_def_of_nonneg hx, complex.cpow_def]; split_ifs; simp [complex.of_real_log hx] @[simp] lemma abs_cpow_real (x : ℂ) (y : ℝ) : abs (x ^ (y : ℂ)) = x.abs ^ y := begin rw [real.rpow_def_of_nonneg (abs_nonneg _), complex.cpow_def], split_ifs; simp [*, abs_of_nonneg (le_of_lt (real.exp_pos _)), complex.log, complex.exp_add, add_mul, mul_right_comm _ I, exp_mul_I, abs_cos_add_sin_mul_I, (complex.of_real_mul _ _).symm, -complex.of_real_mul, -is_R_or_C.of_real_mul] at * end @[simp] lemma abs_cpow_inv_nat (x : ℂ) (n : ℕ) : abs (x ^ (n⁻¹ : ℂ)) = x.abs ^ (n⁻¹ : ℝ) := by rw ← abs_cpow_real; simp [-abs_cpow_real] end complex namespace real variables {x y z : ℝ} lemma rpow_add {x : ℝ} (hx : 0 < x) (y z : ℝ) : x ^ (y + z) = x ^ y * x ^ z := by simp only [rpow_def_of_pos hx, mul_add, exp_add] lemma rpow_add' {x : ℝ} (hx : 0 ≤ x) {y z : ℝ} (h : y + z ≠ 0) : x ^ (y + z) = x ^ y * x ^ z := begin rcases le_iff_eq_or_lt.1 hx with H|pos, { simp only [← H, h, rpow_eq_zero_iff_of_nonneg, true_and, zero_rpow, eq_self_iff_true, ne.def, not_false_iff, zero_eq_mul], by_contradiction F, push_neg at F, apply h, simp [F] }, { exact rpow_add pos _ _ } end /-- For `0 ≤ x`, the only problematic case in the equality `x ^ y * x ^ z = x ^ (y + z)` is for `x = 0` and `y + z = 0`, where the right hand side is `1` while the left hand side can vanish. The inequality is always true, though, and given in this lemma. -/ lemma le_rpow_add {x : ℝ} (hx : 0 ≤ x) (y z : ℝ) : x ^ y * x ^ z ≤ x ^ (y + z) := begin rcases le_iff_eq_or_lt.1 hx with H|pos, { by_cases h : y + z = 0, { simp only [H.symm, h, rpow_zero], calc (0 : ℝ) ^ y * 0 ^ z ≤ 1 * 1 : mul_le_mul (zero_rpow_le_one y) (zero_rpow_le_one z) (zero_rpow_nonneg z) zero_le_one ... = 1 : by simp }, { simp [rpow_add', ← H, h] } }, { simp [rpow_add pos] } end lemma rpow_mul {x : ℝ} (hx : 0 ≤ x) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z := by rw [← complex.of_real_inj, complex.of_real_cpow (rpow_nonneg_of_nonneg hx _), complex.of_real_cpow hx, complex.of_real_mul, complex.cpow_mul, complex.of_real_cpow hx]; simp only [(complex.of_real_mul _ _).symm, (complex.of_real_log hx).symm, complex.of_real_im, neg_lt_zero, pi_pos, le_of_lt pi_pos] lemma rpow_neg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : x ^ -y = (x ^ y)⁻¹ := by simp only [rpow_def_of_nonneg hx]; split_ifs; simp [*, exp_neg] at * lemma rpow_sub {x : ℝ} (hx : 0 < x) (y z : ℝ) : x ^ (y - z) = x ^ y / x ^ z := by simp only [sub_eq_add_neg, rpow_add hx, rpow_neg (le_of_lt hx), div_eq_mul_inv] lemma rpow_sub' {x : ℝ} (hx : 0 ≤ x) {y z : ℝ} (h : y - z ≠ 0) : x ^ (y - z) = x ^ y / x ^ z := by { simp only [sub_eq_add_neg] at h ⊢, simp only [rpow_add' hx h, rpow_neg hx, div_eq_mul_inv] } @[simp] lemma rpow_nat_cast (x : ℝ) (n : ℕ) : x ^ (n : ℝ) = x ^ n := by simp only [rpow_def, (complex.of_real_pow _ _).symm, complex.cpow_nat_cast, complex.of_real_nat_cast, complex.of_real_re] @[simp] lemma rpow_int_cast (x : ℝ) (n : ℤ) : x ^ (n : ℝ) = x ^ n := by simp only [rpow_def, (complex.of_real_fpow _ _).symm, complex.cpow_int_cast, complex.of_real_int_cast, complex.of_real_re] lemma rpow_neg_one (x : ℝ) : x ^ (-1 : ℝ) = x⁻¹ := begin suffices H : x ^ ((-1 : ℤ) : ℝ) = x⁻¹, by exact_mod_cast H, simp only [rpow_int_cast, gpow_one, fpow_neg], end lemma mul_rpow {x y z : ℝ} (h : 0 ≤ x) (h₁ : 0 ≤ y) : (x*y)^z = x^z * y^z := begin iterate 3 { rw real.rpow_def_of_nonneg }, split_ifs; simp * at *, { have hx : 0 < x, { cases lt_or_eq_of_le h with h₂ h₂, { exact h₂ }, exfalso, apply h_2, exact eq.symm h₂ }, have hy : 0 < y, { cases lt_or_eq_of_le h₁ with h₂ h₂, { exact h₂ }, exfalso, apply h_3, exact eq.symm h₂ }, rw [log_mul (ne_of_gt hx) (ne_of_gt hy), add_mul, exp_add]}, { exact h₁ }, { exact h }, { exact mul_nonneg h h₁ }, end lemma inv_rpow (hx : 0 ≤ x) (y : ℝ) : (x⁻¹)^y = (x^y)⁻¹ := begin by_cases hy0 : y = 0, { simp [*] }, by_cases hx0 : x = 0, { simp [*] }, simp only [real.rpow_def_of_nonneg hx, real.rpow_def_of_nonneg (inv_nonneg.2 hx), if_false, hx0, mt inv_eq_zero.1 hx0, log_inv, ← neg_mul_eq_neg_mul, exp_neg] end lemma div_rpow (hx : 0 ≤ x) (hy : 0 ≤ y) (z : ℝ) : (x / y) ^ z = x^z / y^z := by simp only [div_eq_mul_inv, mul_rpow hx (inv_nonneg.2 hy), inv_rpow hy] lemma log_rpow {x : ℝ} (hx : 0 < x) (y : ℝ) : log (x^y) = y * (log x) := begin apply exp_injective, rw [exp_log (rpow_pos_of_pos hx y), ← exp_log hx, mul_comm, rpow_def_of_pos (exp_pos (log x)) y], end lemma rpow_lt_rpow (hx : 0 ≤ x) (hxy : x < y) (hz : 0 < z) : x^z < y^z := begin rw le_iff_eq_or_lt at hx, cases hx, { rw [← hx, zero_rpow (ne_of_gt hz)], exact rpow_pos_of_pos (by rwa ← hx at hxy) _ }, rw [rpow_def_of_pos hx, rpow_def_of_pos (lt_trans hx hxy), exp_lt_exp], exact mul_lt_mul_of_pos_right (log_lt_log hx hxy) hz end lemma rpow_le_rpow {x y z: ℝ} (h : 0 ≤ x) (h₁ : x ≤ y) (h₂ : 0 ≤ z) : x^z ≤ y^z := begin rcases eq_or_lt_of_le h₁ with rfl|h₁', { refl }, rcases eq_or_lt_of_le h₂ with rfl|h₂', { simp }, exact le_of_lt (rpow_lt_rpow h h₁' h₂') end lemma rpow_lt_rpow_iff (hx : 0 ≤ x) (hy : 0 ≤ y) (hz : 0 < z) : x ^ z < y ^ z ↔ x < y := ⟨lt_imp_lt_of_le_imp_le $ λ h, rpow_le_rpow hy h (le_of_lt hz), λ h, rpow_lt_rpow hx h hz⟩ lemma rpow_le_rpow_iff (hx : 0 ≤ x) (hy : 0 ≤ y) (hz : 0 < z) : x ^ z ≤ y ^ z ↔ x ≤ y := le_iff_le_iff_lt_iff_lt.2 $ rpow_lt_rpow_iff hy hx hz lemma rpow_lt_rpow_of_exponent_lt (hx : 1 < x) (hyz : y < z) : x^y < x^z := begin repeat {rw [rpow_def_of_pos (lt_trans zero_lt_one hx)]}, rw exp_lt_exp, exact mul_lt_mul_of_pos_left hyz (log_pos hx), end lemma rpow_le_rpow_of_exponent_le (hx : 1 ≤ x) (hyz : y ≤ z) : x^y ≤ x^z := begin repeat {rw [rpow_def_of_pos (lt_of_lt_of_le zero_lt_one hx)]}, rw exp_le_exp, exact mul_le_mul_of_nonneg_left hyz (log_nonneg hx), end lemma rpow_lt_rpow_of_exponent_gt (hx0 : 0 < x) (hx1 : x < 1) (hyz : z < y) : x^y < x^z := begin repeat {rw [rpow_def_of_pos hx0]}, rw exp_lt_exp, exact mul_lt_mul_of_neg_left hyz (log_neg hx0 hx1), end lemma rpow_le_rpow_of_exponent_ge (hx0 : 0 < x) (hx1 : x ≤ 1) (hyz : z ≤ y) : x^y ≤ x^z := begin repeat {rw [rpow_def_of_pos hx0]}, rw exp_le_exp, exact mul_le_mul_of_nonpos_left hyz (log_nonpos (le_of_lt hx0) hx1), end lemma rpow_lt_one {x z : ℝ} (hx1 : 0 ≤ x) (hx2 : x < 1) (hz : 0 < z) : x^z < 1 := by { rw ← one_rpow z, exact rpow_lt_rpow hx1 hx2 hz } lemma rpow_le_one {x z : ℝ} (hx1 : 0 ≤ x) (hx2 : x ≤ 1) (hz : 0 ≤ z) : x^z ≤ 1 := by { rw ← one_rpow z, exact rpow_le_rpow hx1 hx2 hz } lemma rpow_lt_one_of_one_lt_of_neg {x z : ℝ} (hx : 1 < x) (hz : z < 0) : x^z < 1 := by { convert rpow_lt_rpow_of_exponent_lt hx hz, exact (rpow_zero x).symm } lemma rpow_le_one_of_one_le_of_nonpos {x z : ℝ} (hx : 1 ≤ x) (hz : z ≤ 0) : x^z ≤ 1 := by { convert rpow_le_rpow_of_exponent_le hx hz, exact (rpow_zero x).symm } lemma one_lt_rpow {x z : ℝ} (hx : 1 < x) (hz : 0 < z) : 1 < x^z := by { rw ← one_rpow z, exact rpow_lt_rpow zero_le_one hx hz } lemma one_le_rpow {x z : ℝ} (hx : 1 ≤ x) (hz : 0 ≤ z) : 1 ≤ x^z := by { rw ← one_rpow z, exact rpow_le_rpow zero_le_one hx hz } lemma one_lt_rpow_of_pos_of_lt_one_of_neg (hx1 : 0 < x) (hx2 : x < 1) (hz : z < 0) : 1 < x^z := by { convert rpow_lt_rpow_of_exponent_gt hx1 hx2 hz, exact (rpow_zero x).symm } lemma one_le_rpow_of_pos_of_le_one_of_nonpos (hx1 : 0 < x) (hx2 : x ≤ 1) (hz : z ≤ 0) : 1 ≤ x^z := by { convert rpow_le_rpow_of_exponent_ge hx1 hx2 hz, exact (rpow_zero x).symm } lemma rpow_lt_one_iff_of_pos (hx : 0 < x) : x ^ y < 1 ↔ 1 < x ∧ y < 0 ∨ x < 1 ∧ 0 < y := by rw [rpow_def_of_pos hx, exp_lt_one_iff, mul_neg_iff, log_pos_iff hx, log_neg_iff hx] lemma rpow_lt_one_iff (hx : 0 ≤ x) : x ^ y < 1 ↔ x = 0 ∧ y ≠ 0 ∨ 1 < x ∧ y < 0 ∨ x < 1 ∧ 0 < y := begin rcases hx.eq_or_lt with (rfl|hx), { rcases em (y = 0) with (rfl|hy); simp [*, lt_irrefl, zero_lt_one] }, { simp [rpow_lt_one_iff_of_pos hx, hx.ne.symm] } end lemma one_lt_rpow_iff_of_pos (hx : 0 < x) : 1 < x ^ y ↔ 1 < x ∧ 0 < y ∨ x < 1 ∧ y < 0 := by rw [rpow_def_of_pos hx, one_lt_exp_iff, mul_pos_iff, log_pos_iff hx, log_neg_iff hx] lemma one_lt_rpow_iff (hx : 0 ≤ x) : 1 < x ^ y ↔ 1 < x ∧ 0 < y ∨ 0 < x ∧ x < 1 ∧ y < 0 := begin rcases hx.eq_or_lt with (rfl|hx), { rcases em (y = 0) with (rfl|hy); simp [*, lt_irrefl, (@zero_lt_one ℝ _ _).not_lt] }, { simp [one_lt_rpow_iff_of_pos hx, hx] } end lemma le_rpow_iff_log_le (hx : 0 < x) (hy : 0 < y) : x ≤ y^z ↔ real.log x ≤ z * real.log y := by rw [←real.log_le_log hx (real.rpow_pos_of_pos hy z), real.log_rpow hy] lemma le_rpow_of_log_le (hx : 0 ≤ x) (hy : 0 < y) (h : real.log x ≤ z * real.log y) : x ≤ y^z := begin obtain hx | rfl := hx.lt_or_eq, { exact (le_rpow_iff_log_le hx hy).2 h }, exact (real.rpow_pos_of_pos hy z).le, end lemma lt_rpow_iff_log_lt (hx : 0 < x) (hy : 0 < y) : x < y^z ↔ real.log x < z * real.log y := by rw [←real.log_lt_log_iff hx (real.rpow_pos_of_pos hy z), real.log_rpow hy] lemma lt_rpow_of_log_lt (hx : 0 ≤ x) (hy : 0 < y) (h : real.log x < z * real.log y) : x < y^z := begin obtain hx | rfl := hx.lt_or_eq, { exact (lt_rpow_iff_log_lt hx hy).2 h }, exact real.rpow_pos_of_pos hy z, end lemma rpow_le_one_iff_of_pos (hx : 0 < x) : x ^ y ≤ 1 ↔ 1 ≤ x ∧ y ≤ 0 ∨ x ≤ 1 ∧ 0 ≤ y := by rw [rpow_def_of_pos hx, exp_le_one_iff, mul_nonpos_iff, log_nonneg_iff hx, log_nonpos_iff hx] lemma pow_nat_rpow_nat_inv {x : ℝ} (hx : 0 ≤ x) {n : ℕ} (hn : 0 < n) : (x ^ n) ^ (n⁻¹ : ℝ) = x := have hn0 : (n : ℝ) ≠ 0, by simpa [pos_iff_ne_zero] using hn, by rw [← rpow_nat_cast, ← rpow_mul hx, mul_inv_cancel hn0, rpow_one] lemma rpow_nat_inv_pow_nat {x : ℝ} (hx : 0 ≤ x) {n : ℕ} (hn : 0 < n) : (x ^ (n⁻¹ : ℝ)) ^ n = x := have hn0 : (n : ℝ) ≠ 0, by simpa [pos_iff_ne_zero] using hn, by rw [← rpow_nat_cast, ← rpow_mul hx, inv_mul_cancel hn0, rpow_one] section prove_rpow_is_continuous lemma continuous_rpow_aux1 : continuous (λp : {p:ℝ×ℝ // 0 < p.1}, p.val.1 ^ p.val.2) := suffices h : continuous (λ p : {p:ℝ×ℝ // 0 < p.1 }, exp (log p.val.1 * p.val.2)), by { convert h, ext p, rw rpow_def_of_pos p.2 }, continuous_exp.comp $ (show continuous ((λp:{p:ℝ//0 < p}, log (p.val)) ∘ (λp:{p:ℝ×ℝ//0<p.fst}, ⟨p.val.1, p.2⟩)), from continuous_log'.comp $ continuous_subtype_mk _ $ continuous_fst.comp continuous_subtype_val).mul (continuous_snd.comp $ continuous_subtype_val.comp continuous_id) lemma continuous_rpow_aux2 : continuous (λ p : {p:ℝ×ℝ // p.1 < 0}, p.val.1 ^ p.val.2) := suffices h : continuous (λp:{p:ℝ×ℝ // p.1 < 0}, exp (log (-p.val.1) * p.val.2) * cos (p.val.2 * π)), by { convert h, ext p, rw [rpow_def_of_neg p.2, log_neg_eq_log] }, (continuous_exp.comp $ (show continuous $ (λp:{p:ℝ//0<p}, log (p.val))∘(λp:{p:ℝ×ℝ//p.1<0}, ⟨-p.val.1, neg_pos_of_neg p.2⟩), from continuous_log'.comp $ continuous_subtype_mk _ $ continuous_neg.comp $ continuous_fst.comp continuous_subtype_val).mul (continuous_snd.comp $ continuous_subtype_val.comp continuous_id)).mul (continuous_cos.comp $ (continuous_snd.comp $ continuous_subtype_val.comp continuous_id).mul continuous_const) lemma continuous_at_rpow_of_ne_zero (hx : x ≠ 0) (y : ℝ) : continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) := begin cases lt_trichotomy 0 x, exact continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_rpow_aux1 _ h) (is_open.mem_nhds (by { convert (is_open_lt' (0:ℝ)).prod is_open_univ, ext, finish }) h), cases h, { exact absurd h.symm hx }, exact continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_rpow_aux2 _ h) (is_open.mem_nhds (by { convert (is_open_gt' (0:ℝ)).prod is_open_univ, ext, finish }) h) end lemma continuous_rpow_aux3 : continuous (λ p : {p:ℝ×ℝ // 0 < p.2}, p.val.1 ^ p.val.2) := continuous_iff_continuous_at.2 $ λ ⟨(x₀, y₀), hy₀⟩, begin by_cases hx₀ : x₀ = 0, { simp only [continuous_at, hx₀, zero_rpow (ne_of_gt hy₀), metric.tendsto_nhds_nhds], assume ε ε0, rcases exists_pos_rat_lt (half_pos hy₀) with ⟨q, q_pos, q_lt⟩, let q := (q:ℝ), replace q_pos : 0 < q := rat.cast_pos.2 q_pos, let δ := min (min q (ε ^ (1 / q))) (1/2), have δ0 : 0 < δ := lt_min (lt_min q_pos (rpow_pos_of_pos ε0 _)) (by norm_num), have : δ ≤ q := le_trans (min_le_left _ _) (min_le_left _ _), have : δ ≤ ε ^ (1 / q) := le_trans (min_le_left _ _) (min_le_right _ _), have : δ < 1 := lt_of_le_of_lt (min_le_right _ _) (by norm_num), use δ, use δ0, rintros ⟨⟨x, y⟩, hy⟩, simp only [subtype.dist_eq, real.dist_eq, prod.dist_eq, sub_zero, subtype.coe_mk], assume h, rw max_lt_iff at h, cases h with xδ yy₀, have qy : q < y, calc q < y₀ / 2 : q_lt ... = y₀ - y₀ / 2 : (sub_half _).symm ... ≤ y₀ - δ : by linarith ... < y : sub_lt_of_abs_sub_lt_left yy₀, calc abs(x^y) ≤ abs(x)^y : abs_rpow_le_abs_rpow _ _ ... < δ ^ y : rpow_lt_rpow (abs_nonneg _) xδ hy ... < δ ^ q : by { refine rpow_lt_rpow_of_exponent_gt _ _ _, repeat {linarith} } ... ≤ (ε ^ (1 / q)) ^ q : by { refine rpow_le_rpow _ _ _, repeat {linarith} } ... = ε : by { rw [← rpow_mul, div_mul_cancel, rpow_one], exact ne_of_gt q_pos, linarith }}, { exact (continuous_within_at_iff_continuous_at_restrict (λp:ℝ×ℝ, p.1^p.2) _).1 (continuous_at_rpow_of_ne_zero hx₀ _).continuous_within_at } end lemma continuous_at_rpow_of_pos (hy : 0 < y) (x : ℝ) : continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) := continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_rpow_aux3 _ hy) (is_open.mem_nhds (by { convert is_open_univ.prod (is_open_lt' (0:ℝ)), ext, finish }) hy) lemma continuous_at_rpow {x y : ℝ} (h : x ≠ 0 ∨ 0 < y) : continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) := by { cases h, exact continuous_at_rpow_of_ne_zero h _, exact continuous_at_rpow_of_pos h x } variables {α : Type*} [topological_space α] {f g : α → ℝ} /-- `real.rpow` is continuous at all points except for the lower half of the y-axis. In other words, the function `λp:ℝ×ℝ, p.1^p.2` is continuous at `(x, y)` if `x ≠ 0` or `y > 0`. Multiple forms of the claim is provided in the current section. -/ lemma continuous_rpow (h : ∀a, f a ≠ 0 ∨ 0 < g a) (hf : continuous f) (hg : continuous g): continuous (λa:α, (f a) ^ (g a)) := continuous_iff_continuous_at.2 $ λ a, begin show continuous_at ((λp:ℝ×ℝ, p.1^p.2) ∘ (λa, (f a, g a))) a, refine continuous_at.comp _ (continuous_iff_continuous_at.1 (hf.prod_mk hg) _), { replace h := h a, cases h, { exact continuous_at_rpow_of_ne_zero h _ }, { exact continuous_at_rpow_of_pos h _ }}, end lemma continuous_rpow_of_ne_zero (h : ∀a, f a ≠ 0) (hf : continuous f) (hg : continuous g): continuous (λa:α, (f a) ^ (g a)) := continuous_rpow (λa, or.inl $ h a) hf hg lemma continuous_rpow_of_pos (h : ∀a, 0 < g a) (hf : continuous f) (hg : continuous g): continuous (λa:α, (f a) ^ (g a)) := continuous_rpow (λa, or.inr $ h a) hf hg end prove_rpow_is_continuous section prove_rpow_is_differentiable lemma has_deriv_at_rpow_of_pos {x : ℝ} (h : 0 < x) (p : ℝ) : has_deriv_at (λ x, x^p) (p * x^(p-1)) x := begin have : has_deriv_at (λ x, exp (log x * p)) (p * x^(p-1)) x, { convert (has_deriv_at_exp _).comp x ((has_deriv_at_log (ne_of_gt h)).mul_const p) using 1, field_simp [rpow_def_of_pos h, mul_sub, exp_sub, exp_log h, ne_of_gt h], ring }, apply this.congr_of_eventually_eq, have : set.Ioi (0 : ℝ) ∈ 𝓝 x := is_open.mem_nhds is_open_Ioi h, exact filter.eventually_of_mem this (λ y hy, rpow_def_of_pos hy _) end lemma has_deriv_at_rpow_of_neg {x : ℝ} (h : x < 0) (p : ℝ) : has_deriv_at (λ x, x^p) (p * x^(p-1)) x := begin have : has_deriv_at (λ x, exp (log x * p) * cos (p * π)) (p * x^(p-1)) x, { convert ((has_deriv_at_exp _).comp x ((has_deriv_at_log (ne_of_lt h)).mul_const p)).mul_const _ using 1, field_simp [rpow_def_of_neg h, mul_sub, exp_sub, sub_mul, cos_sub, exp_log_of_neg h, ne_of_lt h], ring }, apply this.congr_of_eventually_eq, have : set.Iio (0 : ℝ) ∈ 𝓝 x := is_open.mem_nhds is_open_Iio h, exact filter.eventually_of_mem this (λ y hy, rpow_def_of_neg hy _) end lemma has_deriv_at_rpow {x : ℝ} (h : x ≠ 0) (p : ℝ) : has_deriv_at (λ x, x^p) (p * x^(p-1)) x := begin rcases lt_trichotomy x 0 with H|H|H, { exact has_deriv_at_rpow_of_neg H p }, { exact (h H).elim }, { exact has_deriv_at_rpow_of_pos H p }, end lemma has_deriv_at_rpow_zero_of_one_le {p : ℝ} (h : 1 ≤ p) : has_deriv_at (λ x, x^p) (p * (0 : ℝ)^(p-1)) 0 := begin apply has_deriv_at_of_has_deriv_at_of_ne (λ x hx, has_deriv_at_rpow hx p), { exact (continuous_rpow_of_pos (λ _, (lt_of_lt_of_le zero_lt_one h)) continuous_id continuous_const).continuous_at }, { rcases le_iff_eq_or_lt.1 h with rfl|h, { simp [continuous_const.continuous_at] }, { exact (continuous_const.mul (continuous_rpow_of_pos (λ _, sub_pos_of_lt h) continuous_id continuous_const)).continuous_at } } end lemma has_deriv_at_rpow_of_one_le (x : ℝ) {p : ℝ} (h : 1 ≤ p) : has_deriv_at (λ x, x^p) (p * x^(p-1)) x := begin by_cases hx : x = 0, { rw hx, exact has_deriv_at_rpow_zero_of_one_le h }, { exact has_deriv_at_rpow hx p } end end prove_rpow_is_differentiable section sqrt lemma sqrt_eq_rpow : sqrt = λx:ℝ, x ^ (1/(2:ℝ)) := begin funext, by_cases h : 0 ≤ x, { rw [← mul_self_inj_of_nonneg, mul_self_sqrt h, ← sq, ← rpow_nat_cast, ← rpow_mul h], norm_num, exact sqrt_nonneg _, exact rpow_nonneg_of_nonneg h _ }, { replace h : x < 0 := lt_of_not_ge h, have : 1 / (2:ℝ) * π = π / (2:ℝ), ring, rw [sqrt_eq_zero_of_nonpos (le_of_lt h), rpow_def_of_neg h, this, cos_pi_div_two, mul_zero] } end end sqrt end real section differentiability open real variables {f : ℝ → ℝ} {x f' : ℝ} {s : set ℝ} (p : ℝ) /- Differentiability statements for the power of a function, when the function does not vanish and the exponent is arbitrary-/ lemma has_deriv_within_at.rpow (hf : has_deriv_within_at f f' s x) (hx : f x ≠ 0) : has_deriv_within_at (λ y, (f y)^p) (f' * p * (f x)^(p-1)) s x := begin convert (has_deriv_at_rpow hx p).comp_has_deriv_within_at x hf using 1, ring end lemma has_deriv_at.rpow (hf : has_deriv_at f f' x) (hx : f x ≠ 0) : has_deriv_at (λ y, (f y)^p) (f' * p * (f x)^(p-1)) x := begin rw ← has_deriv_within_at_univ at *, exact hf.rpow p hx end lemma differentiable_within_at.rpow (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0) : differentiable_within_at ℝ (λx, (f x)^p) s x := (hf.has_deriv_within_at.rpow p hx).differentiable_within_at @[simp] lemma differentiable_at.rpow (hf : differentiable_at ℝ f x) (hx : f x ≠ 0) : differentiable_at ℝ (λx, (f x)^p) x := (hf.has_deriv_at.rpow p hx).differentiable_at lemma differentiable_on.rpow (hf : differentiable_on ℝ f s) (hx : ∀ x ∈ s, f x ≠ 0) : differentiable_on ℝ (λx, (f x)^p) s := λx h, (hf x h).rpow p (hx x h) @[simp] lemma differentiable.rpow (hf : differentiable ℝ f) (hx : ∀ x, f x ≠ 0) : differentiable ℝ (λx, (f x)^p) := λx, (hf x).rpow p (hx x) lemma deriv_within_rpow (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, (f x)^p) s x = (deriv_within f s x) * p * (f x)^(p-1) := (hf.has_deriv_within_at.rpow p hx).deriv_within hxs @[simp] lemma deriv_rpow (hf : differentiable_at ℝ f x) (hx : f x ≠ 0) : deriv (λx, (f x)^p) x = (deriv f x) * p * (f x)^(p-1) := (hf.has_deriv_at.rpow p hx).deriv /- Differentiability statements for the power of a function, when the function may vanish but the exponent is at least one. -/ variable {p} lemma has_deriv_within_at.rpow_of_one_le (hf : has_deriv_within_at f f' s x) (hp : 1 ≤ p) : has_deriv_within_at (λ y, (f y)^p) (f' * p * (f x)^(p-1)) s x := begin convert (has_deriv_at_rpow_of_one_le (f x) hp).comp_has_deriv_within_at x hf using 1, ring end lemma has_deriv_at.rpow_of_one_le (hf : has_deriv_at f f' x) (hp : 1 ≤ p) : has_deriv_at (λ y, (f y)^p) (f' * p * (f x)^(p-1)) x := begin rw ← has_deriv_within_at_univ at *, exact hf.rpow_of_one_le hp end lemma differentiable_within_at.rpow_of_one_le (hf : differentiable_within_at ℝ f s x) (hp : 1 ≤ p) : differentiable_within_at ℝ (λx, (f x)^p) s x := (hf.has_deriv_within_at.rpow_of_one_le hp).differentiable_within_at @[simp] lemma differentiable_at.rpow_of_one_le (hf : differentiable_at ℝ f x) (hp : 1 ≤ p) : differentiable_at ℝ (λx, (f x)^p) x := (hf.has_deriv_at.rpow_of_one_le hp).differentiable_at lemma differentiable_on.rpow_of_one_le (hf : differentiable_on ℝ f s) (hp : 1 ≤ p) : differentiable_on ℝ (λx, (f x)^p) s := λx h, (hf x h).rpow_of_one_le hp @[simp] lemma differentiable.rpow_of_one_le (hf : differentiable ℝ f) (hp : 1 ≤ p) : differentiable ℝ (λx, (f x)^p) := λx, (hf x).rpow_of_one_le hp lemma deriv_within_rpow_of_one_le (hf : differentiable_within_at ℝ f s x) (hp : 1 ≤ p) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, (f x)^p) s x = (deriv_within f s x) * p * (f x)^(p-1) := (hf.has_deriv_within_at.rpow_of_one_le hp).deriv_within hxs @[simp] lemma deriv_rpow_of_one_le (hf : differentiable_at ℝ f x) (hp : 1 ≤ p) : deriv (λx, (f x)^p) x = (deriv f x) * p * (f x)^(p-1) := (hf.has_deriv_at.rpow_of_one_le hp).deriv end differentiability section limits open real filter /-- The function `x ^ y` tends to `+∞` at `+∞` for any positive real `y`. -/ lemma tendsto_rpow_at_top {y : ℝ} (hy : 0 < y) : tendsto (λ x : ℝ, x ^ y) at_top at_top := begin rw tendsto_at_top_at_top, intro b, use (max b 0) ^ (1/y), intros x hx, exact le_of_max_le_left (by { convert rpow_le_rpow (rpow_nonneg_of_nonneg (le_max_right b 0) (1/y)) hx (le_of_lt hy), rw [← rpow_mul (le_max_right b 0), (eq_div_iff (ne_of_gt hy)).mp rfl, rpow_one] }), end /-- The function `x ^ (-y)` tends to `0` at `+∞` for any positive real `y`. -/ lemma tendsto_rpow_neg_at_top {y : ℝ} (hy : 0 < y) : tendsto (λ x : ℝ, x ^ (-y)) at_top (𝓝 0) := tendsto.congr' (eventually_eq_of_mem (Ioi_mem_at_top 0) (λ x hx, (rpow_neg (le_of_lt hx) y).symm)) (tendsto_rpow_at_top hy).inv_tendsto_at_top /-- The function `x ^ (a / (b * x + c))` tends to `1` at `+∞`, for any real numbers `a`, `b`, and `c` such that `b` is nonzero. -/ lemma tendsto_rpow_div_mul_add (a b c : ℝ) (hb : 0 ≠ b) : tendsto (λ x, x ^ (a / (b*x+c))) at_top (𝓝 1) := begin refine tendsto.congr' _ ((tendsto_exp_nhds_0_nhds_1.comp (by simpa only [mul_zero, pow_one] using ((@tendsto_const_nhds _ _ _ a _).mul (tendsto_div_pow_mul_exp_add_at_top b c 1 hb (by norm_num))))).comp (tendsto_log_at_top)), apply eventually_eq_of_mem (Ioi_mem_at_top (0:ℝ)), intros x hx, simp only [set.mem_Ioi, function.comp_app] at hx ⊢, rw [exp_log hx, ← exp_log (rpow_pos_of_pos hx (a / (b * x + c))), log_rpow hx (a / (b * x + c))], field_simp, end /-- The function `x ^ (1 / x)` tends to `1` at `+∞`. -/ lemma tendsto_rpow_div : tendsto (λ x, x ^ ((1:ℝ) / x)) at_top (𝓝 1) := by { convert tendsto_rpow_div_mul_add (1:ℝ) _ (0:ℝ) zero_ne_one, ring_nf } /-- The function `x ^ (-1 / x)` tends to `1` at `+∞`. -/ lemma tendsto_rpow_neg_div : tendsto (λ x, x ^ (-(1:ℝ) / x)) at_top (𝓝 1) := by { convert tendsto_rpow_div_mul_add (-(1:ℝ)) _ (0:ℝ) zero_ne_one, ring_nf } end limits namespace nnreal /-- The nonnegative real power function `x^y`, defined for `x : ℝ≥0` and `y : ℝ ` as the restriction of the real power function. For `x > 0`, it is equal to `exp (y log x)`. For `x = 0`, one sets `0 ^ 0 = 1` and `0 ^ y = 0` for `y ≠ 0`. -/ noncomputable def rpow (x : ℝ≥0) (y : ℝ) : ℝ≥0 := ⟨(x : ℝ) ^ y, real.rpow_nonneg_of_nonneg x.2 y⟩ noncomputable instance : has_pow ℝ≥0 ℝ := ⟨rpow⟩ @[simp] lemma rpow_eq_pow (x : ℝ≥0) (y : ℝ) : rpow x y = x ^ y := rfl @[simp, norm_cast] lemma coe_rpow (x : ℝ≥0) (y : ℝ) : ((x ^ y : ℝ≥0) : ℝ) = (x : ℝ) ^ y := rfl @[simp] lemma rpow_zero (x : ℝ≥0) : x ^ (0 : ℝ) = 1 := nnreal.eq $ real.rpow_zero _ @[simp] lemma rpow_eq_zero_iff {x : ℝ≥0} {y : ℝ} : x ^ y = 0 ↔ x = 0 ∧ y ≠ 0 := begin rw [← nnreal.coe_eq, coe_rpow, ← nnreal.coe_eq_zero], exact real.rpow_eq_zero_iff_of_nonneg x.2 end @[simp] lemma zero_rpow {x : ℝ} (h : x ≠ 0) : (0 : ℝ≥0) ^ x = 0 := nnreal.eq $ real.zero_rpow h @[simp] lemma rpow_one (x : ℝ≥0) : x ^ (1 : ℝ) = x := nnreal.eq $ real.rpow_one _ @[simp] lemma one_rpow (x : ℝ) : (1 : ℝ≥0) ^ x = 1 := nnreal.eq $ real.one_rpow _ lemma rpow_add {x : ℝ≥0} (hx : x ≠ 0) (y z : ℝ) : x ^ (y + z) = x ^ y * x ^ z := nnreal.eq $ real.rpow_add (pos_iff_ne_zero.2 hx) _ _ lemma rpow_add' (x : ℝ≥0) {y z : ℝ} (h : y + z ≠ 0) : x ^ (y + z) = x ^ y * x ^ z := nnreal.eq $ real.rpow_add' x.2 h lemma rpow_mul (x : ℝ≥0) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z := nnreal.eq $ real.rpow_mul x.2 y z lemma rpow_neg (x : ℝ≥0) (y : ℝ) : x ^ -y = (x ^ y)⁻¹ := nnreal.eq $ real.rpow_neg x.2 _ lemma rpow_neg_one (x : ℝ≥0) : x ^ (-1 : ℝ) = x ⁻¹ := by simp [rpow_neg] lemma rpow_sub {x : ℝ≥0} (hx : x ≠ 0) (y z : ℝ) : x ^ (y - z) = x ^ y / x ^ z := nnreal.eq $ real.rpow_sub (pos_iff_ne_zero.2 hx) y z lemma rpow_sub' (x : ℝ≥0) {y z : ℝ} (h : y - z ≠ 0) : x ^ (y - z) = x ^ y / x ^ z := nnreal.eq $ real.rpow_sub' x.2 h lemma inv_rpow (x : ℝ≥0) (y : ℝ) : (x⁻¹) ^ y = (x ^ y)⁻¹ := nnreal.eq $ real.inv_rpow x.2 y lemma div_rpow (x y : ℝ≥0) (z : ℝ) : (x / y) ^ z = x ^ z / y ^ z := nnreal.eq $ real.div_rpow x.2 y.2 z @[simp, norm_cast] lemma rpow_nat_cast (x : ℝ≥0) (n : ℕ) : x ^ (n : ℝ) = x ^ n := nnreal.eq $ by simpa only [coe_rpow, coe_pow] using real.rpow_nat_cast x n lemma mul_rpow {x y : ℝ≥0} {z : ℝ} : (x*y)^z = x^z * y^z := nnreal.eq $ real.mul_rpow x.2 y.2 lemma rpow_le_rpow {x y : ℝ≥0} {z: ℝ} (h₁ : x ≤ y) (h₂ : 0 ≤ z) : x^z ≤ y^z := real.rpow_le_rpow x.2 h₁ h₂ lemma rpow_lt_rpow {x y : ℝ≥0} {z: ℝ} (h₁ : x < y) (h₂ : 0 < z) : x^z < y^z := real.rpow_lt_rpow x.2 h₁ h₂ lemma rpow_lt_rpow_iff {x y : ℝ≥0} {z : ℝ} (hz : 0 < z) : x ^ z < y ^ z ↔ x < y := real.rpow_lt_rpow_iff x.2 y.2 hz lemma rpow_le_rpow_iff {x y : ℝ≥0} {z : ℝ} (hz : 0 < z) : x ^ z ≤ y ^ z ↔ x ≤ y := real.rpow_le_rpow_iff x.2 y.2 hz lemma rpow_lt_rpow_of_exponent_lt {x : ℝ≥0} {y z : ℝ} (hx : 1 < x) (hyz : y < z) : x^y < x^z := real.rpow_lt_rpow_of_exponent_lt hx hyz lemma rpow_le_rpow_of_exponent_le {x : ℝ≥0} {y z : ℝ} (hx : 1 ≤ x) (hyz : y ≤ z) : x^y ≤ x^z := real.rpow_le_rpow_of_exponent_le hx hyz lemma rpow_lt_rpow_of_exponent_gt {x : ℝ≥0} {y z : ℝ} (hx0 : 0 < x) (hx1 : x < 1) (hyz : z < y) : x^y < x^z := real.rpow_lt_rpow_of_exponent_gt hx0 hx1 hyz lemma rpow_le_rpow_of_exponent_ge {x : ℝ≥0} {y z : ℝ} (hx0 : 0 < x) (hx1 : x ≤ 1) (hyz : z ≤ y) : x^y ≤ x^z := real.rpow_le_rpow_of_exponent_ge hx0 hx1 hyz lemma rpow_lt_one {x : ℝ≥0} {z : ℝ} (hx : 0 ≤ x) (hx1 : x < 1) (hz : 0 < z) : x^z < 1 := real.rpow_lt_one hx hx1 hz lemma rpow_le_one {x : ℝ≥0} {z : ℝ} (hx2 : x ≤ 1) (hz : 0 ≤ z) : x^z ≤ 1 := real.rpow_le_one x.2 hx2 hz lemma rpow_lt_one_of_one_lt_of_neg {x : ℝ≥0} {z : ℝ} (hx : 1 < x) (hz : z < 0) : x^z < 1 := real.rpow_lt_one_of_one_lt_of_neg hx hz lemma rpow_le_one_of_one_le_of_nonpos {x : ℝ≥0} {z : ℝ} (hx : 1 ≤ x) (hz : z ≤ 0) : x^z ≤ 1 := real.rpow_le_one_of_one_le_of_nonpos hx hz lemma one_lt_rpow {x : ℝ≥0} {z : ℝ} (hx : 1 < x) (hz : 0 < z) : 1 < x^z := real.one_lt_rpow hx hz lemma one_le_rpow {x : ℝ≥0} {z : ℝ} (h : 1 ≤ x) (h₁ : 0 ≤ z) : 1 ≤ x^z := real.one_le_rpow h h₁ lemma one_lt_rpow_of_pos_of_lt_one_of_neg {x : ℝ≥0} {z : ℝ} (hx1 : 0 < x) (hx2 : x < 1) (hz : z < 0) : 1 < x^z := real.one_lt_rpow_of_pos_of_lt_one_of_neg hx1 hx2 hz lemma one_le_rpow_of_pos_of_le_one_of_nonpos {x : ℝ≥0} {z : ℝ} (hx1 : 0 < x) (hx2 : x ≤ 1) (hz : z ≤ 0) : 1 ≤ x^z := real.one_le_rpow_of_pos_of_le_one_of_nonpos hx1 hx2 hz lemma pow_nat_rpow_nat_inv (x : ℝ≥0) {n : ℕ} (hn : 0 < n) : (x ^ n) ^ (n⁻¹ : ℝ) = x := by { rw [← nnreal.coe_eq, coe_rpow, nnreal.coe_pow], exact real.pow_nat_rpow_nat_inv x.2 hn } lemma rpow_nat_inv_pow_nat (x : ℝ≥0) {n : ℕ} (hn : 0 < n) : (x ^ (n⁻¹ : ℝ)) ^ n = x := by { rw [← nnreal.coe_eq, nnreal.coe_pow, coe_rpow], exact real.rpow_nat_inv_pow_nat x.2 hn } lemma continuous_at_rpow {x : ℝ≥0} {y : ℝ} (h : x ≠ 0 ∨ 0 < y) : continuous_at (λp:ℝ≥0×ℝ, p.1^p.2) (x, y) := begin have : (λp:ℝ≥0×ℝ, p.1^p.2) = real.to_nnreal ∘ (λp:ℝ×ℝ, p.1^p.2) ∘ (λp:ℝ≥0 × ℝ, (p.1.1, p.2)), { ext p, rw [coe_rpow, real.coe_to_nnreal _ (real.rpow_nonneg_of_nonneg p.1.2 _)], refl }, rw this, refine nnreal.continuous_of_real.continuous_at.comp (continuous_at.comp _ _), { apply real.continuous_at_rpow, simp at h, rw ← (nnreal.coe_eq_zero x) at h, exact h }, { exact ((continuous_subtype_val.comp continuous_fst).prod_mk continuous_snd).continuous_at } end lemma _root_.real.to_nnreal_rpow_of_nonneg {x y : ℝ} (hx : 0 ≤ x) : real.to_nnreal (x ^ y) = (real.to_nnreal x) ^ y := begin nth_rewrite 0 ← real.coe_to_nnreal x hx, rw [←nnreal.coe_rpow, real.to_nnreal_coe], end end nnreal open filter lemma filter.tendsto.nnrpow {α : Type*} {f : filter α} {u : α → ℝ≥0} {v : α → ℝ} {x : ℝ≥0} {y : ℝ} (hx : tendsto u f (𝓝 x)) (hy : tendsto v f (𝓝 y)) (h : x ≠ 0 ∨ 0 < y) : tendsto (λ a, (u a) ^ (v a)) f (𝓝 (x ^ y)) := tendsto.comp (nnreal.continuous_at_rpow h) (hx.prod_mk_nhds hy) namespace nnreal lemma continuous_at_rpow_const {x : ℝ≥0} {y : ℝ} (h : x ≠ 0 ∨ 0 ≤ y) : continuous_at (λ z, z^y) x := h.elim (λ h, tendsto_id.nnrpow tendsto_const_nhds (or.inl h)) $ λ h, h.eq_or_lt.elim (λ h, h ▸ by simp only [rpow_zero, continuous_at_const]) (λ h, tendsto_id.nnrpow tendsto_const_nhds (or.inr h)) lemma continuous_rpow_const {y : ℝ} (h : 0 ≤ y) : continuous (λ x : ℝ≥0, x^y) := continuous_iff_continuous_at.2 $ λ x, continuous_at_rpow_const (or.inr h) theorem tendsto_rpow_at_top {y : ℝ} (hy : 0 < y) : tendsto (λ (x : ℝ≥0), x ^ y) at_top at_top := begin rw filter.tendsto_at_top_at_top, intros b, obtain ⟨c, hc⟩ := tendsto_at_top_at_top.mp (tendsto_rpow_at_top hy) b, use c.to_nnreal, intros a ha, exact_mod_cast hc a (real.to_nnreal_le_iff_le_coe.mp ha), end end nnreal namespace ennreal /-- The real power function `x^y` on extended nonnegative reals, defined for `x : ℝ≥0∞` and `y : ℝ` as the restriction of the real power function if `0 < x < ⊤`, and with the natural values for `0` and `⊤` (i.e., `0 ^ x = 0` for `x > 0`, `1` for `x = 0` and `⊤` for `x < 0`, and `⊤ ^ x = 1 / 0 ^ x`). -/ noncomputable def rpow : ℝ≥0∞ → ℝ → ℝ≥0∞ | (some x) y := if x = 0 ∧ y < 0 then ⊤ else (x ^ y : ℝ≥0) | none y := if 0 < y then ⊤ else if y = 0 then 1 else 0 noncomputable instance : has_pow ℝ≥0∞ ℝ := ⟨rpow⟩ @[simp] lemma rpow_eq_pow (x : ℝ≥0∞) (y : ℝ) : rpow x y = x ^ y := rfl @[simp] lemma rpow_zero {x : ℝ≥0∞} : x ^ (0 : ℝ) = 1 := by cases x; { dsimp only [(^), rpow], simp [lt_irrefl] } lemma top_rpow_def (y : ℝ) : (⊤ : ℝ≥0∞) ^ y = if 0 < y then ⊤ else if y = 0 then 1 else 0 := rfl @[simp] lemma top_rpow_of_pos {y : ℝ} (h : 0 < y) : (⊤ : ℝ≥0∞) ^ y = ⊤ := by simp [top_rpow_def, h] @[simp] lemma top_rpow_of_neg {y : ℝ} (h : y < 0) : (⊤ : ℝ≥0∞) ^ y = 0 := by simp [top_rpow_def, asymm h, ne_of_lt h] @[simp] lemma zero_rpow_of_pos {y : ℝ} (h : 0 < y) : (0 : ℝ≥0∞) ^ y = 0 := begin rw [← ennreal.coe_zero, ← ennreal.some_eq_coe], dsimp only [(^), rpow], simp [h, asymm h, ne_of_gt h], end @[simp] lemma zero_rpow_of_neg {y : ℝ} (h : y < 0) : (0 : ℝ≥0∞) ^ y = ⊤ := begin rw [← ennreal.coe_zero, ← ennreal.some_eq_coe], dsimp only [(^), rpow], simp [h, ne_of_gt h], end lemma zero_rpow_def (y : ℝ) : (0 : ℝ≥0∞) ^ y = if 0 < y then 0 else if y = 0 then 1 else ⊤ := begin rcases lt_trichotomy 0 y with H|rfl|H, { simp [H, ne_of_gt, zero_rpow_of_pos, lt_irrefl] }, { simp [lt_irrefl] }, { simp [H, asymm H, ne_of_lt, zero_rpow_of_neg] } end @[norm_cast] lemma coe_rpow_of_ne_zero {x : ℝ≥0} (h : x ≠ 0) (y : ℝ) : (x : ℝ≥0∞) ^ y = (x ^ y : ℝ≥0) := begin rw [← ennreal.some_eq_coe], dsimp only [(^), rpow], simp [h] end @[norm_cast] lemma coe_rpow_of_nonneg (x : ℝ≥0) {y : ℝ} (h : 0 ≤ y) : (x : ℝ≥0∞) ^ y = (x ^ y : ℝ≥0) := begin by_cases hx : x = 0, { rcases le_iff_eq_or_lt.1 h with H|H, { simp [hx, H.symm] }, { simp [hx, zero_rpow_of_pos H, nnreal.zero_rpow (ne_of_gt H)] } }, { exact coe_rpow_of_ne_zero hx _ } end lemma coe_rpow_def (x : ℝ≥0) (y : ℝ) : (x : ℝ≥0∞) ^ y = if x = 0 ∧ y < 0 then ⊤ else (x ^ y : ℝ≥0) := rfl @[simp] lemma rpow_one (x : ℝ≥0∞) : x ^ (1 : ℝ) = x := by cases x; dsimp only [(^), rpow]; simp [zero_lt_one, not_lt_of_le zero_le_one] @[simp] lemma one_rpow (x : ℝ) : (1 : ℝ≥0∞) ^ x = 1 := by { rw [← coe_one, coe_rpow_of_ne_zero one_ne_zero], simp } @[simp] lemma rpow_eq_zero_iff {x : ℝ≥0∞} {y : ℝ} : x ^ y = 0 ↔ (x = 0 ∧ 0 < y) ∨ (x = ⊤ ∧ y < 0) := begin cases x, { rcases lt_trichotomy y 0 with H|H|H; simp [H, top_rpow_of_neg, top_rpow_of_pos, le_of_lt] }, { by_cases h : x = 0, { rcases lt_trichotomy y 0 with H|H|H; simp [h, H, zero_rpow_of_neg, zero_rpow_of_pos, le_of_lt] }, { simp [coe_rpow_of_ne_zero h, h] } } end @[simp] lemma rpow_eq_top_iff {x : ℝ≥0∞} {y : ℝ} : x ^ y = ⊤ ↔ (x = 0 ∧ y < 0) ∨ (x = ⊤ ∧ 0 < y) := begin cases x, { rcases lt_trichotomy y 0 with H|H|H; simp [H, top_rpow_of_neg, top_rpow_of_pos, le_of_lt] }, { by_cases h : x = 0, { rcases lt_trichotomy y 0 with H|H|H; simp [h, H, zero_rpow_of_neg, zero_rpow_of_pos, le_of_lt] }, { simp [coe_rpow_of_ne_zero h, h] } } end lemma rpow_eq_top_iff_of_pos {x : ℝ≥0∞} {y : ℝ} (hy : 0 < y) : x ^ y = ⊤ ↔ x = ⊤ := by simp [rpow_eq_top_iff, hy, asymm hy] lemma rpow_eq_top_of_nonneg (x : ℝ≥0∞) {y : ℝ} (hy0 : 0 ≤ y) : x ^ y = ⊤ → x = ⊤ := begin rw ennreal.rpow_eq_top_iff, intro h, cases h, { exfalso, rw lt_iff_not_ge at h, exact h.right hy0, }, { exact h.left, }, end lemma rpow_ne_top_of_nonneg {x : ℝ≥0∞} {y : ℝ} (hy0 : 0 ≤ y) (h : x ≠ ⊤) : x ^ y ≠ ⊤ := mt (ennreal.rpow_eq_top_of_nonneg x hy0) h lemma rpow_lt_top_of_nonneg {x : ℝ≥0∞} {y : ℝ} (hy0 : 0 ≤ y) (h : x ≠ ⊤) : x ^ y < ⊤ := ennreal.lt_top_iff_ne_top.mpr (ennreal.rpow_ne_top_of_nonneg hy0 h) lemma rpow_add {x : ℝ≥0∞} (y z : ℝ) (hx : x ≠ 0) (h'x : x ≠ ⊤) : x ^ (y + z) = x ^ y * x ^ z := begin cases x, { exact (h'x rfl).elim }, have : x ≠ 0 := λ h, by simpa [h] using hx, simp [coe_rpow_of_ne_zero this, nnreal.rpow_add this] end lemma rpow_neg (x : ℝ≥0∞) (y : ℝ) : x ^ -y = (x ^ y)⁻¹ := begin cases x, { rcases lt_trichotomy y 0 with H|H|H; simp [top_rpow_of_pos, top_rpow_of_neg, H, neg_pos.mpr] }, { by_cases h : x = 0, { rcases lt_trichotomy y 0 with H|H|H; simp [h, zero_rpow_of_pos, zero_rpow_of_neg, H, neg_pos.mpr] }, { have A : x ^ y ≠ 0, by simp [h], simp [coe_rpow_of_ne_zero h, ← coe_inv A, nnreal.rpow_neg] } } end lemma rpow_sub {x : ℝ≥0∞} (y z : ℝ) (hx : x ≠ 0) (h'x : x ≠ ⊤) : x ^ (y - z) = x ^ y / x ^ z := by rw [sub_eq_add_neg, rpow_add _ _ hx h'x, rpow_neg, div_eq_mul_inv] lemma rpow_neg_one (x : ℝ≥0∞) : x ^ (-1 : ℝ) = x ⁻¹ := by simp [rpow_neg] lemma rpow_mul (x : ℝ≥0∞) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z := begin cases x, { rcases lt_trichotomy y 0 with Hy|Hy|Hy; rcases lt_trichotomy z 0 with Hz|Hz|Hz; simp [Hy, Hz, zero_rpow_of_neg, zero_rpow_of_pos, top_rpow_of_neg, top_rpow_of_pos, mul_pos_of_neg_of_neg, mul_neg_of_neg_of_pos, mul_neg_of_pos_of_neg] }, { by_cases h : x = 0, { rcases lt_trichotomy y 0 with Hy|Hy|Hy; rcases lt_trichotomy z 0 with Hz|Hz|Hz; simp [h, Hy, Hz, zero_rpow_of_neg, zero_rpow_of_pos, top_rpow_of_neg, top_rpow_of_pos, mul_pos_of_neg_of_neg, mul_neg_of_neg_of_pos, mul_neg_of_pos_of_neg] }, { have : x ^ y ≠ 0, by simp [h], simp [coe_rpow_of_ne_zero h, coe_rpow_of_ne_zero this, nnreal.rpow_mul] } } end @[simp, norm_cast] lemma rpow_nat_cast (x : ℝ≥0∞) (n : ℕ) : x ^ (n : ℝ) = x ^ n := begin cases x, { cases n; simp [top_rpow_of_pos (nat.cast_add_one_pos _), top_pow (nat.succ_pos _)] }, { simp [coe_rpow_of_nonneg _ (nat.cast_nonneg n)] } end @[norm_cast] lemma coe_mul_rpow (x y : ℝ≥0) (z : ℝ) : ((x : ℝ≥0∞) * y) ^ z = x^z * y^z := begin rcases lt_trichotomy z 0 with H|H|H, { by_cases hx : x = 0; by_cases hy : y = 0, { simp [hx, hy, zero_rpow_of_neg, H] }, { have : (y : ℝ≥0∞) ^ z ≠ 0, by simp [rpow_eq_zero_iff, hy], simp [hx, hy, zero_rpow_of_neg, H, with_top.top_mul this] }, { have : (x : ℝ≥0∞) ^ z ≠ 0, by simp [rpow_eq_zero_iff, hx], simp [hx, hy, zero_rpow_of_neg H, with_top.mul_top this] }, { rw [← coe_mul, coe_rpow_of_ne_zero, nnreal.mul_rpow, coe_mul, coe_rpow_of_ne_zero hx, coe_rpow_of_ne_zero hy], simp [hx, hy] } }, { simp [H] }, { by_cases hx : x = 0; by_cases hy : y = 0, { simp [hx, hy, zero_rpow_of_pos, H] }, { have : (y : ℝ≥0∞) ^ z ≠ 0, by simp [rpow_eq_zero_iff, hy], simp [hx, hy, zero_rpow_of_pos H, with_top.top_mul this] }, { have : (x : ℝ≥0∞) ^ z ≠ 0, by simp [rpow_eq_zero_iff, hx], simp [hx, hy, zero_rpow_of_pos H, with_top.mul_top this] }, { rw [← coe_mul, coe_rpow_of_ne_zero, nnreal.mul_rpow, coe_mul, coe_rpow_of_ne_zero hx, coe_rpow_of_ne_zero hy], simp [hx, hy] } }, end lemma mul_rpow_of_ne_top {x y : ℝ≥0∞} (hx : x ≠ ⊤) (hy : y ≠ ⊤) (z : ℝ) : (x * y) ^ z = x^z * y^z := begin lift x to ℝ≥0 using hx, lift y to ℝ≥0 using hy, exact coe_mul_rpow x y z end lemma mul_rpow_of_ne_zero {x y : ℝ≥0∞} (hx : x ≠ 0) (hy : y ≠ 0) (z : ℝ) : (x * y) ^ z = x ^ z * y ^ z := begin rcases lt_trichotomy z 0 with H|H|H, { cases x; cases y, { simp [hx, hy, top_rpow_of_neg, H] }, { have : y ≠ 0, by simpa using hy, simp [hx, hy, top_rpow_of_neg, H, rpow_eq_zero_iff, this] }, { have : x ≠ 0, by simpa using hx, simp [hx, hy, top_rpow_of_neg, H, rpow_eq_zero_iff, this] }, { have hx' : x ≠ 0, by simpa using hx, have hy' : y ≠ 0, by simpa using hy, simp only [some_eq_coe], rw [← coe_mul, coe_rpow_of_ne_zero, nnreal.mul_rpow, coe_mul, coe_rpow_of_ne_zero hx', coe_rpow_of_ne_zero hy'], simp [hx', hy'] } }, { simp [H] }, { cases x; cases y, { simp [hx, hy, top_rpow_of_pos, H] }, { have : y ≠ 0, by simpa using hy, simp [hx, hy, top_rpow_of_pos, H, rpow_eq_zero_iff, this] }, { have : x ≠ 0, by simpa using hx, simp [hx, hy, top_rpow_of_pos, H, rpow_eq_zero_iff, this] }, { have hx' : x ≠ 0, by simpa using hx, have hy' : y ≠ 0, by simpa using hy, simp only [some_eq_coe], rw [← coe_mul, coe_rpow_of_ne_zero, nnreal.mul_rpow, coe_mul, coe_rpow_of_ne_zero hx', coe_rpow_of_ne_zero hy'], simp [hx', hy'] } } end lemma mul_rpow_of_nonneg (x y : ℝ≥0∞) {z : ℝ} (hz : 0 ≤ z) : (x * y) ^ z = x ^ z * y ^ z := begin rcases le_iff_eq_or_lt.1 hz with H|H, { simp [← H] }, by_cases h : x = 0 ∨ y = 0, { cases h; simp [h, zero_rpow_of_pos H] }, push_neg at h, exact mul_rpow_of_ne_zero h.1 h.2 z end lemma inv_rpow_of_pos {x : ℝ≥0∞} {y : ℝ} (hy : 0 < y) : (x⁻¹) ^ y = (x ^ y)⁻¹ := begin by_cases h0 : x = 0, { rw [h0, zero_rpow_of_pos hy, inv_zero, top_rpow_of_pos hy], }, by_cases h_top : x = ⊤, { rw [h_top, top_rpow_of_pos hy, inv_top, zero_rpow_of_pos hy], }, rw ←coe_to_nnreal h_top, have h : x.to_nnreal ≠ 0, { rw [ne.def, to_nnreal_eq_zero_iff], simp [h0, h_top], }, rw [←coe_inv h, coe_rpow_of_nonneg _ (le_of_lt hy), coe_rpow_of_nonneg _ (le_of_lt hy), ←coe_inv], { rw coe_eq_coe, exact nnreal.inv_rpow x.to_nnreal y, }, { simp [h], }, end lemma div_rpow_of_nonneg (x y : ℝ≥0∞) {z : ℝ} (hz : 0 ≤ z) : (x / y) ^ z = x ^ z / y ^ z := begin by_cases h0 : z = 0, { simp [h0], }, rw ←ne.def at h0, have hz_pos : 0 < z, from lt_of_le_of_ne hz h0.symm, rw [div_eq_mul_inv, mul_rpow_of_nonneg x y⁻¹ hz, inv_rpow_of_pos hz_pos, ←div_eq_mul_inv], end lemma rpow_le_rpow {x y : ℝ≥0∞} {z : ℝ} (h₁ : x ≤ y) (h₂ : 0 ≤ z) : x^z ≤ y^z := begin rcases le_iff_eq_or_lt.1 h₂ with H|H, { simp [← H, le_refl] }, cases y, { simp [top_rpow_of_pos H] }, cases x, { exact (not_top_le_coe h₁).elim }, simp at h₁, simp [coe_rpow_of_nonneg _ h₂, nnreal.rpow_le_rpow h₁ h₂] end lemma rpow_lt_rpow {x y : ℝ≥0∞} {z : ℝ} (h₁ : x < y) (h₂ : 0 < z) : x^z < y^z := begin cases x, { exact (not_top_lt h₁).elim }, cases y, { simp [top_rpow_of_pos h₂, coe_rpow_of_nonneg _ (le_of_lt h₂)] }, simp at h₁, simp [coe_rpow_of_nonneg _ (le_of_lt h₂), nnreal.rpow_lt_rpow h₁ h₂] end lemma rpow_le_rpow_iff {x y : ℝ≥0∞} {z : ℝ} (hz : 0 < z) : x ^ z ≤ y ^ z ↔ x ≤ y := begin refine ⟨λ h, _, λ h, rpow_le_rpow h (le_of_lt hz)⟩, rw [←rpow_one x, ←rpow_one y, ←@_root_.mul_inv_cancel _ _ z (ne_of_lt hz).symm, rpow_mul, rpow_mul, ←one_div], exact rpow_le_rpow h (by simp [le_of_lt hz]), end lemma rpow_lt_rpow_iff {x y : ℝ≥0∞} {z : ℝ} (hz : 0 < z) : x ^ z < y ^ z ↔ x < y := begin refine ⟨λ h_lt, _, λ h, rpow_lt_rpow h hz⟩, rw [←rpow_one x, ←rpow_one y, ←@_root_.mul_inv_cancel _ _ z (ne_of_lt hz).symm, rpow_mul, rpow_mul], exact rpow_lt_rpow h_lt (by simp [hz]), end lemma le_rpow_one_div_iff {x y : ℝ≥0∞} {z : ℝ} (hz : 0 < z) : x ≤ y ^ (1 / z) ↔ x ^ z ≤ y := begin nth_rewrite 0 ←rpow_one x, nth_rewrite 0 ←@_root_.mul_inv_cancel _ _ z (ne_of_lt hz).symm, rw [rpow_mul, ←one_div, @rpow_le_rpow_iff _ _ (1/z) (by simp [hz])], end lemma lt_rpow_one_div_iff {x y : ℝ≥0∞} {z : ℝ} (hz : 0 < z) : x < y ^ (1 / z) ↔ x ^ z < y := begin nth_rewrite 0 ←rpow_one x, nth_rewrite 0 ←@_root_.mul_inv_cancel _ _ z (ne_of_lt hz).symm, rw [rpow_mul, ←one_div, @rpow_lt_rpow_iff _ _ (1/z) (by simp [hz])], end lemma rpow_lt_rpow_of_exponent_lt {x : ℝ≥0∞} {y z : ℝ} (hx : 1 < x) (hx' : x ≠ ⊤) (hyz : y < z) : x^y < x^z := begin lift x to ℝ≥0 using hx', rw [one_lt_coe_iff] at hx, simp [coe_rpow_of_ne_zero (ne_of_gt (lt_trans zero_lt_one hx)), nnreal.rpow_lt_rpow_of_exponent_lt hx hyz] end lemma rpow_le_rpow_of_exponent_le {x : ℝ≥0∞} {y z : ℝ} (hx : 1 ≤ x) (hyz : y ≤ z) : x^y ≤ x^z := begin cases x, { rcases lt_trichotomy y 0 with Hy|Hy|Hy; rcases lt_trichotomy z 0 with Hz|Hz|Hz; simp [Hy, Hz, top_rpow_of_neg, top_rpow_of_pos, le_refl]; linarith }, { simp only [one_le_coe_iff, some_eq_coe] at hx, simp [coe_rpow_of_ne_zero (ne_of_gt (lt_of_lt_of_le zero_lt_one hx)), nnreal.rpow_le_rpow_of_exponent_le hx hyz] } end lemma rpow_lt_rpow_of_exponent_gt {x : ℝ≥0∞} {y z : ℝ} (hx0 : 0 < x) (hx1 : x < 1) (hyz : z < y) : x^y < x^z := begin lift x to ℝ≥0 using ne_of_lt (lt_of_lt_of_le hx1 le_top), simp at hx0 hx1, simp [coe_rpow_of_ne_zero (ne_of_gt hx0), nnreal.rpow_lt_rpow_of_exponent_gt hx0 hx1 hyz] end lemma rpow_le_rpow_of_exponent_ge {x : ℝ≥0∞} {y z : ℝ} (hx1 : x ≤ 1) (hyz : z ≤ y) : x^y ≤ x^z := begin lift x to ℝ≥0 using ne_of_lt (lt_of_le_of_lt hx1 coe_lt_top), by_cases h : x = 0, { rcases lt_trichotomy y 0 with Hy|Hy|Hy; rcases lt_trichotomy z 0 with Hz|Hz|Hz; simp [Hy, Hz, h, zero_rpow_of_neg, zero_rpow_of_pos, le_refl]; linarith }, { simp at hx1, simp [coe_rpow_of_ne_zero h, nnreal.rpow_le_rpow_of_exponent_ge (bot_lt_iff_ne_bot.mpr h) hx1 hyz] } end lemma rpow_le_self_of_le_one {x : ℝ≥0∞} {z : ℝ} (hx : x ≤ 1) (h_one_le : 1 ≤ z) : x ^ z ≤ x := begin nth_rewrite 1 ←ennreal.rpow_one x, exact ennreal.rpow_le_rpow_of_exponent_ge hx h_one_le, end lemma le_rpow_self_of_one_le {x : ℝ≥0∞} {z : ℝ} (hx : 1 ≤ x) (h_one_le : 1 ≤ z) : x ≤ x ^ z := begin nth_rewrite 0 ←ennreal.rpow_one x, exact ennreal.rpow_le_rpow_of_exponent_le hx h_one_le, end lemma rpow_pos_of_nonneg {p : ℝ} {x : ℝ≥0∞} (hx_pos : 0 < x) (hp_nonneg : 0 ≤ p) : 0 < x^p := begin by_cases hp_zero : p = 0, { simp [hp_zero, ennreal.zero_lt_one], }, { rw ←ne.def at hp_zero, have hp_pos := lt_of_le_of_ne hp_nonneg hp_zero.symm, rw ←zero_rpow_of_pos hp_pos, exact rpow_lt_rpow hx_pos hp_pos, }, end lemma rpow_pos {p : ℝ} {x : ℝ≥0∞} (hx_pos : 0 < x) (hx_ne_top : x ≠ ⊤) : 0 < x^p := begin cases lt_or_le 0 p with hp_pos hp_nonpos, { exact rpow_pos_of_nonneg hx_pos (le_of_lt hp_pos), }, { rw [←neg_neg p, rpow_neg, inv_pos], exact rpow_ne_top_of_nonneg (by simp [hp_nonpos]) hx_ne_top, }, end lemma rpow_lt_one {x : ℝ≥0∞} {z : ℝ} (hx : x < 1) (hz : 0 < z) : x^z < 1 := begin lift x to ℝ≥0 using ne_of_lt (lt_of_lt_of_le hx le_top), simp only [coe_lt_one_iff] at hx, simp [coe_rpow_of_nonneg _ (le_of_lt hz), nnreal.rpow_lt_one (zero_le x) hx hz], end lemma rpow_le_one {x : ℝ≥0∞} {z : ℝ} (hx : x ≤ 1) (hz : 0 ≤ z) : x^z ≤ 1 := begin lift x to ℝ≥0 using ne_of_lt (lt_of_le_of_lt hx coe_lt_top), simp only [coe_le_one_iff] at hx, simp [coe_rpow_of_nonneg _ hz, nnreal.rpow_le_one hx hz], end lemma rpow_lt_one_of_one_lt_of_neg {x : ℝ≥0∞} {z : ℝ} (hx : 1 < x) (hz : z < 0) : x^z < 1 := begin cases x, { simp [top_rpow_of_neg hz, ennreal.zero_lt_one] }, { simp only [some_eq_coe, one_lt_coe_iff] at hx, simp [coe_rpow_of_ne_zero (ne_of_gt (lt_trans zero_lt_one hx)), nnreal.rpow_lt_one_of_one_lt_of_neg hx hz] }, end lemma rpow_le_one_of_one_le_of_neg {x : ℝ≥0∞} {z : ℝ} (hx : 1 ≤ x) (hz : z < 0) : x^z ≤ 1 := begin cases x, { simp [top_rpow_of_neg hz, ennreal.zero_lt_one] }, { simp only [one_le_coe_iff, some_eq_coe] at hx, simp [coe_rpow_of_ne_zero (ne_of_gt (lt_of_lt_of_le zero_lt_one hx)), nnreal.rpow_le_one_of_one_le_of_nonpos hx (le_of_lt hz)] }, end lemma one_lt_rpow {x : ℝ≥0∞} {z : ℝ} (hx : 1 < x) (hz : 0 < z) : 1 < x^z := begin cases x, { simp [top_rpow_of_pos hz] }, { simp only [some_eq_coe, one_lt_coe_iff] at hx, simp [coe_rpow_of_nonneg _ (le_of_lt hz), nnreal.one_lt_rpow hx hz] } end lemma one_le_rpow {x : ℝ≥0∞} {z : ℝ} (hx : 1 ≤ x) (hz : 0 < z) : 1 ≤ x^z := begin cases x, { simp [top_rpow_of_pos hz] }, { simp only [one_le_coe_iff, some_eq_coe] at hx, simp [coe_rpow_of_nonneg _ (le_of_lt hz), nnreal.one_le_rpow hx (le_of_lt hz)] }, end lemma one_lt_rpow_of_pos_of_lt_one_of_neg {x : ℝ≥0∞} {z : ℝ} (hx1 : 0 < x) (hx2 : x < 1) (hz : z < 0) : 1 < x^z := begin lift x to ℝ≥0 using ne_of_lt (lt_of_lt_of_le hx2 le_top), simp only [coe_lt_one_iff, coe_pos] at ⊢ hx1 hx2, simp [coe_rpow_of_ne_zero (ne_of_gt hx1), nnreal.one_lt_rpow_of_pos_of_lt_one_of_neg hx1 hx2 hz], end lemma one_le_rpow_of_pos_of_le_one_of_neg {x : ℝ≥0∞} {z : ℝ} (hx1 : 0 < x) (hx2 : x ≤ 1) (hz : z < 0) : 1 ≤ x^z := begin lift x to ℝ≥0 using ne_of_lt (lt_of_le_of_lt hx2 coe_lt_top), simp only [coe_le_one_iff, coe_pos] at ⊢ hx1 hx2, simp [coe_rpow_of_ne_zero (ne_of_gt hx1), nnreal.one_le_rpow_of_pos_of_le_one_of_nonpos hx1 hx2 (le_of_lt hz)], end lemma to_nnreal_rpow (x : ℝ≥0∞) (z : ℝ) : (x.to_nnreal) ^ z = (x ^ z).to_nnreal := begin rcases lt_trichotomy z 0 with H|H|H, { cases x, { simp [H, ne_of_lt] }, by_cases hx : x = 0, { simp [hx, H, ne_of_lt] }, { simp [coe_rpow_of_ne_zero hx] } }, { simp [H] }, { cases x, { simp [H, ne_of_gt] }, simp [coe_rpow_of_nonneg _ (le_of_lt H)] } end lemma to_real_rpow (x : ℝ≥0∞) (z : ℝ) : (x.to_real) ^ z = (x ^ z).to_real := by rw [ennreal.to_real, ennreal.to_real, ←nnreal.coe_rpow, ennreal.to_nnreal_rpow] lemma of_real_rpow_of_pos {x p : ℝ} (hx_pos : 0 < x) : ennreal.of_real x ^ p = ennreal.of_real (x ^ p) := begin simp_rw ennreal.of_real, rw [coe_rpow_of_ne_zero, coe_eq_coe, real.to_nnreal_rpow_of_nonneg hx_pos.le], simp [hx_pos], end lemma of_real_rpow_of_nonneg {x p : ℝ} (hx_nonneg : 0 ≤ x) (hp_nonneg : 0 ≤ p) : ennreal.of_real x ^ p = ennreal.of_real (x ^ p) := begin by_cases hp0 : p = 0, { simp [hp0], }, by_cases hx0 : x = 0, { rw ← ne.def at hp0, have hp_pos : 0 < p := lt_of_le_of_ne hp_nonneg hp0.symm, simp [hx0, hp_pos, hp_pos.ne.symm], }, rw ← ne.def at hx0, exact of_real_rpow_of_pos (hx_nonneg.lt_of_ne hx0.symm), end lemma rpow_left_injective {x : ℝ} (hx : x ≠ 0) : function.injective (λ y : ℝ≥0∞, y^x) := begin intros y z hyz, dsimp only at hyz, rw [←rpow_one y, ←rpow_one z, ←_root_.mul_inv_cancel hx, rpow_mul, rpow_mul, hyz], end lemma rpow_left_surjective {x : ℝ} (hx : x ≠ 0) : function.surjective (λ y : ℝ≥0∞, y^x) := λ y, ⟨y ^ x⁻¹, by simp_rw [←rpow_mul, _root_.inv_mul_cancel hx, rpow_one]⟩ lemma rpow_left_bijective {x : ℝ} (hx : x ≠ 0) : function.bijective (λ y : ℝ≥0∞, y^x) := ⟨rpow_left_injective hx, rpow_left_surjective hx⟩ lemma rpow_left_monotone_of_nonneg {x : ℝ} (hx : 0 ≤ x) : monotone (λ y : ℝ≥0∞, y^x) := λ y z hyz, rpow_le_rpow hyz hx lemma rpow_left_strict_mono_of_pos {x : ℝ} (hx : 0 < x) : strict_mono (λ y : ℝ≥0∞, y^x) := λ y z hyz, rpow_lt_rpow hyz hx theorem tendsto_rpow_at_top {y : ℝ} (hy : 0 < y) : tendsto (λ (x : ℝ≥0∞), x ^ y) (𝓝 ⊤) (𝓝 ⊤) := begin rw tendsto_nhds_top_iff_nnreal, intros x, obtain ⟨c, _, hc⟩ := (at_top_basis_Ioi.tendsto_iff at_top_basis_Ioi).mp (nnreal.tendsto_rpow_at_top hy) x trivial, have hc' : set.Ioi (↑c) ∈ 𝓝 (⊤ : ℝ≥0∞) := Ioi_mem_nhds coe_lt_top, refine eventually_of_mem hc' _, intros a ha, by_cases ha' : a = ⊤, { simp [ha', hy] }, lift a to ℝ≥0 using ha', change ↑c < ↑a at ha, rw coe_rpow_of_nonneg _ hy.le, exact_mod_cast hc a (by exact_mod_cast ha), end private lemma continuous_at_rpow_const_of_pos {x : ℝ≥0∞} {y : ℝ} (h : 0 < y) : continuous_at (λ a : ennreal, a ^ y) x := begin by_cases hx : x = ⊤, { rw [hx, continuous_at], convert tendsto_rpow_at_top h, simp [h] }, lift x to ℝ≥0 using hx, rw continuous_at_coe_iff, convert continuous_coe.continuous_at.comp (nnreal.continuous_at_rpow_const (or.inr h.le)) using 1, ext1 x, simp [coe_rpow_of_nonneg _ h.le] end @[continuity] lemma continuous_rpow_const {y : ℝ} : continuous (λ a : ennreal, a ^ y) := begin apply continuous_iff_continuous_at.2 (λ x, _), rcases lt_trichotomy 0 y with hy|rfl|hy, { exact continuous_at_rpow_const_of_pos hy }, { simp, exact continuous_at_const }, { obtain ⟨z, hz⟩ : ∃ z, y = -z := ⟨-y, (neg_neg _).symm⟩, have z_pos : 0 < z, by simpa [hz] using hy, simp_rw [hz, rpow_neg], exact ennreal.continuous_inv.continuous_at.comp (continuous_at_rpow_const_of_pos z_pos) } end end ennreal
37c497b2564ab103709e5498d153bf21ad46dcf3
82e44445c70db0f03e30d7be725775f122d72f3e
/src/algebra/direct_limit.lean
f105dc571dc72a099d8bb72a6ce4bf0b59d73344
[ "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
24,960
lean
/- Copyright (c) 2019 Kenny Lau, Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Chris Hughes -/ import data.finset.order import linear_algebra.direct_sum_module import ring_theory.free_comm_ring import ring_theory.ideal.operations /-! # Direct limit of modules, abelian groups, rings, and fields. See Atiyah-Macdonald PP.32-33, Matsumura PP.269-270 Generalizes the notion of "union", or "gluing", of incomparable modules over the same ring, or incomparable abelian groups, or rings, or fields. It is constructed as a quotient of the free module (for the module case) or quotient of the free commutative ring (for the ring case) instead of a quotient of the disjoint union so as to make the operations (addition etc.) "computable". -/ universes u v w u₁ open submodule variables {R : Type u} [ring R] variables {ι : Type v} variables [dec_ι : decidable_eq ι] [directed_order ι] variables (G : ι → Type w) /-- A directed system is a functor from the category (directed poset) to another category. This is used for abelian groups and rings and fields because their maps are not bundled. See module.directed_system -/ class directed_system (f : Π i j, i ≤ j → G i → G j) : Prop := (map_self [] : ∀ i x h, f i i h x = x) (map_map [] : ∀ i j k hij hjk x, f j k hjk (f i j hij x) = f i k (le_trans hij hjk) x) namespace module variables [Π i, add_comm_group (G i)] [Π i, module R (G i)] /-- A directed system is a functor from the category (directed poset) to the category of `R`-modules. -/ class directed_system (f : Π i j, i ≤ j → G i →ₗ[R] G j) : Prop := (map_self [] : ∀ i x h, f i i h x = x) (map_map [] : ∀ i j k hij hjk x, f j k hjk (f i j hij x) = f i k (le_trans hij hjk) x) variables (f : Π i j, i ≤ j → G i →ₗ[R] G j) include dec_ι /-- The direct limit of a directed system is the modules glued together along the maps. -/ def direct_limit : Type (max v w) := (span R $ { a | ∃ (i j) (H : i ≤ j) x, direct_sum.lof R ι G i x - direct_sum.lof R ι G j (f i j H x) = a }).quotient namespace direct_limit instance : add_comm_group (direct_limit G f) := quotient.add_comm_group _ instance : module R (direct_limit G f) := quotient.module _ instance : inhabited (direct_limit G f) := ⟨0⟩ variables (R ι) /-- The canonical map from a component to the direct limit. -/ def of (i) : G i →ₗ[R] direct_limit G f := (mkq _).comp $ direct_sum.lof R ι G i variables {R ι G f} @[simp] lemma of_f {i j hij x} : (of R ι G f j (f i j hij x)) = of R ι G f i x := eq.symm $ (submodule.quotient.eq _).2 $ subset_span ⟨i, j, hij, x, rfl⟩ /-- Every element of the direct limit corresponds to some element in some component of the directed system. -/ theorem exists_of [nonempty ι] (z : direct_limit G f) : ∃ i x, of R ι G f i x = z := nonempty.elim (by apply_instance) $ assume ind : ι, quotient.induction_on' z $ λ z, direct_sum.induction_on z ⟨ind, 0, linear_map.map_zero _⟩ (λ i x, ⟨i, x, rfl⟩) (λ p q ⟨i, x, ihx⟩ ⟨j, y, ihy⟩, let ⟨k, hik, hjk⟩ := directed_order.directed i j in ⟨k, f i k hik x + f j k hjk y, by rw [linear_map.map_add, of_f, of_f, ihx, ihy]; refl⟩) @[elab_as_eliminator] protected theorem induction_on [nonempty ι] {C : direct_limit G f → Prop} (z : direct_limit G f) (ih : ∀ i x, C (of R ι G f i x)) : C z := let ⟨i, x, h⟩ := exists_of z in h ▸ ih i x variables {P : Type u₁} [add_comm_group P] [module R P] (g : Π i, G i →ₗ[R] P) variables (Hg : ∀ i j hij x, g j (f i j hij x) = g i x) include Hg variables (R ι G f) /-- The universal property of the direct limit: maps from the components to another module that respect the directed system structure (i.e. make some diagram commute) give rise to a unique map out of the direct limit. -/ def lift : direct_limit G f →ₗ[R] P := liftq _ (direct_sum.to_module R ι P g) (span_le.2 $ λ a ⟨i, j, hij, x, hx⟩, by rw [← hx, set_like.mem_coe, linear_map.sub_mem_ker_iff, direct_sum.to_module_lof, direct_sum.to_module_lof, Hg]) variables {R ι G f} omit Hg lemma lift_of {i} (x) : lift R ι G f g Hg (of R ι G f i x) = g i x := direct_sum.to_module_lof R _ _ theorem lift_unique [nonempty ι] (F : direct_limit G f →ₗ[R] P) (x) : F x = lift R ι G f (λ i, F.comp $ of R ι G f i) (λ i j hij x, by rw [linear_map.comp_apply, of_f]; refl) x := direct_limit.induction_on x $ λ i x, by rw lift_of; refl section totalize open_locale classical variables (G f) omit dec_ι /-- `totalize G f i j` is a linear map from `G i` to `G j`, for *every* `i` and `j`. If `i ≤ j`, then it is the map `f i j` that comes with the directed system `G`, and otherwise it is the zero map. -/ noncomputable def totalize : Π i j, G i →ₗ[R] G j := λ i j, if h : i ≤ j then f i j h else 0 variables {G f} lemma totalize_apply (i j x) : totalize G f i j x = if h : i ≤ j then f i j h x else 0 := if h : i ≤ j then by dsimp only [totalize]; rw [dif_pos h, dif_pos h] else by dsimp only [totalize]; rw [dif_neg h, dif_neg h, linear_map.zero_apply] end totalize variables [directed_system G f] open_locale classical lemma to_module_totalize_of_le {x : direct_sum ι G} {i j : ι} (hij : i ≤ j) (hx : ∀ k ∈ x.support, k ≤ i) : direct_sum.to_module R ι (G j) (λ k, totalize G f k j) x = f i j hij (direct_sum.to_module R ι (G i) (λ k, totalize G f k i) x) := begin rw [← @dfinsupp.sum_single ι G _ _ _ x], unfold dfinsupp.sum, simp only [linear_map.map_sum], refine finset.sum_congr rfl (λ k hk, _), rw direct_sum.single_eq_lof R k (x k), simp [totalize_apply, hx k hk, le_trans (hx k hk) hij, directed_system.map_map f] end lemma of.zero_exact_aux [nonempty ι] {x : direct_sum ι G} (H : submodule.quotient.mk x = (0 : direct_limit G f)) : ∃ j, (∀ k ∈ x.support, k ≤ j) ∧ direct_sum.to_module R ι (G j) (λ i, totalize G f i j) x = (0 : G j) := nonempty.elim (by apply_instance) $ assume ind : ι, span_induction ((quotient.mk_eq_zero _).1 H) (λ x ⟨i, j, hij, y, hxy⟩, let ⟨k, hik, hjk⟩ := directed_order.directed i j in ⟨k, begin clear_, subst hxy, split, { intros i0 hi0, rw [dfinsupp.mem_support_iff, direct_sum.sub_apply, ← direct_sum.single_eq_lof, ← direct_sum.single_eq_lof, dfinsupp.single_apply, dfinsupp.single_apply] at hi0, split_ifs at hi0 with hi hj hj, { rwa hi at hik }, { rwa hi at hik }, { rwa hj at hjk }, exfalso, apply hi0, rw sub_zero }, simp [linear_map.map_sub, totalize_apply, hik, hjk, directed_system.map_map f, direct_sum.apply_eq_component, direct_sum.component.of], end⟩) ⟨ind, λ _ h, (finset.not_mem_empty _ h).elim, linear_map.map_zero _⟩ (λ x y ⟨i, hi, hxi⟩ ⟨j, hj, hyj⟩, let ⟨k, hik, hjk⟩ := directed_order.directed i j in ⟨k, λ l hl, (finset.mem_union.1 (dfinsupp.support_add hl)).elim (λ hl, le_trans (hi _ hl) hik) (λ hl, le_trans (hj _ hl) hjk), by simp [linear_map.map_add, hxi, hyj, to_module_totalize_of_le hik hi, to_module_totalize_of_le hjk hj]⟩) (λ a x ⟨i, hi, hxi⟩, ⟨i, λ k hk, hi k (direct_sum.support_smul _ _ hk), by simp [linear_map.map_smul, hxi]⟩) /-- A component that corresponds to zero in the direct limit is already zero in some bigger module in the directed system. -/ theorem of.zero_exact {i x} (H : of R ι G f i x = 0) : ∃ j hij, f i j hij x = (0 : G j) := by haveI : nonempty ι := ⟨i⟩; exact let ⟨j, hj, hxj⟩ := of.zero_exact_aux H in if hx0 : x = 0 then ⟨i, le_refl _, by simp [hx0]⟩ else have hij : i ≤ j, from hj _ $ by simp [direct_sum.apply_eq_component, hx0], ⟨j, hij, by simpa [totalize_apply, hij] using hxj⟩ end direct_limit end module namespace add_comm_group variables [Π i, add_comm_group (G i)] include dec_ι /-- The direct limit of a directed system is the abelian groups glued together along the maps. -/ def direct_limit (f : Π i j, i ≤ j → G i →+ G j) : Type* := @module.direct_limit ℤ _ ι _ _ G _ _ (λ i j hij, (f i j hij).to_int_linear_map) namespace direct_limit variables (f : Π i j, i ≤ j → G i →+ G j) omit dec_ι protected lemma directed_system [directed_system G (λ i j h, f i j h)] : module.directed_system G (λ i j hij, (f i j hij).to_int_linear_map) := ⟨directed_system.map_self (λ i j h, f i j h), directed_system.map_map (λ i j h, f i j h)⟩ include dec_ι local attribute [instance] direct_limit.directed_system instance : add_comm_group (direct_limit G f) := module.direct_limit.add_comm_group G (λ i j hij, (f i j hij).to_int_linear_map) instance : inhabited (direct_limit G f) := ⟨0⟩ /-- The canonical map from a component to the direct limit. -/ def of (i) : G i →ₗ[ℤ] direct_limit G f := module.direct_limit.of ℤ ι G (λ i j hij, (f i j hij).to_int_linear_map) i variables {G f} @[simp] lemma of_f {i j} (hij) (x) : of G f j (f i j hij x) = of G f i x := module.direct_limit.of_f @[elab_as_eliminator] protected theorem induction_on [nonempty ι] {C : direct_limit G f → Prop} (z : direct_limit G f) (ih : ∀ i x, C (of G f i x)) : C z := module.direct_limit.induction_on z ih /-- A component that corresponds to zero in the direct limit is already zero in some bigger module in the directed system. -/ theorem of.zero_exact [directed_system G (λ i j h, f i j h)] (i x) (h : of G f i x = 0) : ∃ j hij, f i j hij x = 0 := module.direct_limit.of.zero_exact h variables (P : Type u₁) [add_comm_group P] variables (g : Π i, G i →+ P) variables (Hg : ∀ i j hij x, g j (f i j hij x) = g i x) variables (G f) /-- The universal property of the direct limit: maps from the components to another abelian group that respect the directed system structure (i.e. make some diagram commute) give rise to a unique map out of the direct limit. -/ def lift : direct_limit G f →ₗ[ℤ] P := module.direct_limit.lift ℤ ι G (λ i j hij, (f i j hij).to_int_linear_map) (λ i, (g i).to_int_linear_map) Hg variables {G f} @[simp] lemma lift_of (i x) : lift G f P g Hg (of G f i x) = g i x := module.direct_limit.lift_of _ _ _ lemma lift_unique [nonempty ι] (F : direct_limit G f →+ P) (x) : F x = lift G f P (λ i, F.comp (of G f i).to_add_monoid_hom) (λ i j hij x, by simp) x := direct_limit.induction_on x $ λ i x, by simp end direct_limit end add_comm_group namespace ring variables [Π i, comm_ring (G i)] section variables (f : Π i j, i ≤ j → G i → G j) open free_comm_ring /-- The direct limit of a directed system is the rings glued together along the maps. -/ def direct_limit : Type (max v w) := (ideal.span { a | (∃ i j H x, of (⟨j, f i j H x⟩ : Σ i, G i) - of ⟨i, x⟩ = a) ∨ (∃ i, of (⟨i, 1⟩ : Σ i, G i) - 1 = a) ∨ (∃ i x y, of (⟨i, x + y⟩ : Σ i, G i) - (of ⟨i, x⟩ + of ⟨i, y⟩) = a) ∨ (∃ i x y, of (⟨i, x * y⟩ : Σ i, G i) - (of ⟨i, x⟩ * of ⟨i, y⟩) = a) }).quotient namespace direct_limit instance : comm_ring (direct_limit G f) := ideal.quotient.comm_ring _ instance : ring (direct_limit G f) := comm_ring.to_ring _ instance : inhabited (direct_limit G f) := ⟨0⟩ /-- The canonical map from a component to the direct limit. -/ def of (i) : G i →+* direct_limit G f := ring_hom.mk' { to_fun := λ x, ideal.quotient.mk _ (of (⟨i, x⟩ : Σ i, G i)), map_one' := ideal.quotient.eq.2 $ subset_span $ or.inr $ or.inl ⟨i, rfl⟩, map_mul' := λ x y, ideal.quotient.eq.2 $ subset_span $ or.inr $ or.inr $ or.inr ⟨i, x, y, rfl⟩, } (λ x y, ideal.quotient.eq.2 $ subset_span $ or.inr $ or.inr $ or.inl ⟨i, x, y, rfl⟩) variables {G f} @[simp] lemma of_f {i j} (hij) (x) : of G f j (f i j hij x) = of G f i x := ideal.quotient.eq.2 $ subset_span $ or.inl ⟨i, j, hij, x, rfl⟩ /-- Every element of the direct limit corresponds to some element in some component of the directed system. -/ theorem exists_of [nonempty ι] (z : direct_limit G f) : ∃ i x, of G f i x = z := nonempty.elim (by apply_instance) $ assume ind : ι, quotient.induction_on' z $ λ x, free_abelian_group.induction_on x ⟨ind, 0, (of _ _ ind).map_zero⟩ (λ s, multiset.induction_on s ⟨ind, 1, (of _ _ ind).map_one⟩ (λ a s ih, let ⟨i, x⟩ := a, ⟨j, y, hs⟩ := ih, ⟨k, hik, hjk⟩ := directed_order.directed i j in ⟨k, f i k hik x * f j k hjk y, by rw [(of _ _ _).map_mul, of_f, of_f, hs]; refl⟩)) (λ s ⟨i, x, ih⟩, ⟨i, -x, by rw [(of _ _ _).map_neg, ih]; refl⟩) (λ p q ⟨i, x, ihx⟩ ⟨j, y, ihy⟩, let ⟨k, hik, hjk⟩ := directed_order.directed i j in ⟨k, f i k hik x + f j k hjk y, by rw [(of _ _ _).map_add, of_f, of_f, ihx, ihy]; refl⟩) section open_locale classical open polynomial variables {f' : Π i j, i ≤ j → G i →+* G j} theorem polynomial.exists_of [nonempty ι] (q : polynomial (direct_limit G (λ i j h, f' i j h))) : ∃ i p, polynomial.map (of G (λ i j h, f' i j h) i) p = q := polynomial.induction_on q (λ z, let ⟨i, x, h⟩ := exists_of z in ⟨i, C x, by rw [map_C, h]⟩) (λ q₁ q₂ ⟨i₁, p₁, ih₁⟩ ⟨i₂, p₂, ih₂⟩, let ⟨i, h1, h2⟩ := directed_order.directed i₁ i₂ in ⟨i, p₁.map (f' i₁ i h1) + p₂.map (f' i₂ i h2), by { rw [polynomial.map_add, map_map, map_map, ← ih₁, ← ih₂], congr' 2; ext x; simp_rw [ring_hom.comp_apply, of_f] }⟩) (λ n z ih, let ⟨i, x, h⟩ := exists_of z in ⟨i, C x * X ^ (n + 1), by rw [polynomial.map_mul, map_C, h, polynomial.map_pow, map_X]⟩) end @[elab_as_eliminator] theorem induction_on [nonempty ι] {C : direct_limit G f → Prop} (z : direct_limit G f) (ih : ∀ i x, C (of G f i x)) : C z := let ⟨i, x, hx⟩ := exists_of z in hx ▸ ih i x section of_zero_exact open_locale classical variables (f' : Π i j, i ≤ j → G i →+* G j) variables [directed_system G (λ i j h, f' i j h)] variables (G f) lemma of.zero_exact_aux2 {x : free_comm_ring Σ i, G i} {s t} (hxs : is_supported x s) {j k} (hj : ∀ z : Σ i, G i, z ∈ s → z.1 ≤ j) (hk : ∀ z : Σ i, G i, z ∈ t → z.1 ≤ k) (hjk : j ≤ k) (hst : s ⊆ t) : f' j k hjk (lift (λ ix : s, f' ix.1.1 j (hj ix ix.2) ix.1.2) (restriction s x)) = lift (λ ix : t, f' ix.1.1 k (hk ix ix.2) ix.1.2) (restriction t x) := begin refine subring.in_closure.rec_on hxs _ _ _ _, { rw [(restriction _).map_one, (free_comm_ring.lift _).map_one, (f' j k hjk).map_one, (restriction _).map_one, (free_comm_ring.lift _).map_one] }, { rw [(restriction _).map_neg, (restriction _).map_one, (free_comm_ring.lift _).map_neg, (free_comm_ring.lift _).map_one, (f' j k hjk).map_neg, (f' j k hjk).map_one, (restriction _).map_neg, (restriction _).map_one, (free_comm_ring.lift _).map_neg, (free_comm_ring.lift _).map_one] }, { rintros _ ⟨p, hps, rfl⟩ n ih, rw [(restriction _).map_mul, (free_comm_ring.lift _).map_mul, (f' j k hjk).map_mul, ih, (restriction _).map_mul, (free_comm_ring.lift _).map_mul, restriction_of, dif_pos hps, lift_of, restriction_of, dif_pos (hst hps), lift_of], dsimp only, have := directed_system.map_map (λ i j h, f' i j h), dsimp only at this, rw this, refl }, { rintros x y ihx ihy, rw [(restriction _).map_add, (free_comm_ring.lift _).map_add, (f' j k hjk).map_add, ihx, ihy, (restriction _).map_add, (free_comm_ring.lift _).map_add] } end variables {G f f'} lemma of.zero_exact_aux [nonempty ι] {x : free_comm_ring Σ i, G i} (H : ideal.quotient.mk _ x = (0 : direct_limit G (λ i j h, f' i j h))) : ∃ j s, ∃ H : (∀ k : Σ i, G i, k ∈ s → k.1 ≤ j), is_supported x s ∧ lift (λ ix : s, f' ix.1.1 j (H ix ix.2) ix.1.2) (restriction s x) = (0 : G j) := begin refine span_induction (ideal.quotient.eq_zero_iff_mem.1 H) _ _ _ _, { rintros x (⟨i, j, hij, x, rfl⟩ | ⟨i, rfl⟩ | ⟨i, x, y, rfl⟩ | ⟨i, x, y, rfl⟩), { refine ⟨j, {⟨i, x⟩, ⟨j, f' i j hij x⟩}, _, is_supported_sub (is_supported_of.2 $ or.inr rfl) (is_supported_of.2 $ or.inl rfl), _⟩, { rintros k (rfl | ⟨rfl | _⟩), exact hij, refl }, { rw [(restriction _).map_sub, (free_comm_ring.lift _).map_sub, restriction_of, dif_pos, restriction_of, dif_pos, lift_of, lift_of], dsimp only, have := directed_system.map_map (λ i j h, f' i j h), dsimp only at this, rw this, exact sub_self _, exacts [or.inr rfl, or.inl rfl] } }, { refine ⟨i, {⟨i, 1⟩}, _, is_supported_sub (is_supported_of.2 rfl) is_supported_one, _⟩, { rintros k (rfl|h), refl }, { rw [(restriction _).map_sub, (free_comm_ring.lift _).map_sub, restriction_of, dif_pos, (restriction _).map_one, lift_of, (free_comm_ring.lift _).map_one], dsimp only, rw [(f' i i _).map_one, sub_self], { exact set.mem_singleton _ } } }, { refine ⟨i, {⟨i, x+y⟩, ⟨i, x⟩, ⟨i, y⟩}, _, is_supported_sub (is_supported_of.2 $ or.inl rfl) (is_supported_add (is_supported_of.2 $ or.inr $ or.inl rfl) (is_supported_of.2 $ or.inr $ or.inr rfl)), _⟩, { rintros k (rfl | ⟨rfl | ⟨rfl | hk⟩⟩); refl }, { rw [(restriction _).map_sub, (restriction _).map_add, restriction_of, restriction_of, restriction_of, dif_pos, dif_pos, dif_pos, (free_comm_ring.lift _).map_sub, (free_comm_ring.lift _).map_add, lift_of, lift_of, lift_of], dsimp only, rw (f' i i _).map_add, exact sub_self _, exacts [or.inl rfl, or.inr (or.inr rfl), or.inr (or.inl rfl)] } }, { refine ⟨i, {⟨i, x*y⟩, ⟨i, x⟩, ⟨i, y⟩}, _, is_supported_sub (is_supported_of.2 $ or.inl rfl) (is_supported_mul (is_supported_of.2 $ or.inr $ or.inl rfl) (is_supported_of.2 $ or.inr $ or.inr rfl)), _⟩, { rintros k (rfl | ⟨rfl | ⟨rfl | hk⟩⟩); refl }, { rw [(restriction _).map_sub, (restriction _).map_mul, restriction_of, restriction_of, restriction_of, dif_pos, dif_pos, dif_pos, (free_comm_ring.lift _).map_sub, (free_comm_ring.lift _).map_mul, lift_of, lift_of, lift_of], dsimp only, rw (f' i i _).map_mul, exacts [sub_self _, or.inl rfl, or.inr (or.inr rfl), or.inr (or.inl rfl)] } } }, { refine nonempty.elim (by apply_instance) (assume ind : ι, _), refine ⟨ind, ∅, λ _, false.elim, is_supported_zero, _⟩, rw [(restriction _).map_zero, (free_comm_ring.lift _).map_zero] }, { rintros x y ⟨i, s, hi, hxs, ihs⟩ ⟨j, t, hj, hyt, iht⟩, rcases directed_order.directed i j with ⟨k, hik, hjk⟩, have : ∀ z : Σ i, G i, z ∈ s ∪ t → z.1 ≤ k, { rintros z (hz | hz), exact le_trans (hi z hz) hik, exact le_trans (hj z hz) hjk }, refine ⟨k, s ∪ t, this, is_supported_add (is_supported_upwards hxs $ set.subset_union_left s t) (is_supported_upwards hyt $ set.subset_union_right s t), _⟩, { rw [(restriction _).map_add, (free_comm_ring.lift _).map_add, ← of.zero_exact_aux2 G f' hxs hi this hik (set.subset_union_left s t), ← of.zero_exact_aux2 G f' hyt hj this hjk (set.subset_union_right s t), ihs, (f' i k hik).map_zero, iht, (f' j k hjk).map_zero, zero_add] } }, { rintros x y ⟨j, t, hj, hyt, iht⟩, rw smul_eq_mul, rcases exists_finset_support x with ⟨s, hxs⟩, rcases (s.image sigma.fst).exists_le with ⟨i, hi⟩, rcases directed_order.directed i j with ⟨k, hik, hjk⟩, have : ∀ z : Σ i, G i, z ∈ ↑s ∪ t → z.1 ≤ k, { rintros z (hz | hz), exacts [(hi z.1 $ finset.mem_image.2 ⟨z, hz, rfl⟩).trans hik, (hj z hz).trans hjk] }, refine ⟨k, ↑s ∪ t, this, is_supported_mul (is_supported_upwards hxs $ set.subset_union_left ↑s t) (is_supported_upwards hyt $ set.subset_union_right ↑s t), _⟩, rw [(restriction _).map_mul, (free_comm_ring.lift _).map_mul, ← of.zero_exact_aux2 G f' hyt hj this hjk (set.subset_union_right ↑s t), iht, (f' j k hjk).map_zero, mul_zero] } end /-- A component that corresponds to zero in the direct limit is already zero in some bigger module in the directed system. -/ lemma of.zero_exact {i x} (hix : of G (λ i j h, f' i j h) i x = 0) : ∃ j (hij : i ≤ j), f' i j hij x = 0 := by haveI : nonempty ι := ⟨i⟩; exact let ⟨j, s, H, hxs, hx⟩ := of.zero_exact_aux hix in have hixs : (⟨i, x⟩ : Σ i, G i) ∈ s, from is_supported_of.1 hxs, ⟨j, H ⟨i, x⟩ hixs, by rw [restriction_of, dif_pos hixs, lift_of] at hx; exact hx⟩ end of_zero_exact variables (f' : Π i j, i ≤ j → G i →+* G j) /-- If the maps in the directed system are injective, then the canonical maps from the components to the direct limits are injective. -/ theorem of_injective [directed_system G (λ i j h, f' i j h)] (hf : ∀ i j hij, function.injective (f' i j hij)) (i) : function.injective (of G (λ i j h, f' i j h) i) := begin suffices : ∀ x, of G (λ i j h, f' i j h) i x = 0 → x = 0, { intros x y hxy, rw ← sub_eq_zero, apply this, rw [(of G _ i).map_sub, hxy, sub_self] }, intros x hx, rcases of.zero_exact hx with ⟨j, hij, hfx⟩, apply hf i j hij, rw [hfx, (f' i j hij).map_zero] end variables (P : Type u₁) [comm_ring P] variables (g : Π i, G i →+* P) variables (Hg : ∀ i j hij x, g j (f i j hij x) = g i x) include Hg open free_comm_ring variables (G f) /-- The universal property of the direct limit: maps from the components to another ring that respect the directed system structure (i.e. make some diagram commute) give rise to a unique map out of the direct limit. -/ def lift : direct_limit G f →+* P := ideal.quotient.lift _ (free_comm_ring.lift $ λ (x : Σ i, G i), g x.1 x.2) begin suffices : ideal.span _ ≤ ideal.comap (free_comm_ring.lift (λ (x : Σ (i : ι), G i), g (x.fst) (x.snd))) ⊥, { intros x hx, exact (mem_bot P).1 (this hx) }, rw ideal.span_le, intros x hx, rw [set_like.mem_coe, ideal.mem_comap, mem_bot], rcases hx with ⟨i, j, hij, x, rfl⟩ | ⟨i, rfl⟩ | ⟨i, x, y, rfl⟩ | ⟨i, x, y, rfl⟩; simp only [ring_hom.map_sub, lift_of, Hg, ring_hom.map_one, ring_hom.map_add, ring_hom.map_mul, (g i).map_one, (g i).map_add, (g i).map_mul, sub_self] end variables {G f} omit Hg @[simp] lemma lift_of (i x) : lift G f P g Hg (of G f i x) = g i x := free_comm_ring.lift_of _ _ theorem lift_unique [nonempty ι] (F : direct_limit G f →+* P) (x) : F x = lift G f P (λ i, F.comp $ of G f i) (λ i j hij x, by simp) x := direct_limit.induction_on x $ λ i x, by simp end direct_limit end end ring namespace field variables [nonempty ι] [Π i, field (G i)] variables (f : Π i j, i ≤ j → G i → G j) variables (f' : Π i j, i ≤ j → G i →+* G j) namespace direct_limit instance nontrivial [directed_system G (λ i j h, f' i j h)] : nontrivial (ring.direct_limit G (λ i j h, f' i j h)) := ⟨⟨0, 1, nonempty.elim (by apply_instance) $ assume i : ι, begin change (0 : ring.direct_limit G (λ i j h, f' i j h)) ≠ 1, rw ← (ring.direct_limit.of _ _ _).map_one, intros H, rcases ring.direct_limit.of.zero_exact H.symm with ⟨j, hij, hf⟩, rw (f' i j hij).map_one at hf, exact one_ne_zero hf end ⟩⟩ theorem exists_inv {p : ring.direct_limit G f} : p ≠ 0 → ∃ y, p * y = 1 := ring.direct_limit.induction_on p $ λ i x H, ⟨ring.direct_limit.of G f i (x⁻¹), by erw [← (ring.direct_limit.of _ _ _).map_mul, mul_inv_cancel (assume h : x = 0, H $ by rw [h, (ring.direct_limit.of _ _ _).map_zero]), (ring.direct_limit.of _ _ _).map_one]⟩ section open_locale classical /-- Noncomputable multiplicative inverse in a direct limit of fields. -/ noncomputable def inv (p : ring.direct_limit G f) : ring.direct_limit G f := if H : p = 0 then 0 else classical.some (direct_limit.exists_inv G f H) protected theorem mul_inv_cancel {p : ring.direct_limit G f} (hp : p ≠ 0) : p * inv G f p = 1 := by rw [inv, dif_neg hp, classical.some_spec (direct_limit.exists_inv G f hp)] protected theorem inv_mul_cancel {p : ring.direct_limit G f} (hp : p ≠ 0) : inv G f p * p = 1 := by rw [_root_.mul_comm, direct_limit.mul_inv_cancel G f hp] /-- Noncomputable field structure on the direct limit of fields. -/ protected noncomputable def field [directed_system G (λ i j h, f' i j h)] : field (ring.direct_limit G (λ i j h, f' i j h)) := { inv := inv G (λ i j h, f' i j h), mul_inv_cancel := λ p, direct_limit.mul_inv_cancel G (λ i j h, f' i j h), inv_zero := dif_pos rfl, .. ring.direct_limit.comm_ring G (λ i j h, f' i j h), .. direct_limit.nontrivial G (λ i j h, f' i j h) } end end direct_limit end field
9e7705f28f232e051b909e27d8ef3c3f404f5791
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/field_theory/separable.lean
4094b01bd7f997cda724671a8f8a2586824f367c
[ "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
25,689
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.polynomial.big_operators import field_theory.minpoly import field_theory.splitting_field import field_theory.tower import algebra.squarefree /-! # Separable polynomials We define a polynomial to be separable if it is coprime with its derivative. We prove basic properties about separable polynomials here. ## Main definitions * `polynomial.separable f`: a polynomial `f` is separable iff it is coprime with its derivative. * `polynomial.expand R p f`: expand the polynomial `f` with coefficients in a commutative semiring `R` by a factor of p, so `expand R p (∑ aₙ xⁿ)` is `∑ aₙ xⁿᵖ`. * `polynomial.contract p f`: the opposite of `expand`, so it sends `∑ aₙ xⁿᵖ` to `∑ aₙ xⁿ`. -/ universes u v w open_locale classical big_operators open finset namespace polynomial section comm_semiring variables {R : Type u} [comm_semiring R] {S : Type v} [comm_semiring S] /-- A polynomial is separable iff it is coprime with its derivative. -/ def separable (f : polynomial R) : Prop := is_coprime f f.derivative lemma separable_def (f : polynomial R) : f.separable ↔ is_coprime f f.derivative := iff.rfl lemma separable_def' (f : polynomial R) : f.separable ↔ ∃ a b : polynomial R, a * f + b * f.derivative = 1 := iff.rfl lemma separable_one : (1 : polynomial R).separable := is_coprime_one_left lemma separable_X_add_C (a : R) : (X + C a).separable := by { rw [separable_def, derivative_add, derivative_X, derivative_C, add_zero], exact is_coprime_one_right } lemma separable_X : (X : polynomial R).separable := by { rw [separable_def, derivative_X], exact is_coprime_one_right } lemma separable_C (r : R) : (C r).separable ↔ is_unit r := by rw [separable_def, derivative_C, is_coprime_zero_right, is_unit_C] lemma separable.of_mul_left {f g : polynomial R} (h : (f * g).separable) : f.separable := begin have := h.of_mul_left_left, rw derivative_mul at this, exact is_coprime.of_mul_right_left (is_coprime.of_add_mul_left_right this) end lemma separable.of_mul_right {f g : polynomial R} (h : (f * g).separable) : g.separable := by { rw mul_comm at h, exact h.of_mul_left } lemma separable.of_dvd {f g : polynomial R} (hf : f.separable) (hfg : g ∣ f) : g.separable := by { rcases hfg with ⟨f', rfl⟩, exact separable.of_mul_left hf } lemma separable_gcd_left {F : Type*} [field F] {f : polynomial F} (hf : f.separable) (g : polynomial F) : (euclidean_domain.gcd f g).separable := separable.of_dvd hf (euclidean_domain.gcd_dvd_left f g) lemma separable_gcd_right {F : Type*} [field F] {g : polynomial F} (f : polynomial F) (hg : g.separable) : (euclidean_domain.gcd f g).separable := separable.of_dvd hg (euclidean_domain.gcd_dvd_right f g) lemma separable.is_coprime {f g : polynomial R} (h : (f * g).separable) : is_coprime f g := begin have := h.of_mul_left_left, rw derivative_mul at this, exact is_coprime.of_mul_right_right (is_coprime.of_add_mul_left_right this) end theorem separable.of_pow' {f : polynomial R} : ∀ {n : ℕ} (h : (f ^ n).separable), is_unit f ∨ (f.separable ∧ n = 1) ∨ n = 0 | 0 := λ h, or.inr $ or.inr rfl | 1 := λ h, or.inr $ or.inl ⟨pow_one f ▸ h, rfl⟩ | (n+2) := λ h, or.inl $ is_coprime_self.1 h.is_coprime.of_mul_right_left theorem separable.of_pow {f : polynomial R} (hf : ¬is_unit f) {n : ℕ} (hn : n ≠ 0) (hfs : (f ^ n).separable) : f.separable ∧ n = 1 := (hfs.of_pow'.resolve_left hf).resolve_right hn theorem separable.map {p : polynomial R} (h : p.separable) {f : R →+* S} : (p.map f).separable := let ⟨a, b, H⟩ := h in ⟨a.map f, b.map f, by rw [derivative_map, ← map_mul, ← map_mul, ← map_add, H, map_one]⟩ variables (R) (p q : ℕ) /-- Expand the polynomial by a factor of p, so `∑ aₙ xⁿ` becomes `∑ aₙ xⁿᵖ`. -/ noncomputable def expand : polynomial R →ₐ[R] polynomial R := { commutes' := λ r, eval₂_C _ _, .. (eval₂_ring_hom C (X ^ p) : polynomial R →+* polynomial R) } lemma coe_expand : (expand R p : polynomial R → polynomial R) = eval₂ C (X ^ p) := rfl variables {R} lemma expand_eq_sum {f : polynomial R} : expand R p f = f.sum (λ e a, C a * (X ^ p) ^ e) := by { dsimp [expand, eval₂], refl, } @[simp] lemma expand_C (r : R) : expand R p (C r) = C r := eval₂_C _ _ @[simp] lemma expand_X : expand R p X = X ^ p := eval₂_X _ _ @[simp] lemma expand_monomial (r : R) : expand R p (monomial q r) = monomial (q * p) r := by simp_rw [monomial_eq_smul_X, alg_hom.map_smul, alg_hom.map_pow, expand_X, mul_comm, pow_mul] theorem expand_expand (f : polynomial R) : expand R p (expand R q f) = expand R (p * q) f := polynomial.induction_on f (λ r, by simp_rw expand_C) (λ f g ihf ihg, by simp_rw [alg_hom.map_add, ihf, ihg]) (λ n r ih, by simp_rw [alg_hom.map_mul, expand_C, alg_hom.map_pow, expand_X, alg_hom.map_pow, expand_X, pow_mul]) theorem expand_mul (f : polynomial R) : expand R (p * q) f = expand R p (expand R q f) := (expand_expand p q f).symm @[simp] theorem expand_one (f : polynomial R) : expand R 1 f = f := polynomial.induction_on f (λ r, by rw expand_C) (λ f g ihf ihg, by rw [alg_hom.map_add, ihf, ihg]) (λ n r ih, by rw [alg_hom.map_mul, expand_C, alg_hom.map_pow, expand_X, pow_one]) theorem expand_pow (f : polynomial R) : expand R (p ^ q) f = (expand R p ^[q] f) := nat.rec_on q (by rw [pow_zero, expand_one, function.iterate_zero, id]) $ λ n ih, by rw [function.iterate_succ_apply', pow_succ, expand_mul, ih] theorem derivative_expand (f : polynomial R) : (expand R p f).derivative = expand R p f.derivative * (p * X ^ (p - 1)) := by rw [coe_expand, derivative_eval₂_C, derivative_pow, derivative_X, mul_one] theorem coeff_expand {p : ℕ} (hp : 0 < p) (f : polynomial R) (n : ℕ) : (expand R p f).coeff n = if p ∣ n then f.coeff (n / p) else 0 := begin simp only [expand_eq_sum], simp_rw [coeff_sum, ← pow_mul, C_mul_X_pow_eq_monomial, coeff_monomial, finsupp.sum], split_ifs with h, { rw [finset.sum_eq_single (n/p), nat.mul_div_cancel' h, if_pos rfl], refl, { intros b hb1 hb2, rw if_neg, intro hb3, apply hb2, rw [← hb3, nat.mul_div_cancel_left b hp] }, { intro hn, rw finsupp.not_mem_support_iff.1 hn, split_ifs; refl } }, { rw finset.sum_eq_zero, intros k hk, rw if_neg, exact λ hkn, h ⟨k, hkn.symm⟩, }, end @[simp] theorem coeff_expand_mul {p : ℕ} (hp : 0 < p) (f : polynomial R) (n : ℕ) : (expand R p f).coeff (n * p) = f.coeff n := by rw [coeff_expand hp, if_pos (dvd_mul_left _ _), nat.mul_div_cancel _ hp] @[simp] theorem coeff_expand_mul' {p : ℕ} (hp : 0 < p) (f : polynomial R) (n : ℕ) : (expand R p f).coeff (p * n) = f.coeff n := by rw [mul_comm, coeff_expand_mul hp] theorem expand_eq_map_domain (p : ℕ) (f : polynomial R) : expand R p f = f.map_domain (*p) := polynomial.induction_on' f (λ p q hp hq, by simp [*, finsupp.map_domain_add]) $ λ n a, by simp_rw [expand_monomial, monomial_def, finsupp.map_domain_single] theorem expand_inj {p : ℕ} (hp : 0 < p) {f g : polynomial R} : expand R p f = expand R p g ↔ f = g := ⟨λ H, ext $ λ n, by rw [← coeff_expand_mul hp, H, coeff_expand_mul hp], congr_arg _⟩ theorem expand_eq_zero {p : ℕ} (hp : 0 < p) {f : polynomial R} : expand R p f = 0 ↔ f = 0 := by rw [← (expand R p).map_zero, expand_inj hp, alg_hom.map_zero] theorem expand_eq_C {p : ℕ} (hp : 0 < p) {f : polynomial R} {r : R} : expand R p f = C r ↔ f = C r := by rw [← expand_C, expand_inj hp, expand_C] theorem nat_degree_expand (p : ℕ) (f : polynomial R) : (expand R p f).nat_degree = f.nat_degree * p := begin cases p.eq_zero_or_pos with hp hp, { rw [hp, coe_expand, pow_zero, mul_zero, ← C_1, eval₂_hom, nat_degree_C] }, by_cases hf : f = 0, { rw [hf, alg_hom.map_zero, nat_degree_zero, zero_mul] }, have hf1 : expand R p f ≠ 0 := mt (expand_eq_zero hp).1 hf, rw [← with_bot.coe_eq_coe, ← degree_eq_nat_degree hf1], refine le_antisymm ((degree_le_iff_coeff_zero _ _).2 $ λ n hn, _) _, { rw coeff_expand hp, split_ifs with hpn, { rw coeff_eq_zero_of_nat_degree_lt, contrapose! hn, rw [with_bot.coe_le_coe, ← nat.div_mul_cancel hpn], exact nat.mul_le_mul_right p hn }, { refl } }, { refine le_degree_of_ne_zero _, rw [coeff_expand_mul hp, ← leading_coeff], exact mt leading_coeff_eq_zero.1 hf } end theorem map_expand {p : ℕ} (hp : 0 < p) {f : R →+* S} {q : polynomial R} : map f (expand R p q) = expand S p (map f q) := by { ext, rw [coeff_map, coeff_expand hp, coeff_expand hp], split_ifs; simp, } end comm_semiring section comm_ring variables {R : Type u} [comm_ring R] lemma separable_X_sub_C {x : R} : separable (X - C x) := by simpa only [sub_eq_add_neg, C_neg] using separable_X_add_C (-x) lemma separable.mul {f g : polynomial R} (hf : f.separable) (hg : g.separable) (h : is_coprime f g) : (f * g).separable := by { rw [separable_def, derivative_mul], exact ((hf.mul_right h).add_mul_left_right _).mul_left ((h.symm.mul_right hg).mul_add_right_right _) } lemma separable_prod' {ι : Sort*} {f : ι → polynomial R} {s : finset ι} : (∀x∈s, ∀y∈s, x ≠ y → is_coprime (f x) (f y)) → (∀x∈s, (f x).separable) → (∏ x in s, f x).separable := finset.induction_on s (λ _ _, separable_one) $ λ a s has ih h1 h2, begin simp_rw [finset.forall_mem_insert, forall_and_distrib] at h1 h2, rw prod_insert has, exact h2.1.mul (ih h1.2.2 h2.2) (is_coprime.prod_right $ λ i his, h1.1.2 i his $ ne.symm $ ne_of_mem_of_not_mem his has) end lemma separable_prod {ι : Sort*} [fintype ι] {f : ι → polynomial R} (h1 : pairwise (is_coprime on f)) (h2 : ∀ x, (f x).separable) : (∏ x, f x).separable := separable_prod' (λ x hx y hy hxy, h1 x y hxy) (λ x hx, h2 x) lemma separable.inj_of_prod_X_sub_C [nontrivial R] {ι : Sort*} {f : ι → R} {s : finset ι} (hfs : (∏ i in s, (X - C (f i))).separable) {x y : ι} (hx : x ∈ s) (hy : y ∈ s) (hfxy : f x = f y) : x = y := begin by_contra hxy, rw [← insert_erase hx, prod_insert (not_mem_erase _ _), ← insert_erase (mem_erase_of_ne_of_mem (ne.symm hxy) hy), prod_insert (not_mem_erase _ _), ← mul_assoc, hfxy, ← pow_two] at hfs, cases (hfs.of_mul_left.of_pow (by exact not_is_unit_X_sub_C) two_ne_zero).2 end lemma separable.injective_of_prod_X_sub_C [nontrivial R] {ι : Sort*} [fintype ι] {f : ι → R} (hfs : (∏ i, (X - C (f i))).separable) : function.injective f := λ x y hfxy, hfs.inj_of_prod_X_sub_C (mem_univ _) (mem_univ _) hfxy lemma is_unit_of_self_mul_dvd_separable {p q : polynomial R} (hp : p.separable) (hq : q * q ∣ p) : is_unit q := begin obtain ⟨p, rfl⟩ := hq, apply is_coprime_self.mp, have : is_coprime (q * (q * p)) (q * (q.derivative * p + q.derivative * p + q * p.derivative)), { simp only [← mul_assoc, mul_add], convert hp, rw [derivative_mul, derivative_mul], ring }, exact is_coprime.of_mul_right_left (is_coprime.of_mul_left_left this) end end comm_ring section integral_domain variables (R : Type u) [integral_domain R] theorem is_local_ring_hom_expand {p : ℕ} (hp : 0 < p) : is_local_ring_hom (↑(expand R p) : polynomial R →+* polynomial R) := begin refine ⟨λ f hf1, _⟩, rw ← coe_fn_coe_base at hf1, have hf2 := eq_C_of_degree_eq_zero (degree_eq_zero_of_is_unit hf1), rw [coeff_expand hp, if_pos (dvd_zero _), p.zero_div] at hf2, rw [hf2, is_unit_C] at hf1, rw expand_eq_C hp at hf2, rwa [hf2, is_unit_C] end end integral_domain section field variables {F : Type u} [field F] {K : Type v} [field K] theorem separable_iff_derivative_ne_zero {f : polynomial F} (hf : irreducible f) : f.separable ↔ f.derivative ≠ 0 := ⟨λ h1 h2, hf.not_unit $ is_coprime_zero_right.1 $ h2 ▸ h1, λ h, is_coprime_of_dvd (mt and.right h) $ λ g hg1 hg2 ⟨p, hg3⟩ hg4, let ⟨u, hu⟩ := (hf.is_unit_or_is_unit hg3).resolve_left hg1 in have f ∣ f.derivative, by { conv_lhs { rw [hg3, ← hu] }, rwa units.mul_right_dvd }, not_lt_of_le (nat_degree_le_of_dvd this h) $ nat_degree_derivative_lt h⟩ theorem separable_map (f : F →+* K) {p : polynomial F} : (p.map f).separable ↔ p.separable := by simp_rw [separable_def, derivative_map, is_coprime_map] section char_p variables (p : ℕ) [hp : fact p.prime] include hp /-- The opposite of `expand`: sends `∑ aₙ xⁿᵖ` to `∑ aₙ xⁿ`. -/ noncomputable def contract (f : polynomial F) : polynomial F := ⟨f.support.preimage (*p) $ λ _ _ _ _, (nat.mul_left_inj hp.1.pos).1, λ n, f.coeff (n * p), λ n, by rw [finset.mem_preimage, mem_support_iff]⟩ theorem coeff_contract (f : polynomial F) (n : ℕ) : (contract p f).coeff n = f.coeff (n * p) := rfl theorem of_irreducible_expand {f : polynomial F} (hf : irreducible (expand F p f)) : irreducible f := @@of_irreducible_map _ _ _ (is_local_ring_hom_expand F hp.1.pos) hf theorem of_irreducible_expand_pow {f : polynomial F} {n : ℕ} : irreducible (expand F (p ^ n) f) → irreducible f := nat.rec_on n (λ hf, by rwa [pow_zero, expand_one] at hf) $ λ n ih hf, ih $ of_irreducible_expand p $ by rwa [expand_expand] variables [HF : char_p F p] include HF theorem expand_char (f : polynomial F) : map (frobenius F p) (expand F p f) = f ^ p := begin refine f.induction_on' (λ a b ha hb, _) (λ n a, _), { rw [alg_hom.map_add, map_add, ha, hb, add_pow_char], }, { rw [expand_monomial, map_monomial, single_eq_C_mul_X, single_eq_C_mul_X, mul_pow, ← C.map_pow, frobenius_def], ring_exp } end theorem map_expand_pow_char (f : polynomial F) (n : ℕ) : map ((frobenius F p) ^ n) (expand F (p ^ n) f) = f ^ (p ^ n) := begin induction n, {simp [ring_hom.one_def]}, symmetry, rw [pow_succ', pow_mul, ← n_ih, ← expand_char, pow_succ, ring_hom.mul_def, ← map_map, mul_comm, expand_mul, ← map_expand (nat.prime.pos hp.1)], end theorem expand_contract {f : polynomial F} (hf : f.derivative = 0) : expand F p (contract p f) = f := begin ext n, rw [coeff_expand hp.1.pos, coeff_contract], split_ifs with h, { rw nat.div_mul_cancel h }, { cases n, { exact absurd (dvd_zero p) h }, have := coeff_derivative f n, rw [hf, coeff_zero, zero_eq_mul] at this, cases this, { rw this }, rw [← nat.cast_succ, char_p.cast_eq_zero_iff F p] at this, exact absurd this h } end theorem separable_or {f : polynomial F} (hf : irreducible f) : f.separable ∨ ¬f.separable ∧ ∃ g : polynomial F, irreducible g ∧ expand F p g = f := if H : f.derivative = 0 then or.inr ⟨by rw [separable_iff_derivative_ne_zero hf, not_not, H], contract p f, by haveI := is_local_ring_hom_expand F hp.1.pos; exact of_irreducible_map ↑(expand F p) (by rwa ← expand_contract p H at hf), expand_contract p H⟩ else or.inl $ (separable_iff_derivative_ne_zero hf).2 H theorem exists_separable_of_irreducible {f : polynomial F} (hf : irreducible f) (hf0 : f ≠ 0) : ∃ (n : ℕ) (g : polynomial F), g.separable ∧ expand F (p ^ n) g = f := begin generalize hn : f.nat_degree = N, unfreezingI { revert f }, apply nat.strong_induction_on N, intros N ih f hf hf0 hn, rcases separable_or p hf with h | ⟨h1, g, hg, hgf⟩, { refine ⟨0, f, h, _⟩, rw [pow_zero, expand_one] }, { cases N with N, { rw [nat_degree_eq_zero_iff_degree_le_zero, degree_le_zero_iff] at hn, rw [hn, separable_C, is_unit_iff_ne_zero, not_not] at h1, rw [h1, C_0] at hn, exact absurd hn hf0 }, have hg1 : g.nat_degree * p = N.succ, { rwa [← nat_degree_expand, hgf] }, have hg2 : g.nat_degree ≠ 0, { intro this, rw [this, zero_mul] at hg1, cases hg1 }, have hg3 : g.nat_degree < N.succ, { rw [← mul_one g.nat_degree, ← hg1], exact nat.mul_lt_mul_of_pos_left hp.1.one_lt (nat.pos_of_ne_zero hg2) }, have hg4 : g ≠ 0, { rintro rfl, exact hg2 nat_degree_zero }, rcases ih _ hg3 hg hg4 rfl with ⟨n, g, hg5, rfl⟩, refine ⟨n+1, g, hg5, _⟩, rw [← hgf, expand_expand, pow_succ] } end theorem is_unit_or_eq_zero_of_separable_expand {f : polynomial F} (n : ℕ) (hf : (expand F (p ^ n) f).separable) : is_unit f ∨ n = 0 := begin rw or_iff_not_imp_right, intro hn, have hf2 : (expand F (p ^ n) f).derivative = 0, { by rw [derivative_expand, nat.cast_pow, char_p.cast_eq_zero, zero_pow (nat.pos_of_ne_zero hn), zero_mul, mul_zero] }, rw [separable_def, hf2, is_coprime_zero_right, is_unit_iff] at hf, rcases hf with ⟨r, hr, hrf⟩, rw [eq_comm, expand_eq_C (pow_pos hp.1.pos _)] at hrf, rwa [hrf, is_unit_C] end theorem unique_separable_of_irreducible {f : polynomial F} (hf : irreducible f) (hf0 : f ≠ 0) (n₁ : ℕ) (g₁ : polynomial F) (hg₁ : g₁.separable) (hgf₁ : expand F (p ^ n₁) g₁ = f) (n₂ : ℕ) (g₂ : polynomial F) (hg₂ : g₂.separable) (hgf₂ : expand F (p ^ n₂) g₂ = f) : n₁ = n₂ ∧ g₁ = g₂ := begin revert g₁ g₂, wlog hn : n₁ ≤ n₂ := le_total n₁ n₂ using [n₁ n₂, n₂ n₁] tactic.skip, unfreezingI { intros, rw le_iff_exists_add at hn, rcases hn with ⟨k, rfl⟩, rw [← hgf₁, pow_add, expand_mul, expand_inj (pow_pos hp.1.pos n₁)] at hgf₂, subst hgf₂, subst hgf₁, rcases is_unit_or_eq_zero_of_separable_expand p k hg₁ with h | rfl, { rw is_unit_iff at h, rcases h with ⟨r, hr, rfl⟩, simp_rw expand_C at hf, exact absurd (is_unit_C.2 hr) hf.1 }, { rw [add_zero, pow_zero, expand_one], split; refl } }, exact λ g₁ g₂ hg₁ hgf₁ hg₂ hgf₂, let ⟨hn, hg⟩ := this g₂ g₁ hg₂ hgf₂ hg₁ hgf₁ in ⟨hn.symm, hg.symm⟩ end end char_p lemma separable_prod_X_sub_C_iff' {ι : Sort*} {f : ι → F} {s : finset ι} : (∏ i in s, (X - C (f i))).separable ↔ (∀ (x ∈ s) (y ∈ s), f x = f y → x = y) := ⟨λ hfs x hx y hy hfxy, hfs.inj_of_prod_X_sub_C hx hy hfxy, λ H, by { rw ← prod_attach, exact separable_prod' (λ x hx y hy hxy, @pairwise_coprime_X_sub _ _ { x // x ∈ s } (λ x, f x) (λ x y hxy, subtype.eq $ H x.1 x.2 y.1 y.2 hxy) _ _ hxy) (λ _ _, separable_X_sub_C) }⟩ lemma separable_prod_X_sub_C_iff {ι : Sort*} [fintype ι] {f : ι → F} : (∏ i, (X - C (f i))).separable ↔ function.injective f := separable_prod_X_sub_C_iff'.trans $ by simp_rw [mem_univ, true_implies_iff] section splits open_locale big_operators variables {i : F →+* K} lemma not_unit_X_sub_C (a : F) : ¬ is_unit (X - C a) := λ h, have one_eq_zero : (1 : with_bot ℕ) = 0, by simpa using degree_eq_zero_of_is_unit h, one_ne_zero (option.some_injective _ one_eq_zero) lemma nodup_of_separable_prod {s : multiset F} (hs : separable (multiset.map (λ a, X - C a) s).prod) : s.nodup := begin rw multiset.nodup_iff_ne_cons_cons, rintros a t rfl, refine not_unit_X_sub_C a (is_unit_of_self_mul_dvd_separable hs _), simpa only [multiset.map_cons, multiset.prod_cons] using mul_dvd_mul_left _ (dvd_mul_right _ _) end lemma multiplicity_le_one_of_separable {p q : polynomial F} (hq : ¬ is_unit q) (hsep : separable p) : multiplicity q p ≤ 1 := begin contrapose! hq, apply is_unit_of_self_mul_dvd_separable hsep, rw ← pow_two, apply multiplicity.pow_dvd_of_le_multiplicity, exact_mod_cast (enat.add_one_le_of_lt hq) end lemma separable.squarefree {p : polynomial F} (hsep : separable p) : squarefree p := begin rw multiplicity.squarefree_iff_multiplicity_le_one p, intro f, by_cases hunit : is_unit f, { exact or.inr hunit }, exact or.inl (multiplicity_le_one_of_separable hunit hsep) end /--If `n ≠ 0` in `F`, then ` X ^ n - a` is separable for any `a ≠ 0`. -/ lemma separable_X_pow_sub_C {n : ℕ} (a : F) (hn : (n : F) ≠ 0) (ha : a ≠ 0) : separable (X ^ n - C a) := begin cases nat.eq_zero_or_pos n with hzero hpos, { exfalso, rw hzero at hn, exact hn (refl 0) }, apply (separable_def' (X ^ n - C a)).2, use [-C (a⁻¹), (C ((a⁻¹) * (↑n)⁻¹) * X)], have mul_pow_sub : X * X ^ (n - 1) = X ^ n, { nth_rewrite 0 [←pow_one X], rw pow_mul_pow_sub X (nat.succ_le_iff.mpr hpos) }, rw [derivative_sub, derivative_C, sub_zero, derivative_pow X n, derivative_X, mul_one], have hcalc : C (a⁻¹ * (↑n)⁻¹) * (↑n * (X ^ n)) = C a⁻¹ * (X ^ n), { calc C (a⁻¹ * (↑n)⁻¹) * (↑n * (X ^ n)) = C a⁻¹ * C ((↑n)⁻¹) * (C ↑n * (X ^ n)) : by rw [C_mul, C_eq_nat_cast] ... = C a⁻¹ * (C ((↑n)⁻¹) * C ↑n) * (X ^ n) : by ring ... = C a⁻¹ * C ((↑n)⁻¹ * ↑n) * (X ^ n) : by rw [← C_mul] ... = C a⁻¹ * C 1 * (X ^ n) : by field_simp [hn] ... = C a⁻¹ * (X ^ n) : by rw [C_1, mul_one] }, calc -C a⁻¹ * (X ^ n - C a) + C (a⁻¹ * (↑n)⁻¹) * X * (↑n * X ^ (n - 1)) = -C a⁻¹ * (X ^ n - C a) + C (a⁻¹ * (↑n)⁻¹) * (↑n * (X * X ^ (n - 1))) : by ring ... = -C a⁻¹ * (X ^ n - C a) + C a⁻¹ * (X ^ n) : by rw [mul_pow_sub, hcalc] ... = C a⁻¹ * C a : by ring ... = (1 : polynomial F) : by rw [← C_mul, inv_mul_cancel ha, C_1] end /--If `n ≠ 0` in `F`, then ` X ^ n - a` is squarefree for any `a ≠ 0`. -/ lemma squarefree_X_pow_sub_C {n : ℕ} (a : F) (hn : (n : F) ≠ 0) (ha : a ≠ 0) : squarefree (X ^ n - C a) := (separable_X_pow_sub_C a hn ha).squarefree lemma root_multiplicity_le_one_of_separable {p : polynomial F} (hp : p ≠ 0) (hsep : separable p) (x : F) : root_multiplicity x p ≤ 1 := begin rw [root_multiplicity_eq_multiplicity, dif_neg hp, ← enat.coe_le_coe, enat.coe_get], exact multiplicity_le_one_of_separable (not_unit_X_sub_C _) hsep end lemma count_roots_le_one {p : polynomial F} (hsep : separable p) (x : F) : p.roots.count x ≤ 1 := begin by_cases hp : p = 0, { simp [hp] }, rw count_roots hp, exact root_multiplicity_le_one_of_separable hp hsep x end lemma nodup_roots {p : polynomial F} (hsep : separable p) : p.roots.nodup := multiset.nodup_iff_count_le_one.mpr (count_roots_le_one hsep) lemma eq_X_sub_C_of_separable_of_root_eq {x : F} {h : polynomial F} (h_ne_zero : h ≠ 0) (h_sep : h.separable) (h_root : h.eval x = 0) (h_splits : splits i h) (h_roots : ∀ y ∈ (h.map i).roots, y = i x) : h = (C (leading_coeff h)) * (X - C x) := begin apply polynomial.eq_X_sub_C_of_splits_of_single_root i h_splits, apply finset.mk.inj, { change _ = {i x}, rw finset.eq_singleton_iff_unique_mem, split, { apply finset.mem_mk.mpr, rw mem_roots (show h.map i ≠ 0, by exact map_ne_zero h_ne_zero), rw [is_root.def,←eval₂_eq_eval_map,eval₂_hom,h_root], exact ring_hom.map_zero i }, { exact h_roots } }, { exact nodup_roots (separable.map h_sep) }, end end splits end field end polynomial open polynomial theorem irreducible.separable {F : Type u} [field F] [char_zero F] {f : polynomial F} (hf : irreducible f) : f.separable := begin rw [separable_iff_derivative_ne_zero hf, ne, ← degree_eq_bot, degree_derivative_eq], rintro ⟨⟩, rw [pos_iff_ne_zero, ne, nat_degree_eq_zero_iff_degree_le_zero, degree_le_zero_iff], refine λ hf1, hf.not_unit _, rw [hf1, is_unit_C, is_unit_iff_ne_zero], intro hf2, rw [hf2, C_0] at hf1, exact absurd hf1 hf.ne_zero end -- TODO: refactor to allow transcendental extensions? -- See: https://en.wikipedia.org/wiki/Separable_extension#Separability_of_transcendental_extensions /-- Typeclass for separable field extension: `K` is a separable field extension of `F` iff the minimal polynomial of every `x : K` is separable. -/ class is_separable (F K : Sort*) [field F] [field K] [algebra F K] : Prop := (is_integral' (x : K) : is_integral F x) (separable' (x : K) : (minpoly F x).separable) theorem is_separable.is_integral {F K} [field F] [field K] [algebra F K] (h : is_separable F K) : ∀ x : K, is_integral F x := is_separable.is_integral' theorem is_separable.separable {F K} [field F] [field K] [algebra F K] (h : is_separable F K) : ∀ x : K, (minpoly F x).separable := is_separable.separable' theorem is_separable_iff {F K} [field F] [field K] [algebra F K] : is_separable F K ↔ ∀ x : K, is_integral F x ∧ (minpoly F x).separable := ⟨λ h x, ⟨h.is_integral x, h.separable x⟩, λ h, ⟨λ x, (h x).1, λ x, (h x).2⟩⟩ instance is_separable_self (F : Type*) [field F] : is_separable F F := ⟨λ x, is_integral_algebra_map, λ x, by { rw minpoly.eq_X_sub_C', exact separable_X_sub_C }⟩ section is_separable_tower variables (F K E : Type*) [field F] [field K] [field E] [algebra F K] [algebra F E] [algebra K E] [is_scalar_tower F K E] lemma is_separable_tower_top_of_is_separable [h : is_separable F E] : is_separable K E := ⟨λ x, is_integral_of_is_scalar_tower x (h.is_integral x), λ x, (h.separable x).map.of_dvd (minpoly.dvd_map_of_is_scalar_tower _ _ _)⟩ lemma is_separable_tower_bot_of_is_separable [h : is_separable F E] : is_separable F K := is_separable_iff.2 $ λ x, begin refine (is_separable_iff.1 h (algebra_map K E x)).imp is_integral_tower_bot_of_is_integral_field (λ hs, _), obtain ⟨q, hq⟩ := minpoly.dvd F x (is_scalar_tower.aeval_eq_zero_of_aeval_algebra_map_eq_zero_field (minpoly.aeval F ((algebra_map K E) x))), rw hq at hs, exact hs.of_mul_left end variables {E} lemma is_separable.of_alg_hom (E' : Type*) [field E'] [algebra F E'] (f : E →ₐ[F] E') [is_separable F E'] : is_separable F E := begin letI : algebra E E' := ring_hom.to_algebra f.to_ring_hom, haveI : is_scalar_tower F E E' := is_scalar_tower.of_algebra_map_eq (λ x, (f.commutes x).symm), exact is_separable_tower_bot_of_is_separable F E E', end end is_separable_tower
817b1aeaaa9246c0eae24e250904da422f7b2c0f
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/set/intervals/proj_Icc.lean
3b6d07a28d5742c73104088033d70e41b79cc307
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
4,388
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov, Patrick Massot -/ import data.set.function import data.set.intervals.basic /-! # Projection of a line onto a closed interval Given a linearly ordered type `α`, in this file we define * `set.proj_Icc (a b : α) (h : a ≤ b)` to be the map `α → [a, b]` sending `(-∞, a]` to `a`, `[b, ∞)` to `b`, and each point `x ∈ [a, b]` to itself; * `set.Icc_extend {a b : α} (h : a ≤ b) (f : Icc a b → β)` to be the extension of `f` to `α` defined as `f ∘ proj_Icc a b h`. We also prove some trivial properties of these maps. -/ variables {α β : Type*} [linear_order α] open function namespace set /-- Projection of `α` to the closed interval `[a, b]`. -/ def proj_Icc (a b : α) (h : a ≤ b) (x : α) : Icc a b := ⟨max a (min b x), le_max_left _ _, max_le h (min_le_left _ _)⟩ variables {a b : α} (h : a ≤ b) {x : α} lemma proj_Icc_of_le_left (hx : x ≤ a) : proj_Icc a b h x = ⟨a, left_mem_Icc.2 h⟩ := by simp [proj_Icc, hx, hx.trans h] @[simp] lemma proj_Icc_left : proj_Icc a b h a = ⟨a, left_mem_Icc.2 h⟩ := proj_Icc_of_le_left h le_rfl lemma proj_Icc_of_right_le (hx : b ≤ x) : proj_Icc a b h x = ⟨b, right_mem_Icc.2 h⟩ := by simp [proj_Icc, hx, h] @[simp] lemma proj_Icc_right : proj_Icc a b h b = ⟨b, right_mem_Icc.2 h⟩ := proj_Icc_of_right_le h le_rfl lemma proj_Icc_eq_left (h : a < b) : proj_Icc a b h.le x = ⟨a, left_mem_Icc.mpr h.le⟩ ↔ x ≤ a := begin refine ⟨λ h', _, proj_Icc_of_le_left _⟩, simp_rw [subtype.ext_iff_val, proj_Icc, max_eq_left_iff, min_le_iff, h.not_le, false_or] at h', exact h' end lemma proj_Icc_eq_right (h : a < b) : proj_Icc a b h.le x = ⟨b, right_mem_Icc.mpr h.le⟩ ↔ b ≤ x := begin refine ⟨λ h', _, proj_Icc_of_right_le _⟩, simp_rw [subtype.ext_iff_val, proj_Icc] at h', have := ((max_choice _ _).resolve_left (by simp [h.ne', h'])).symm.trans h', exact min_eq_left_iff.mp this end lemma proj_Icc_of_mem (hx : x ∈ Icc a b) : proj_Icc a b h x = ⟨x, hx⟩ := by simp [proj_Icc, hx.1, hx.2] @[simp] lemma proj_Icc_coe (x : Icc a b) : proj_Icc a b h x = x := by { cases x, apply proj_Icc_of_mem } lemma proj_Icc_surj_on : surj_on (proj_Icc a b h) (Icc a b) univ := λ x _, ⟨x, x.2, proj_Icc_coe h x⟩ lemma proj_Icc_surjective : surjective (proj_Icc a b h) := λ x, ⟨x, proj_Icc_coe h x⟩ @[simp] lemma range_proj_Icc : range (proj_Icc a b h) = univ := (proj_Icc_surjective h).range_eq lemma monotone_proj_Icc : monotone (proj_Icc a b h) := λ x y hxy, max_le_max le_rfl $ min_le_min le_rfl hxy lemma strict_mono_on_proj_Icc : strict_mono_on (proj_Icc a b h) (Icc a b) := λ x hx y hy hxy, by simpa only [proj_Icc_of_mem, hx, hy] /-- Extend a function `[a, b] → β` to a map `α → β`. -/ def Icc_extend {a b : α} (h : a ≤ b) (f : Icc a b → β) : α → β := f ∘ proj_Icc a b h @[simp] lemma Icc_extend_range (f : Icc a b → β) : range (Icc_extend h f) = range f := by simp only [Icc_extend, range_comp f, range_proj_Icc, range_id'] lemma Icc_extend_of_le_left (f : Icc a b → β) (hx : x ≤ a) : Icc_extend h f x = f ⟨a, left_mem_Icc.2 h⟩ := congr_arg f $ proj_Icc_of_le_left h hx @[simp] lemma Icc_extend_left (f : Icc a b → β) : Icc_extend h f a = f ⟨a, left_mem_Icc.2 h⟩ := Icc_extend_of_le_left h f le_rfl lemma Icc_extend_of_right_le (f : Icc a b → β) (hx : b ≤ x) : Icc_extend h f x = f ⟨b, right_mem_Icc.2 h⟩ := congr_arg f $ proj_Icc_of_right_le h hx @[simp] lemma Icc_extend_right (f : Icc a b → β) : Icc_extend h f b = f ⟨b, right_mem_Icc.2 h⟩ := Icc_extend_of_right_le h f le_rfl lemma Icc_extend_of_mem (f : Icc a b → β) (hx : x ∈ Icc a b) : Icc_extend h f x = f ⟨x, hx⟩ := congr_arg f $ proj_Icc_of_mem h hx @[simp] lemma Icc_extend_coe (f : Icc a b → β) (x : Icc a b) : Icc_extend h f x = f x := congr_arg f $ proj_Icc_coe h x end set open set variables [preorder β] {a b : α} (h : a ≤ b) {f : Icc a b → β} lemma monotone.Icc_extend (hf : monotone f) : monotone (Icc_extend h f) := hf.comp $ monotone_proj_Icc h lemma strict_mono.strict_mono_on_Icc_extend (hf : strict_mono f) : strict_mono_on (Icc_extend h f) (Icc a b) := hf.comp_strict_mono_on (strict_mono_on_proj_Icc h)
9b5ca6630fe3cb16fcba843b2442815f91b4a21e
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/run/633.lean
b2b3a7f9e65986832d9be9c19a9f9b65ebcad3dc
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
1,410
lean
abbrev semantics (α:Type) := StateM (List Nat) α inductive expression : Nat → Type | const : (n : Nat) → expression n def uext {w:Nat} (x: expression w) (o:Nat) : expression w := expression.const w def eval {n : Nat} (v:expression n) : semantics (expression n) := pure (expression.const n) def set_overflow {w : Nat} (e : expression w) : semantics Unit := pure () structure instruction := (mnemonic:String) (patterns:List Nat) def definst (mnem:String) (body: expression 8 -> semantics Unit) : instruction := { mnemonic := mnem , patterns := ((body (expression.const 8)).run []).snd.reverse } def mul : instruction := Id.run <| do -- this is a "pure" do block (as in it is the Id monad) definst "mul" $ fun (src : expression 8) => let action : semantics Unit := do -- this is not "pure" do block let tmp <- eval $ uext src 16 set_overflow $ tmp action def mul' : instruction := Id.run <| do -- this is a "pure" do block (as in it is the Id monad) definst "mul" $ fun (src : expression 8) => let rec action : semantics Unit := do -- this is not "pure" do block let tmp <- eval $ uext src 16 set_overflow $ tmp action def mul'' : instruction := Id.run <| do -- this is a "pure" do block (as in it is the Id monad) definst "mul" $ fun (src : expression 8) => let action : semantics (expression 8) := return (<- eval $ uext src 16) pure ()
b2c7f5eaff67afcd4da34a4cb84f090bef874e92
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/Meta/Tactic/Delta.lean
b310159cb4fa0a3e04e2974e08300ba96c0846ba
[ "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
1,924
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.Meta.Transform import Lean.Meta.Tactic.Replace namespace Lean.Meta def delta? (e : Expr) (p : Name → Bool := fun _ => true) : CoreM (Option Expr) := matchConst e.getAppFn (fun _ => return none) fun fInfo fLvls => do if p fInfo.name && fInfo.hasValue && fInfo.levelParams.length == fLvls.length then let f ← instantiateValueLevelParams fInfo fLvls return some (f.betaRev e.getAppRevArgs (useZeta := true)) else return none /-- Low-level delta expansion. It is used to implement equation lemmas and elimination principles for recursive definitions. -/ def deltaExpand (e : Expr) (p : Name → Bool) : CoreM Expr := Core.transform e fun e => do match (← delta? e p) with | some e' => return TransformStep.visit e' | none => return TransformStep.visit e /-- Delta expand declarations that satisfy `p` at `mvarId` type. -/ def _root_.Lean.MVarId.deltaTarget (mvarId : MVarId) (p : Name → Bool) : MetaM MVarId := mvarId.withContext do mvarId.checkNotAssigned `delta mvarId.change (← deltaExpand (← mvarId.getType) p) (checkDefEq := false) @[deprecated MVarId.deltaTarget] def deltaTarget (mvarId : MVarId) (p : Name → Bool) : MetaM MVarId := mvarId.deltaTarget p /-- Delta expand declarations that satisfy `p` at `fvarId` type. -/ def _root_.Lean.MVarId.deltaLocalDecl (mvarId : MVarId) (fvarId : FVarId) (p : Name → Bool) : MetaM MVarId := mvarId.withContext do mvarId.checkNotAssigned `delta mvarId.changeLocalDecl fvarId (← deltaExpand (← mvarId.getType) p) (checkDefEq := false) @[deprecated MVarId.deltaLocalDecl] def deltaLocalDecl (mvarId : MVarId) (fvarId : FVarId) (p : Name → Bool) : MetaM MVarId := mvarId.deltaLocalDecl fvarId p end Lean.Meta
79a3653f766a894fe99f8afdc70f1b9e8803cb97
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/mv_polynomial/variables.lean
5a32886dc6843e6231902ba082ce1c43debbb50b
[ "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
29,346
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Johan Commelin, Mario Carneiro -/ import algebra.big_operators.order import data.mv_polynomial.monad /-! # Degrees and variables of polynomials This file establishes many results about the degree and variable sets of a multivariate polynomial. The *variable set* of a polynomial $P \in R[X]$ is a `finset` containing each $x \in X$ that appears in a monomial in $P$. The *degree set* of a polynomial $P \in R[X]$ is a `multiset` containing, for each $x$ in the variable set, $n$ copies of $x$, where $n$ is the maximum number of copies of $x$ appearing in a monomial of $P$. ## Main declarations * `mv_polynomial.degrees p` : the multiset of variables representing the union of the multisets corresponding to each non-zero monomial in `p`. For example if `7 ≠ 0` in `R` and `p = x²y+7y³` then `degrees p = {x, x, y, y, y}` * `mv_polynomial.vars p` : the finset of variables occurring in `p`. For example if `p = x⁴y+yz` then `vars p = {x, y, z}` * `mv_polynomial.degree_of n p : ℕ` : the total degree of `p` with respect to the variable `n`. For example if `p = x⁴y+yz` then `degree_of y p = 1`. * `mv_polynomial.total_degree p : ℕ` : the max of the sizes of the multisets `s` whose monomials `X^s` occur in `p`. For example if `p = x⁴y+yz` then `total_degree p = 5`. ## Notation As in other polynomial files, we typically use the notation: + `σ τ : Type*` (indexing the variables) + `R : Type*` `[comm_semiring R]` (the coefficients) + `s : σ →₀ ℕ`, a function from `σ` to `ℕ` which is zero away from a finite set. This will give rise to a monomial in `mv_polynomial σ R` which mathematicians might call `X^s` + `r : R` + `i : σ`, with corresponding monomial `X i`, often denoted `X_i` by mathematicians + `p : mv_polynomial σ R` -/ noncomputable theory open_locale classical big_operators open set function finsupp add_monoid_algebra open_locale big_operators universes u v w variables {R : Type u} {S : Type v} namespace mv_polynomial variables {σ τ : Type*} {r : R} {e : ℕ} {n m : σ} {s : σ →₀ ℕ} section comm_semiring variables [comm_semiring R] {p q : mv_polynomial σ R} section degrees /-! ### `degrees` -/ /-- The maximal degrees of each variable in a multi-variable polynomial, expressed as a multiset. (For example, `degrees (x^2 * y + y^3)` would be `{x, x, y, y, y}`.) -/ def degrees (p : mv_polynomial σ R) : multiset σ := p.support.sup (λs:σ →₀ ℕ, s.to_multiset) lemma degrees_monomial (s : σ →₀ ℕ) (a : R) : degrees (monomial s a) ≤ s.to_multiset := finset.sup_le $ assume t h, begin have := finsupp.support_single_subset h, rw [finset.mem_singleton] at this, rw this end lemma degrees_monomial_eq (s : σ →₀ ℕ) (a : R) (ha : a ≠ 0) : degrees (monomial s a) = s.to_multiset := le_antisymm (degrees_monomial s a) $ finset.le_sup $ by rw [support_monomial, if_neg ha, finset.mem_singleton] lemma degrees_C (a : R) : degrees (C a : mv_polynomial σ R) = 0 := multiset.le_zero.1 $ degrees_monomial _ _ lemma degrees_X' (n : σ) : degrees (X n : mv_polynomial σ R) ≤ {n} := le_trans (degrees_monomial _ _) $ le_of_eq $ to_multiset_single _ _ @[simp] lemma degrees_X [nontrivial R] (n : σ) : degrees (X n : mv_polynomial σ R) = {n} := (degrees_monomial_eq _ (1 : R) one_ne_zero).trans (to_multiset_single _ _) @[simp] lemma degrees_zero : degrees (0 : mv_polynomial σ R) = 0 := by { rw ← C_0, exact degrees_C 0 } @[simp] lemma degrees_one : degrees (1 : mv_polynomial σ R) = 0 := degrees_C 1 lemma degrees_add (p q : mv_polynomial σ R) : (p + q).degrees ≤ p.degrees ⊔ q.degrees := begin refine finset.sup_le (assume b hb, _), have := finsupp.support_add hb, rw finset.mem_union at this, cases this, { exact le_sup_of_le_left (finset.le_sup this) }, { exact le_sup_of_le_right (finset.le_sup this) }, end lemma degrees_sum {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) : (∑ i in s, f i).degrees ≤ s.sup (λi, (f i).degrees) := begin refine s.induction _ _, { simp only [finset.sum_empty, finset.sup_empty, degrees_zero], exact le_rfl }, { assume i s his ih, rw [finset.sup_insert, finset.sum_insert his], exact le_trans (degrees_add _ _) (sup_le_sup_left ih _) } end lemma degrees_mul (p q : mv_polynomial σ R) : (p * q).degrees ≤ p.degrees + q.degrees := begin refine finset.sup_le (assume b hb, _), have := support_mul p q hb, simp only [finset.mem_bUnion, finset.mem_singleton] at this, rcases this with ⟨a₁, h₁, a₂, h₂, rfl⟩, rw [finsupp.to_multiset_add], exact add_le_add (finset.le_sup h₁) (finset.le_sup h₂) end lemma degrees_prod {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) : (∏ i in s, f i).degrees ≤ ∑ i in s, (f i).degrees := begin refine s.induction _ _, { simp only [finset.prod_empty, finset.sum_empty, degrees_one] }, { assume i s his ih, rw [finset.prod_insert his, finset.sum_insert his], exact le_trans (degrees_mul _ _) (add_le_add_left ih _) } end lemma degrees_pow (p : mv_polynomial σ R) : ∀(n : ℕ), (p^n).degrees ≤ n • p.degrees | 0 := begin rw [pow_zero, degrees_one], exact multiset.zero_le _ end | (n + 1) := by { rw [pow_succ, add_smul, add_comm, one_smul], exact le_trans (degrees_mul _ _) (add_le_add_left (degrees_pow n) _) } lemma mem_degrees {p : mv_polynomial σ R} {i : σ} : i ∈ p.degrees ↔ ∃ d, p.coeff d ≠ 0 ∧ i ∈ d.support := by simp only [degrees, multiset.mem_sup, ← mem_support_iff, finsupp.mem_to_multiset, exists_prop] lemma le_degrees_add {p q : mv_polynomial σ R} (h : p.degrees.disjoint q.degrees) : p.degrees ≤ (p + q).degrees := begin apply finset.sup_le, intros d hd, rw multiset.disjoint_iff_ne at h, rw multiset.le_iff_count, intros i, rw [degrees, multiset.count_finset_sup], simp only [finsupp.count_to_multiset], by_cases h0 : d = 0, { simp only [h0, zero_le, finsupp.zero_apply], }, { refine @finset.le_sup _ _ _ _ (p + q).support _ d _, rw [mem_support_iff, coeff_add], suffices : q.coeff d = 0, { rwa [this, add_zero, coeff, ← finsupp.mem_support_iff], }, rw [← finsupp.support_eq_empty, ← ne.def, ← finset.nonempty_iff_ne_empty] at h0, obtain ⟨j, hj⟩ := h0, contrapose! h, rw mem_support_iff at hd, refine ⟨j, _, j, _, rfl⟩, all_goals { rw mem_degrees, refine ⟨d, _, hj⟩, assumption } } end lemma degrees_add_of_disjoint {p q : mv_polynomial σ R} (h : multiset.disjoint p.degrees q.degrees) : (p + q).degrees = p.degrees ∪ q.degrees := begin apply le_antisymm, { apply degrees_add }, { apply multiset.union_le, { apply le_degrees_add h }, { rw add_comm, apply le_degrees_add h.symm } } end lemma degrees_map [comm_semiring S] (p : mv_polynomial σ R) (f : R →+* S) : (map f p).degrees ⊆ p.degrees := begin dsimp only [degrees], apply multiset.subset_of_le, apply finset.sup_mono, apply mv_polynomial.support_map_subset end lemma degrees_rename (f : σ → τ) (φ : mv_polynomial σ R) : (rename f φ).degrees ⊆ (φ.degrees.map f) := begin intros i, rw [mem_degrees, multiset.mem_map], rintro ⟨d, hd, hi⟩, obtain ⟨x, rfl, hx⟩ := coeff_rename_ne_zero _ _ _ hd, simp only [map_domain, finsupp.mem_support_iff] at hi, rw [sum_apply, finsupp.sum] at hi, contrapose! hi, rw [finset.sum_eq_zero], intros j hj, simp only [exists_prop, mem_degrees] at hi, specialize hi j ⟨x, hx, hj⟩, rw [single_apply, if_neg hi], end lemma degrees_map_of_injective [comm_semiring S] (p : mv_polynomial σ R) {f : R →+* S} (hf : injective f) : (map f p).degrees = p.degrees := by simp only [degrees, mv_polynomial.support_map_of_injective _ hf] lemma degrees_rename_of_injective {p : mv_polynomial σ R} {f : σ → τ} (h : function.injective f) : degrees (rename f p) = (degrees p).map f := begin simp only [degrees, multiset.map_finset_sup p.support finsupp.to_multiset f h, support_rename_of_injective h, finset.sup_image], refine finset.sup_congr rfl (λ x hx, _), exact (finsupp.to_multiset_map _ _).symm, end end degrees section vars /-! ### `vars` -/ /-- `vars p` is the set of variables appearing in the polynomial `p` -/ def vars (p : mv_polynomial σ R) : finset σ := p.degrees.to_finset @[simp] lemma vars_0 : (0 : mv_polynomial σ R).vars = ∅ := by rw [vars, degrees_zero, multiset.to_finset_zero] @[simp] lemma vars_monomial (h : r ≠ 0) : (monomial s r).vars = s.support := by rw [vars, degrees_monomial_eq _ _ h, finsupp.to_finset_to_multiset] @[simp] lemma vars_C : (C r : mv_polynomial σ R).vars = ∅ := by rw [vars, degrees_C, multiset.to_finset_zero] @[simp] lemma vars_X [nontrivial R] : (X n : mv_polynomial σ R).vars = {n} := by rw [X, vars_monomial (one_ne_zero' R), finsupp.support_single_ne_zero _ (one_ne_zero' ℕ)] lemma mem_vars (i : σ) : i ∈ p.vars ↔ ∃ (d : σ →₀ ℕ) (H : d ∈ p.support), i ∈ d.support := by simp only [vars, multiset.mem_to_finset, mem_degrees, mem_support_iff, exists_prop] lemma mem_support_not_mem_vars_zero {f : mv_polynomial σ R} {x : σ →₀ ℕ} (H : x ∈ f.support) {v : σ} (h : v ∉ vars f) : x v = 0 := begin rw [vars, multiset.mem_to_finset] at h, rw ← finsupp.not_mem_support_iff, contrapose! h, unfold degrees, rw (show f.support = insert x f.support, from eq.symm $ finset.insert_eq_of_mem H), rw finset.sup_insert, simp only [multiset.mem_union, multiset.sup_eq_union], left, rwa [←to_finset_to_multiset, multiset.mem_to_finset] at h, end lemma vars_add_subset (p q : mv_polynomial σ R) : (p + q).vars ⊆ p.vars ∪ q.vars := begin intros x hx, simp only [vars, finset.mem_union, multiset.mem_to_finset] at hx ⊢, simpa using multiset.mem_of_le (degrees_add _ _) hx, end lemma vars_add_of_disjoint (h : disjoint p.vars q.vars) : (p + q).vars = p.vars ∪ q.vars := begin apply finset.subset.antisymm (vars_add_subset p q), intros x hx, simp only [vars, multiset.disjoint_to_finset] at h hx ⊢, rw [degrees_add_of_disjoint h, multiset.to_finset_union], exact hx end section mul lemma vars_mul (φ ψ : mv_polynomial σ R) : (φ * ψ).vars ⊆ φ.vars ∪ ψ.vars := begin intro i, simp only [mem_vars, finset.mem_union], rintro ⟨d, hd, hi⟩, rw [mem_support_iff, coeff_mul] at hd, contrapose! hd, cases hd, rw finset.sum_eq_zero, rintro ⟨d₁, d₂⟩ H, rw finsupp.mem_antidiagonal at H, subst H, obtain H|H : i ∈ d₁.support ∨ i ∈ d₂.support, { simpa only [finset.mem_union] using finsupp.support_add hi, }, { suffices : coeff d₁ φ = 0, by simp [this], rw [coeff, ← finsupp.not_mem_support_iff], intro, solve_by_elim, }, { suffices : coeff d₂ ψ = 0, by simp [this], rw [coeff, ← finsupp.not_mem_support_iff], intro, solve_by_elim, }, end @[simp] lemma vars_one : (1 : mv_polynomial σ R).vars = ∅ := vars_C lemma vars_pow (φ : mv_polynomial σ R) (n : ℕ) : (φ ^ n).vars ⊆ φ.vars := begin induction n with n ih, { simp }, { rw pow_succ, apply finset.subset.trans (vars_mul _ _), exact finset.union_subset (finset.subset.refl _) ih } end /-- The variables of the product of a family of polynomials are a subset of the union of the sets of variables of each polynomial. -/ lemma vars_prod {ι : Type*} {s : finset ι} (f : ι → mv_polynomial σ R) : (∏ i in s, f i).vars ⊆ s.bUnion (λ i, (f i).vars) := begin apply s.induction_on, { simp }, { intros a s hs hsub, simp only [hs, finset.bUnion_insert, finset.prod_insert, not_false_iff], apply finset.subset.trans (vars_mul _ _), exact finset.union_subset_union (finset.subset.refl _) hsub } end section is_domain variables {A : Type*} [comm_ring A] [is_domain A] lemma vars_C_mul (a : A) (ha : a ≠ 0) (φ : mv_polynomial σ A) : (C a * φ).vars = φ.vars := begin ext1 i, simp only [mem_vars, exists_prop, mem_support_iff], apply exists_congr, intro d, apply and_congr _ iff.rfl, rw [coeff_C_mul, mul_ne_zero_iff, eq_true_intro ha, true_and], end end is_domain end mul section sum variables {ι : Type*} (t : finset ι) (φ : ι → mv_polynomial σ R) lemma vars_sum_subset : (∑ i in t, φ i).vars ⊆ finset.bUnion t (λ i, (φ i).vars) := begin apply t.induction_on, { simp }, { intros a s has hsum, rw [finset.bUnion_insert, finset.sum_insert has], refine finset.subset.trans (vars_add_subset _ _) (finset.union_subset_union (finset.subset.refl _) _), assumption } end lemma vars_sum_of_disjoint (h : pairwise $ disjoint on (λ i, (φ i).vars)) : (∑ i in t, φ i).vars = finset.bUnion t (λ i, (φ i).vars) := begin apply t.induction_on, { simp }, { intros a s has hsum, rw [finset.bUnion_insert, finset.sum_insert has, vars_add_of_disjoint, hsum], unfold pairwise on_fun at h, rw hsum, simp only [finset.disjoint_iff_ne] at h ⊢, intros v hv v2 hv2, rw finset.mem_bUnion at hv2, rcases hv2 with ⟨i, his, hi⟩, refine h _ _ hv _ hi, rintro rfl, contradiction } end end sum section map variables [comm_semiring S] (f : R →+* S) variable (p) lemma vars_map : (map f p).vars ⊆ p.vars := by simp [vars, degrees_map] variable {f} lemma vars_map_of_injective (hf : injective f) : (map f p).vars = p.vars := by simp [vars, degrees_map_of_injective _ hf] lemma vars_monomial_single (i : σ) {e : ℕ} {r : R} (he : e ≠ 0) (hr : r ≠ 0) : (monomial (finsupp.single i e) r).vars = {i} := by rw [vars_monomial hr, finsupp.support_single_ne_zero _ he] lemma vars_eq_support_bUnion_support : p.vars = p.support.bUnion finsupp.support := by { ext i, rw [mem_vars, finset.mem_bUnion] } end map end vars section degree_of /-! ### `degree_of` -/ /-- `degree_of n p` gives the highest power of X_n that appears in `p` -/ def degree_of (n : σ) (p : mv_polynomial σ R) : ℕ := p.degrees.count n lemma degree_of_eq_sup (n : σ) (f : mv_polynomial σ R) : degree_of n f = f.support.sup (λ m, m n) := begin rw [degree_of, degrees, multiset.count_finset_sup], congr, ext, simp, end lemma degree_of_lt_iff {n : σ} {f : mv_polynomial σ R} {d : ℕ} (h : 0 < d) : degree_of n f < d ↔ ∀ m : σ →₀ ℕ, m ∈ f.support → m n < d := by rwa [degree_of_eq_sup n f, finset.sup_lt_iff] @[simp] lemma degree_of_zero (n : σ) : degree_of n (0 : mv_polynomial σ R) = 0 := by simp only [degree_of, degrees_zero, multiset.count_zero] @[simp] lemma degree_of_C (a : R) (x : σ): degree_of x (C a : mv_polynomial σ R) = 0 := by simp [degree_of, degrees_C] lemma degree_of_X (i j : σ) [nontrivial R] : degree_of i (X j : mv_polynomial σ R) = if i = j then 1 else 0 := begin by_cases c : i = j, { simp only [c, if_true, eq_self_iff_true, degree_of, degrees_X, multiset.count_singleton] }, simp [c, if_false, degree_of, degrees_X], end lemma degree_of_add_le (n : σ) (f g : mv_polynomial σ R) : degree_of n (f + g) ≤ max (degree_of n f) (degree_of n g) := begin repeat {rw degree_of}, apply (multiset.count_le_of_le n (degrees_add f g)).trans, dsimp, rw multiset.count_union, end lemma monomial_le_degree_of (i : σ) {f : mv_polynomial σ R} {m : σ →₀ ℕ} (h_m : m ∈ f.support) : m i ≤ degree_of i f := begin rw degree_of_eq_sup i, apply finset.le_sup h_m, end -- TODO we can prove equality here if R is a domain lemma degree_of_mul_le (i : σ) (f g: mv_polynomial σ R) : degree_of i (f * g) ≤ degree_of i f + degree_of i g := begin repeat {rw degree_of}, convert multiset.count_le_of_le i (degrees_mul f g), rw multiset.count_add, end lemma degree_of_mul_X_ne {i j : σ} (f : mv_polynomial σ R) (h : i ≠ j) : degree_of i (f * X j) = degree_of i f := begin repeat {rw degree_of_eq_sup i}, rw support_mul_X, simp only [finset.sup_map], congr, ext, simp only [single, nat.one_ne_zero, add_right_eq_self, add_right_embedding_apply, coe_mk, pi.add_apply, comp_app, ite_eq_right_iff, finsupp.coe_add, pi.single_eq_of_ne h], end /- TODO in the following we have equality iff f ≠ 0 -/ lemma degree_of_mul_X_eq (j : σ) (f : mv_polynomial σ R) : degree_of j (f * X j) ≤ degree_of j f + 1 := begin repeat {rw degree_of}, apply (multiset.count_le_of_le j (degrees_mul f (X j))).trans, simp only [multiset.count_add, add_le_add_iff_left], convert multiset.count_le_of_le j (degrees_X' j), rw multiset.count_singleton_self, end lemma degree_of_rename_of_injective {p : mv_polynomial σ R} {f : σ → τ} (h : function.injective f) (i : σ) : degree_of (f i) (rename f p) = degree_of i p := by simp only [degree_of, degrees_rename_of_injective h, multiset.count_map_eq_count' f (p.degrees) h] end degree_of section total_degree /-! ### `total_degree` -/ /-- `total_degree p` gives the maximum |s| over the monomials X^s in `p` -/ def total_degree (p : mv_polynomial σ R) : ℕ := p.support.sup (λs, s.sum $ λn e, e) lemma total_degree_eq (p : mv_polynomial σ R) : p.total_degree = p.support.sup (λm, m.to_multiset.card) := begin rw [total_degree], congr, funext m, exact (finsupp.card_to_multiset _).symm end lemma total_degree_le_degrees_card (p : mv_polynomial σ R) : p.total_degree ≤ p.degrees.card := begin rw [total_degree_eq], exact finset.sup_le (assume s hs, multiset.card_le_of_le $ finset.le_sup hs) end @[simp] lemma total_degree_C (a : R) : (C a : mv_polynomial σ R).total_degree = 0 := nat.eq_zero_of_le_zero $ finset.sup_le $ assume n hn, have _ := finsupp.support_single_subset hn, begin rw [finset.mem_singleton] at this, subst this, exact le_rfl end @[simp] lemma total_degree_zero : (0 : mv_polynomial σ R).total_degree = 0 := by rw [← C_0]; exact total_degree_C (0 : R) @[simp] lemma total_degree_one : (1 : mv_polynomial σ R).total_degree = 0 := total_degree_C (1 : R) @[simp] lemma total_degree_X {R} [comm_semiring R] [nontrivial R] (s : σ) : (X s : mv_polynomial σ R).total_degree = 1 := begin rw [total_degree, support_X], simp only [finset.sup, sum_single_index, finset.fold_singleton, sup_bot_eq], end lemma total_degree_add (a b : mv_polynomial σ R) : (a + b).total_degree ≤ max a.total_degree b.total_degree := finset.sup_le $ assume n hn, have _ := finsupp.support_add hn, begin rw finset.mem_union at this, cases this, { exact le_max_of_le_left (finset.le_sup this) }, { exact le_max_of_le_right (finset.le_sup this) } end lemma total_degree_add_eq_left_of_total_degree_lt {p q : mv_polynomial σ R} (h : q.total_degree < p.total_degree) : (p + q).total_degree = p.total_degree := begin classical, apply le_antisymm, { rw ← max_eq_left_of_lt h, exact total_degree_add p q, }, by_cases hp : p = 0, { simp [hp], }, obtain ⟨b, hb₁, hb₂⟩ := p.support.exists_mem_eq_sup (finsupp.support_nonempty_iff.mpr hp) (λ (m : σ →₀ ℕ), m.to_multiset.card), have hb : ¬ b ∈ q.support, { contrapose! h, rw [total_degree_eq p, hb₂, total_degree_eq], apply finset.le_sup h, }, have hbb : b ∈ (p + q).support, { apply support_sdiff_support_subset_support_add, rw finset.mem_sdiff, exact ⟨hb₁, hb⟩, }, rw [total_degree_eq, hb₂, total_degree_eq], exact finset.le_sup hbb, end lemma total_degree_add_eq_right_of_total_degree_lt {p q : mv_polynomial σ R} (h : q.total_degree < p.total_degree) : (q + p).total_degree = p.total_degree := by rw [add_comm, total_degree_add_eq_left_of_total_degree_lt h] lemma total_degree_mul (a b : mv_polynomial σ R) : (a * b).total_degree ≤ a.total_degree + b.total_degree := finset.sup_le $ assume n hn, have _ := add_monoid_algebra.support_mul a b hn, begin simp only [finset.mem_bUnion, finset.mem_singleton] at this, rcases this with ⟨a₁, h₁, a₂, h₂, rfl⟩, rw [finsupp.sum_add_index'], { exact add_le_add (finset.le_sup h₁) (finset.le_sup h₂) }, { assume a, refl }, { assume a b₁ b₂, refl } end lemma total_degree_pow (a : mv_polynomial σ R) (n : ℕ) : (a ^ n).total_degree ≤ n * a.total_degree := begin induction n with n ih, { simp only [nat.nat_zero_eq_zero, zero_mul, pow_zero, total_degree_one] }, rw pow_succ, calc total_degree (a * a ^ n) ≤ a.total_degree + (a^n).total_degree : total_degree_mul _ _ ... ≤ a.total_degree + n * a.total_degree : add_le_add_left ih _ ... = (n+1) * a.total_degree : by rw [add_mul, one_mul, add_comm] end @[simp] lemma total_degree_monomial (s : σ →₀ ℕ) {c : R} (hc : c ≠ 0) : (monomial s c : mv_polynomial σ R).total_degree = s.sum (λ _ e, e) := by simp [total_degree, support_monomial, if_neg hc] @[simp] lemma total_degree_X_pow [nontrivial R] (s : σ) (n : ℕ) : (X s ^ n : mv_polynomial σ R).total_degree = n := by simp [X_pow_eq_monomial, one_ne_zero] lemma total_degree_list_prod : ∀(s : list (mv_polynomial σ R)), s.prod.total_degree ≤ (s.map mv_polynomial.total_degree).sum | [] := by rw [@list.prod_nil (mv_polynomial σ R) _, total_degree_one]; refl | (p :: ps) := begin rw [@list.prod_cons (mv_polynomial σ R) _, list.map, list.sum_cons], exact le_trans (total_degree_mul _ _) (add_le_add_left (total_degree_list_prod ps) _) end lemma total_degree_multiset_prod (s : multiset (mv_polynomial σ R)) : s.prod.total_degree ≤ (s.map mv_polynomial.total_degree).sum := begin refine quotient.induction_on s (assume l, _), rw [multiset.quot_mk_to_coe, multiset.coe_prod, multiset.coe_map, multiset.coe_sum], exact total_degree_list_prod l end lemma total_degree_finset_prod {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) : (s.prod f).total_degree ≤ ∑ i in s, (f i).total_degree := begin refine le_trans (total_degree_multiset_prod _) _, rw [multiset.map_map], refl end lemma total_degree_finset_sum {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) : (s.sum f).total_degree ≤ finset.sup s (λ i, (f i).total_degree) := begin induction s using finset.cons_induction with a s has hind, { exact zero_le _ }, { rw [finset.sum_cons, finset.sup_cons, sup_eq_max], exact (mv_polynomial.total_degree_add _ _).trans (max_le_max le_rfl hind), } end lemma exists_degree_lt [fintype σ] (f : mv_polynomial σ R) (n : ℕ) (h : f.total_degree < n * fintype.card σ) {d : σ →₀ ℕ} (hd : d ∈ f.support) : ∃ i, d i < n := begin contrapose! h, calc n * fintype.card σ = ∑ s:σ, n : by rw [finset.sum_const, nat.nsmul_eq_mul, mul_comm, finset.card_univ] ... ≤ ∑ s, d s : finset.sum_le_sum (λ s _, h s) ... ≤ d.sum (λ i e, e) : by { rw [finsupp.sum_fintype], intros, refl } ... ≤ f.total_degree : finset.le_sup hd, end lemma coeff_eq_zero_of_total_degree_lt {f : mv_polynomial σ R} {d : σ →₀ ℕ} (h : f.total_degree < ∑ i in d.support, d i) : coeff d f = 0 := begin classical, rw [total_degree, finset.sup_lt_iff] at h, { specialize h d, rw mem_support_iff at h, refine not_not.mp (mt h _), exact lt_irrefl _, }, { exact lt_of_le_of_lt (nat.zero_le _) h, } end lemma total_degree_rename_le (f : σ → τ) (p : mv_polynomial σ R) : (rename f p).total_degree ≤ p.total_degree := finset.sup_le $ assume b, begin assume h, rw rename_eq at h, have h' := finsupp.map_domain_support h, rw finset.mem_image at h', rcases h' with ⟨s, hs, rfl⟩, rw finsupp.sum_map_domain_index, exact le_trans le_rfl (finset.le_sup hs), exact assume _, rfl, exact assume _ _ _, rfl end end total_degree section eval_vars /-! ### `vars` and `eval` -/ variables [comm_semiring S] lemma eval₂_hom_eq_constant_coeff_of_vars (f : R →+* S) {g : σ → S} {p : mv_polynomial σ R} (hp : ∀ i ∈ p.vars, g i = 0) : eval₂_hom f g p = f (constant_coeff p) := begin conv_lhs { rw p.as_sum }, simp only [ring_hom.map_sum, eval₂_hom_monomial], by_cases h0 : constant_coeff p = 0, work_on_goal 1 { rw [h0, f.map_zero, finset.sum_eq_zero], intros d hd }, work_on_goal 2 { rw [finset.sum_eq_single (0 : σ →₀ ℕ)], { rw [finsupp.prod_zero_index, mul_one], refl }, intros d hd hd0, }, repeat { obtain ⟨i, hi⟩ : d.support.nonempty, { rw [constant_coeff_eq, coeff, ← finsupp.not_mem_support_iff] at h0, rw [finset.nonempty_iff_ne_empty, ne.def, finsupp.support_eq_empty], rintro rfl, contradiction }, rw [finsupp.prod, finset.prod_eq_zero hi, mul_zero], rw [hp, zero_pow (nat.pos_of_ne_zero $ finsupp.mem_support_iff.mp hi)], rw [mem_vars], exact ⟨d, hd, hi⟩ }, { rw [constant_coeff_eq, coeff, ← ne.def, ← finsupp.mem_support_iff] at h0, intro, contradiction } end lemma aeval_eq_constant_coeff_of_vars [algebra R S] {g : σ → S} {p : mv_polynomial σ R} (hp : ∀ i ∈ p.vars, g i = 0) : aeval g p = algebra_map _ _ (constant_coeff p) := eval₂_hom_eq_constant_coeff_of_vars _ hp lemma eval₂_hom_congr' {f₁ f₂ : R →+* S} {g₁ g₂ : σ → S} {p₁ p₂ : mv_polynomial σ R} : f₁ = f₂ → (∀ i, i ∈ p₁.vars → i ∈ p₂.vars → g₁ i = g₂ i) → p₁ = p₂ → eval₂_hom f₁ g₁ p₁ = eval₂_hom f₂ g₂ p₂ := begin rintro rfl h rfl, rename [p₁ p, f₁ f], rw p.as_sum, simp only [ring_hom.map_sum, eval₂_hom_monomial], apply finset.sum_congr rfl, intros d hd, congr' 1, simp only [finsupp.prod], apply finset.prod_congr rfl, intros i hi, have : i ∈ p.vars, { rw mem_vars, exact ⟨d, hd, hi⟩ }, rw h i this this, end /-- If `f₁` and `f₂` are ring homs out of the polynomial ring and `p₁` and `p₂` are polynomials, then `f₁ p₁ = f₂ p₂` if `p₁ = p₂` and `f₁` and `f₂` are equal on `R` and on the variables of `p₁`. -/ lemma hom_congr_vars {f₁ f₂ : mv_polynomial σ R →+* S} {p₁ p₂ : mv_polynomial σ R} (hC : f₁.comp C = f₂.comp C) (hv : ∀ i, i ∈ p₁.vars → i ∈ p₂.vars → f₁ (X i) = f₂ (X i)) (hp : p₁ = p₂) : f₁ p₁ = f₂ p₂ := calc f₁ p₁ = eval₂_hom (f₁.comp C) (f₁ ∘ X) p₁ : ring_hom.congr_fun (by ext; simp) _ ... = eval₂_hom (f₂.comp C) (f₂ ∘ X) p₂ : eval₂_hom_congr' hC hv hp ... = f₂ p₂ : ring_hom.congr_fun (by ext; simp) _ lemma exists_rename_eq_of_vars_subset_range (p : mv_polynomial σ R) (f : τ → σ) (hfi : injective f) (hf : ↑p.vars ⊆ set.range f) : ∃ q : mv_polynomial τ R, rename f q = p := ⟨bind₁ (λ i : σ, option.elim 0 X $ partial_inv f i) p, begin show (rename f).to_ring_hom.comp _ p = ring_hom.id _ p, refine hom_congr_vars _ _ _, { ext1, simp [algebra_map_eq] }, { intros i hip _, rcases hf hip with ⟨i, rfl⟩, simp [partial_inv_left hfi] }, { refl } end⟩ lemma vars_bind₁ (f : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) : (bind₁ f φ).vars ⊆ φ.vars.bUnion (λ i, (f i).vars) := begin calc (bind₁ f φ).vars = (φ.support.sum (λ (x : σ →₀ ℕ), (bind₁ f) (monomial x (coeff x φ)))).vars : by { rw [← alg_hom.map_sum, ← φ.as_sum], } ... ≤ φ.support.bUnion (λ (i : σ →₀ ℕ), ((bind₁ f) (monomial i (coeff i φ))).vars) : vars_sum_subset _ _ ... = φ.support.bUnion (λ (d : σ →₀ ℕ), (C (coeff d φ) * ∏ i in d.support, f i ^ d i).vars) : by simp only [bind₁_monomial] ... ≤ φ.support.bUnion (λ (d : σ →₀ ℕ), d.support.bUnion (λ i, (f i).vars)) : _ -- proof below ... ≤ φ.vars.bUnion (λ (i : σ), (f i).vars) : _, -- proof below { apply finset.bUnion_mono, intros d hd, calc (C (coeff d φ) * ∏ (i : σ) in d.support, f i ^ d i).vars ≤ (C (coeff d φ)).vars ∪ (∏ (i : σ) in d.support, f i ^ d i).vars : vars_mul _ _ ... ≤ (∏ (i : σ) in d.support, f i ^ d i).vars : by simp only [finset.empty_union, vars_C, finset.le_iff_subset, finset.subset.refl] ... ≤ d.support.bUnion (λ (i : σ), (f i ^ d i).vars) : vars_prod _ ... ≤ d.support.bUnion (λ (i : σ), (f i).vars) : _, apply finset.bUnion_mono, intros i hi, apply vars_pow, }, { intro j, simp_rw finset.mem_bUnion, rintro ⟨d, hd, ⟨i, hi, hj⟩⟩, exact ⟨i, (mem_vars _).mpr ⟨d, hd, hi⟩, hj⟩ } end lemma mem_vars_bind₁ (f : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) {j : τ} (h : j ∈ (bind₁ f φ).vars) : ∃ (i : σ), i ∈ φ.vars ∧ j ∈ (f i).vars := by simpa only [exists_prop, finset.mem_bUnion, mem_support_iff, ne.def] using vars_bind₁ f φ h lemma vars_rename (f : σ → τ) (φ : mv_polynomial σ R) : (rename f φ).vars ⊆ (φ.vars.image f) := begin intros i hi, simp only [vars, exists_prop, multiset.mem_to_finset, finset.mem_image] at hi ⊢, simpa only [multiset.mem_map] using degrees_rename _ _ hi end lemma mem_vars_rename (f : σ → τ) (φ : mv_polynomial σ R) {j : τ} (h : j ∈ (rename f φ).vars) : ∃ (i : σ), i ∈ φ.vars ∧ f i = j := by simpa only [exists_prop, finset.mem_image] using vars_rename f φ h end eval_vars end comm_semiring end mv_polynomial
7f9c6b1b94b80d5dd601dceb1acd4aa89a1279f6
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/analysis/mean_inequalities.lean
78def7edeebfbb24008c679cab8a43ca22f18fda
[ "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
6,854
lean
/- Copyright (c) 2019 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.calculus.mean_value data.nat.parity analysis.complex.exponential analysis.convex.specific_functions /-! # Mean value inequalities In this file we prove various inequalities between mean values: arithmetic mean, geometric mean, generalized mean (natural and integer cases). For generalized means we only prove $\left( ∑_j w_j z_j \right)^n ≤ ∑_j w_j z_j^n$ because standard versions would require $\sqrt[n]{x}$ which is not implemented in `mathlib` yet. Probably a better approach to the generalized means inequality is to prove `convex_on_rpow` in `analysis/convex/specific_functions` first, then apply it. It is not yet clear which versions will be useful in the future, so we provide two different forms of most inequalities : for `ℝ` and for `ℝ≥0`. For the AM-GM inequality we also prove special cases for `n=2` and `n=3`. -/ universes u v open real finset open_locale classical nnreal variables {ι : Type u} (s : finset ι) /-- Geometric mean is less than or equal to the arithmetic mean, weighted version for functions on `finset`s. -/ theorem real.am_gm_weighted (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i) (hw' : s.sum w = 1) (hz : ∀ i ∈ s, 0 ≤ z i) : s.prod (λ i, (z i) ^ (w i)) ≤ s.sum (λ i, w i * z i) := begin let s' := s.filter (λ i, w i ≠ 0), rw [← sum_filter_ne_zero] at hw', suffices : s'.prod (λ i, (z i) ^ (w i)) ≤ s'.sum (λ i, w i * z i), { have A : ∀ i ∈ s, i ∉ s' → w i = 0, { intros i hi hi', simpa only [hi, mem_filter, ne.def, true_and, not_not] using hi' }, have B : ∀ i ∈ s, i ∉ s' → (z i) ^ (w i) = 1, from λ i hi hi', by rw [A i hi hi', rpow_zero], have C : ∀ i ∈ s, i ∉ s' → w i * z i = 0, from λ i hi hi', by rw [A i hi hi', zero_mul], rwa [← prod_subset s.filter_subset B, ← sum_subset s.filter_subset C] }, have A : ∀ i ∈ s', i ∈ s ∧ w i ≠ 0, from λ i hi, mem_filter.1 hi, replace hz : ∀ i ∈ s', 0 ≤ z i := λ i hi, hz i (A i hi).1, replace hw : ∀ i ∈ s', 0 ≤ w i := λ i hi, hw i (A i hi).1, by_cases B : ∃ i ∈ s', z i = 0, { rcases B with ⟨i, imem, hzi⟩, rw [prod_eq_zero imem], { exact sum_nonneg (λ j hj, mul_nonneg (hw j hj) (hz j hj)) }, { rw hzi, exact zero_rpow (A i imem).2 } }, { replace hz : ∀ i ∈ s', 0 < z i, from λ i hi, lt_of_le_of_ne (hz _ hi) (λ h, B ⟨i, hi, h.symm⟩), have := convex_on_exp.map_sum_le hw hw' (λ i _, set.mem_univ $ log (z i)), simp only [exp_sum, (∘), smul_eq_mul, mul_comm (w _) (log _)] at this, convert this using 1, { exact prod_congr rfl (λ i hi, rpow_def_of_pos (hz i hi) _) }, { exact sum_congr rfl (λ i hi, congr_arg _ (exp_log $ hz i hi).symm) } } end theorem nnreal.am_gm_weighted (w z : ι → ℝ≥0) (hw' : s.sum w = 1) : s.prod (λ i, (z i) ^ (w i:ℝ)) ≤ s.sum (λ i, w i * z i) := begin rw [← nnreal.coe_le_coe, nnreal.coe_prod, nnreal.coe_sum], refine real.am_gm_weighted _ _ _ (λ i _, (w i).coe_nonneg) _ (λ i _, (z i).coe_nonneg), assumption_mod_cast end theorem nnreal.am_gm2_weighted (w₁ w₂ p₁ p₂ : ℝ≥0) (hw : w₁ + w₂ = 1) : p₁ ^ (w₁:ℝ) * p₂ ^ (w₂:ℝ) ≤ w₁ * p₁ + w₂ * p₂ := begin have := nnreal.am_gm_weighted (univ : finset (fin 2)) (fin.cons w₁ $ fin.cons w₂ fin_zero_elim) (fin.cons p₁ $ fin.cons p₂ $ fin_zero_elim), simp only [fin.prod_univ_succ, fin.sum_univ_succ, fin.prod_univ_zero, fin.sum_univ_zero, fin.cons_succ, fin.cons_zero, add_zero, mul_one] at this, exact this hw end theorem real.am_gm2_weighted {w₁ w₂ p₁ p₂ : ℝ} (hw₁ : 0 ≤ w₁) (hw₂ : 0 ≤ w₂) (hp₁ : 0 ≤ p₁) (hp₂ : 0 ≤ p₂) (hw : w₁ + w₂ = 1) : p₁ ^ w₁ * p₂ ^ w₂ ≤ w₁ * p₁ + w₂ * p₂ := nnreal.am_gm2_weighted ⟨w₁, hw₁⟩ ⟨w₂, hw₂⟩ ⟨p₁, hp₁⟩ ⟨p₂, hp₂⟩ $ nnreal.coe_eq.1 $ by assumption theorem nnreal.am_gm3_weighted (w₁ w₂ w₃ p₁ p₂ p₃ : ℝ≥0) (hw : w₁ + w₂ + w₃ = 1) : p₁ ^ (w₁:ℝ) * p₂ ^ (w₂:ℝ) * p₃ ^ (w₃:ℝ) ≤ w₁ * p₁ + w₂ * p₂ + w₃ * p₃:= begin have := nnreal.am_gm_weighted (univ : finset (fin 3)) (fin.cons w₁ $ fin.cons w₂ $ fin.cons w₃ fin_zero_elim) (fin.cons p₁ $ fin.cons p₂ $ fin.cons p₃ fin_zero_elim), simp only [fin.prod_univ_succ, fin.sum_univ_succ, fin.prod_univ_zero, fin.sum_univ_zero, fin.cons_succ, fin.cons_zero, add_zero, mul_one, (add_assoc _ _ _).symm, (mul_assoc _ _ _).symm] at this, exact this hw end /-- Young's inequality, `ℝ≥0` version -/ theorem nnreal.young_inequality (a b : ℝ≥0) {p q : ℝ≥0} (hp : 1 < p) (hq : 1 < q) (hpq : 1/p + 1/q = 1) : a * b ≤ a^(p:ℝ) / p + b^(q:ℝ) / q := begin have := nnreal.am_gm2_weighted (1/p) (1/q) (a^(p:ℝ)) (b^(q:ℝ)) hpq, simp only [← nnreal.rpow_mul, one_div_eq_inv, nnreal.coe_div, nnreal.coe_one] at this, rw [mul_inv_cancel, mul_inv_cancel, nnreal.rpow_one, nnreal.rpow_one] at this, { ring at ⊢ this, convert this; { rw [nnreal.div_def, nnreal.div_def], ring } }, { exact ne_of_gt (lt_trans zero_lt_one hq) }, { exact ne_of_gt (lt_trans zero_lt_one hp) } end /-- Young's inequality, `ℝ` version -/ theorem real.young_inequality {a b : ℝ} (ha : 0 ≤ a) (hb : 0 ≤ b) {p q : ℝ} (hp : 1 < p) (hq : 1 < q) (hpq : 1/p + 1/q = 1) : a * b ≤ a^p / p + b^q / q := @nnreal.young_inequality ⟨a, ha⟩ ⟨b, hb⟩ ⟨p, le_trans zero_le_one (le_of_lt hp)⟩ ⟨q, le_trans zero_le_one (le_of_lt hq)⟩ hp hq (nnreal.coe_eq.1 hpq) theorem real.pow_am_le_am_pow (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i) (hw' : s.sum w = 1) (hz : ∀ i ∈ s, 0 ≤ z i) (n : ℕ) : (s.sum (λ i, w i * z i)) ^ n ≤ s.sum (λ i, w i * z i ^ n) := (convex_on_pow n).map_sum_le hw hw' hz theorem nnreal.pow_am_le_am_pow (w z : ι → ℝ≥0) (hw' : s.sum w = 1) (n : ℕ) : (s.sum (λ i, w i * z i)) ^ n ≤ s.sum (λ i, w i * z i ^ n) := begin rw [← nnreal.coe_le_coe], push_cast, refine (convex_on_pow n).map_sum_le (λ i _, (w i).coe_nonneg) _ (λ i _, (z i).coe_nonneg), assumption_mod_cast end theorem real.pow_am_le_am_pow_of_even (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i) (hw' : s.sum w = 1) {n : ℕ} (hn : n.even) : (s.sum (λ i, w i * z i)) ^ n ≤ s.sum (λ i, w i * z i ^ n) := (convex_on_pow_of_even hn).map_sum_le hw hw' (λ _ _, trivial) theorem real.fpow_am_le_am_fpow (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i) (hw' : s.sum w = 1) (hz : ∀ i ∈ s, 0 < z i) (m : ℤ) : (s.sum (λ i, w i * z i)) ^ m ≤ s.sum (λ i, w i * z i ^ m) := (convex_on_fpow m).map_sum_le hw hw' hz
0c43c748ae2ab4ed46230bc9fd0766527f2a1d94
ab1416f6fd6655094298e6c7bab1ac47d2533342
/samples/Lean/binary.lean
060a8cb0a7bc3f3aa51a9eb794a2112aedcbd20f
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
monkslc/hyperpolyglot
6ddc09e9d10d30bd8ce5c80a3bd755fa5714d621
a55a3b58eaed09b4314ef93d78e50a80cfec36f4
refs/heads/master
1,685,114,774,686
1,684,331,491,000
1,684,331,491,000
248,387,967
43
11
Apache-2.0
1,684,331,495,000
1,584,583,355,000
RenderScript
UTF-8
Lean
false
false
2,283
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: algebra.binary Authors: Leonardo de Moura, Jeremy Avigad General properties of binary operations. -/ import logic.eq open eq.ops namespace binary section variable {A : Type} variables (op₁ : A → A → A) (inv : A → A) (one : A) local notation a * b := op₁ a b local notation a ⁻¹ := inv a local notation 1 := one definition commutative := ∀a b, a * b = b * a definition associative := ∀a b c, (a * b) * c = a * (b * c) definition left_identity := ∀a, 1 * a = a definition right_identity := ∀a, a * 1 = a definition left_inverse := ∀a, a⁻¹ * a = 1 definition right_inverse := ∀a, a * a⁻¹ = 1 definition left_cancelative := ∀a b c, a * b = a * c → b = c definition right_cancelative := ∀a b c, a * b = c * b → a = c definition inv_op_cancel_left := ∀a b, a⁻¹ * (a * b) = b definition op_inv_cancel_left := ∀a b, a * (a⁻¹ * b) = b definition inv_op_cancel_right := ∀a b, a * b⁻¹ * b = a definition op_inv_cancel_right := ∀a b, a * b * b⁻¹ = a variable (op₂ : A → A → A) local notation a + b := op₂ a b definition left_distributive := ∀a b c, a * (b + c) = a * b + a * c definition right_distributive := ∀a b c, (a + b) * c = a * c + b * c end context variable {A : Type} variable {f : A → A → A} variable H_comm : commutative f variable H_assoc : associative f infixl `*` := f theorem left_comm : ∀a b c, a*(b*c) = b*(a*c) := take a b c, calc a*(b*c) = (a*b)*c : H_assoc ... = (b*a)*c : H_comm ... = b*(a*c) : H_assoc theorem right_comm : ∀a b c, (a*b)*c = (a*c)*b := take a b c, calc (a*b)*c = a*(b*c) : H_assoc ... = a*(c*b) : H_comm ... = (a*c)*b : H_assoc end context variable {A : Type} variable {f : A → A → A} variable H_assoc : associative f infixl `*` := f theorem assoc4helper (a b c d) : (a*b)*(c*d) = a*((b*c)*d) := calc (a*b)*(c*d) = a*(b*(c*d)) : H_assoc ... = a*((b*c)*d) : H_assoc end end binary
3d8e748ddf0d950086d1411a48b616fc7d10dad9
abd677583c7e4d55daf9487b82da11b7c5498d8d
/src/test.lean
8b02ed4e7e6cb1a4ad258d034617a313b23a882c
[ "Apache-2.0" ]
permissive
jesse-michael-han/embed
e9c346918ad58e03933bdaa057a571c0cc4a7641
c2fc188328e871e18e0dcb8258c6d0462c70a8c9
refs/heads/master
1,584,677,705,005
1,528,451,877,000
1,528,451,877,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
261
lean
import lia.cooper.main set_option pp.all true -- lemma foo [ordered_comm_group int] : false := sorry -- lemma bar : false := foo lemma foo : ∃ {a : int}, a = 5 := by cooper #exit ∀ x y, (x = y ↔ ∀ z, (x + z = y + z)), a + c ≠ b + c ⊢ a ≠ b
692ca0b05271ed6f3a87e8ffdd4a09b763f58bfa
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/polynomial/splits.lean
107a88897b602b4b20f72c38010303b5998dbda6
[ "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
16,920
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import data.list.prime import data.polynomial.field_division /-! # Split polynomials A polynomial `f : K[X]` splits over a field extension `L` of `K` if it is zero or all of its irreducible factors over `L` have degree `1`. ## Main definitions * `polynomial.splits i f`: A predicate on a homomorphism `i : K →+* L` from a commutative ring to a field and a polynomial `f` saying that `f.map i` is zero or all of its irreducible factors over `L` have degree `1`. ## Main statements * `lift_of_splits`: If `K` and `L` are field extensions of a field `F` and for some finite subset `S` of `K`, the minimal polynomial of every `x ∈ K` splits as a polynomial with coefficients in `L`, then `algebra.adjoin F S` embeds into `L`. -/ noncomputable theory open_locale classical big_operators polynomial universes u v w variables {F : Type u} {K : Type v} {L : Type w} namespace polynomial open polynomial section splits section comm_ring variables [comm_ring K] [field L] [field F] variables (i : K →+* L) /-- A polynomial `splits` iff it is zero or all of its irreducible factors have `degree` 1. -/ def splits (f : K[X]) : Prop := f.map i = 0 ∨ ∀ {g : L[X]}, irreducible g → g ∣ f.map i → degree g = 1 @[simp] lemma splits_zero : splits i (0 : K[X]) := or.inl (polynomial.map_zero i) lemma splits_of_map_eq_C {f : K[X]} {a : L} (h : f.map i = C a) : splits i f := if ha : a = 0 then or.inl (h.trans (ha.symm ▸ C_0)) else or.inr $ λ g hg ⟨p, hp⟩, absurd hg.1 $ not_not.2 $ is_unit_iff_degree_eq_zero.2 $ begin have := congr_arg degree hp, rw [h, degree_C ha, degree_mul, @eq_comm (with_bot ℕ) 0, nat.with_bot.add_eq_zero_iff] at this, exact this.1, end @[simp] lemma splits_C (a : K) : splits i (C a) := splits_of_map_eq_C i (map_C i) lemma splits_of_map_degree_eq_one {f : K[X]} (hf : degree (f.map i) = 1) : splits i f := or.inr $ λ g hg ⟨p, hp⟩, by have := congr_arg degree hp; simp [nat.with_bot.add_eq_one_iff, hf, @eq_comm (with_bot ℕ) 1, mt is_unit_iff_degree_eq_zero.2 hg.1] at this; clear _fun_match; tauto lemma splits_of_degree_le_one {f : K[X]} (hf : degree f ≤ 1) : splits i f := if hif : degree (f.map i) ≤ 0 then splits_of_map_eq_C i (degree_le_zero_iff.mp hif) else begin push_neg at hif, rw [← order.succ_le_iff, ← with_bot.coe_zero, with_bot.succ_coe, nat.succ_eq_succ] at hif, exact splits_of_map_degree_eq_one i (le_antisymm ((degree_map_le i _).trans hf) hif), end lemma splits_of_degree_eq_one {f : K[X]} (hf : degree f = 1) : splits i f := splits_of_degree_le_one i hf.le lemma splits_of_nat_degree_le_one {f : K[X]} (hf : nat_degree f ≤ 1) : splits i f := splits_of_degree_le_one i (degree_le_of_nat_degree_le hf) lemma splits_of_nat_degree_eq_one {f : K[X]} (hf : nat_degree f = 1) : splits i f := splits_of_nat_degree_le_one i (le_of_eq hf) lemma splits_mul {f g : K[X]} (hf : splits i f) (hg : splits i g) : splits i (f * g) := if h : (f * g).map i = 0 then or.inl h else or.inr $ λ p hp hpf, ((principal_ideal_ring.irreducible_iff_prime.1 hp).2.2 _ _ (show p ∣ map i f * map i g, by convert hpf; rw polynomial.map_mul)).elim (hf.resolve_left (λ hf, by simpa [hf] using h) hp) (hg.resolve_left (λ hg, by simpa [hg] using h) hp) lemma splits_of_splits_mul' {f g : K[X]} (hfg : (f * g).map i ≠ 0) (h : splits i (f * g)) : splits i f ∧ splits i g := ⟨or.inr $ λ g hgi hg, or.resolve_left h hfg hgi (by rw polynomial.map_mul; exact hg.trans (dvd_mul_right _ _)), or.inr $ λ g hgi hg, or.resolve_left h hfg hgi (by rw polynomial.map_mul; exact hg.trans (dvd_mul_left _ _))⟩ lemma splits_map_iff (j : L →+* F) {f : K[X]} : splits j (f.map i) ↔ splits (j.comp i) f := by simp [splits, polynomial.map_map] theorem splits_one : splits i 1 := splits_C i 1 theorem splits_of_is_unit [is_domain K] {u : K[X]} (hu : is_unit u) : u.splits i := (is_unit_iff.mp hu).some_spec.2 ▸ splits_C _ _ theorem splits_X_sub_C {x : K} : (X - C x).splits i := splits_of_degree_le_one _ $ degree_X_sub_C_le _ theorem splits_X : X.splits i := splits_of_degree_le_one _ degree_X_le theorem splits_prod {ι : Type u} {s : ι → K[X]} {t : finset ι} : (∀ j ∈ t, (s j).splits i) → (∏ x in t, s x).splits i := begin refine finset.induction_on t (λ _, splits_one i) (λ a t hat ih ht, _), rw finset.forall_mem_insert at ht, rw finset.prod_insert hat, exact splits_mul i ht.1 (ih ht.2) end lemma splits_pow {f : K[X]} (hf : f.splits i) (n : ℕ) : (f ^ n).splits i := begin rw [←finset.card_range n, ←finset.prod_const], exact splits_prod i (λ j hj, hf), end lemma splits_X_pow (n : ℕ) : (X ^ n).splits i := splits_pow i (splits_X i) n theorem splits_id_iff_splits {f : K[X]} : (f.map i).splits (ring_hom.id L) ↔ f.splits i := by rw [splits_map_iff, ring_hom.id_comp] lemma exists_root_of_splits' {f : K[X]} (hs : splits i f) (hf0 : degree (f.map i) ≠ 0) : ∃ x, eval₂ i x f = 0 := if hf0' : f.map i = 0 then by simp [eval₂_eq_eval_map, hf0'] else let ⟨g, hg⟩ := wf_dvd_monoid.exists_irreducible_factor (show ¬ is_unit (f.map i), from mt is_unit_iff_degree_eq_zero.1 hf0) hf0' in let ⟨x, hx⟩ := exists_root_of_degree_eq_one (hs.resolve_left hf0' hg.1 hg.2) in let ⟨i, hi⟩ := hg.2 in ⟨x, by rw [← eval_map, hi, eval_mul, show _ = _, from hx, zero_mul]⟩ lemma roots_ne_zero_of_splits' {f : K[X]} (hs : splits i f) (hf0 : nat_degree (f.map i) ≠ 0) : (f.map i).roots ≠ 0 := let ⟨x, hx⟩ := exists_root_of_splits' i hs (λ h, hf0 $ nat_degree_eq_of_degree_eq_some h) in λ h, by { rw ← eval_map at hx, cases h.subst ((mem_roots _).2 hx), exact ne_zero_of_nat_degree_gt (nat.pos_of_ne_zero hf0) } /-- Pick a root of a polynomial that splits. See `root_of_splits` for polynomials over a field which has simpler assumptions. -/ def root_of_splits' {f : K[X]} (hf : f.splits i) (hfd : (f.map i).degree ≠ 0) : L := classical.some $ exists_root_of_splits' i hf hfd theorem map_root_of_splits' {f : K[X]} (hf : f.splits i) (hfd) : f.eval₂ i (root_of_splits' i hf hfd) = 0 := classical.some_spec $ exists_root_of_splits' i hf hfd lemma nat_degree_eq_card_roots' {p : K[X]} {i : K →+* L} (hsplit : splits i p) : (p.map i).nat_degree = (p.map i).roots.card := begin by_cases hp : p.map i = 0, { rw [hp, nat_degree_zero, roots_zero, multiset.card_zero] }, obtain ⟨q, he, hd, hr⟩ := exists_prod_multiset_X_sub_C_mul (p.map i), rw [← splits_id_iff_splits, ← he] at hsplit, rw ← he at hp, have hq : q ≠ 0 := λ h, hp (by rw [h, mul_zero]), rw [← hd, add_right_eq_self], by_contra, have h' : (map (ring_hom.id L) q).nat_degree ≠ 0, { simp [h], }, have := roots_ne_zero_of_splits' (ring_hom.id L) (splits_of_splits_mul' _ _ hsplit).2 h', { rw map_id at this, exact this hr }, { rw [map_id], exact mul_ne_zero monic_prod_multiset_X_sub_C.ne_zero hq }, end lemma degree_eq_card_roots' {p : K[X]} {i : K →+* L} (p_ne_zero : p.map i ≠ 0) (hsplit : splits i p) : (p.map i).degree = (p.map i).roots.card := by rw [degree_eq_nat_degree p_ne_zero, nat_degree_eq_card_roots' hsplit] end comm_ring variables [field K] [field L] [field F] variables (i : K →+* L) /-- This lemma is for polynomials over a field. -/ lemma splits_iff (f : K[X]) : splits i f ↔ f = 0 ∨ ∀ {g : L[X]}, irreducible g → g ∣ f.map i → degree g = 1 := by rw [splits, map_eq_zero] /-- This lemma is for polynomials over a field. -/ lemma splits.def {i : K →+* L} {f : K[X]} (h : splits i f) : f = 0 ∨ ∀ {g : L[X]}, irreducible g → g ∣ f.map i → degree g = 1 := (splits_iff i f).mp h lemma splits_of_splits_mul {f g : K[X]} (hfg : f * g ≠ 0) (h : splits i (f * g)) : splits i f ∧ splits i g := splits_of_splits_mul' i (map_ne_zero hfg) h lemma splits_of_splits_of_dvd {f g : K[X]} (hf0 : f ≠ 0) (hf : splits i f) (hgf : g ∣ f) : splits i g := by { obtain ⟨f, rfl⟩ := hgf, exact (splits_of_splits_mul i hf0 hf).1 } lemma splits_of_splits_gcd_left {f g : K[X]} (hf0 : f ≠ 0) (hf : splits i f) : splits i (euclidean_domain.gcd f g) := polynomial.splits_of_splits_of_dvd i hf0 hf (euclidean_domain.gcd_dvd_left f g) lemma splits_of_splits_gcd_right {f g : K[X]} (hg0 : g ≠ 0) (hg : splits i g) : splits i (euclidean_domain.gcd f g) := polynomial.splits_of_splits_of_dvd i hg0 hg (euclidean_domain.gcd_dvd_right f g) theorem splits_mul_iff {f g : K[X]} (hf : f ≠ 0) (hg : g ≠ 0) : (f * g).splits i ↔ f.splits i ∧ g.splits i := ⟨splits_of_splits_mul i (mul_ne_zero hf hg), λ ⟨hfs, hgs⟩, splits_mul i hfs hgs⟩ theorem splits_prod_iff {ι : Type u} {s : ι → K[X]} {t : finset ι} : (∀ j ∈ t, s j ≠ 0) → ((∏ x in t, s x).splits i ↔ ∀ j ∈ t, (s j).splits i) := begin refine finset.induction_on t (λ _, ⟨λ _ _ h, h.elim, λ _, splits_one i⟩) (λ a t hat ih ht, _), rw finset.forall_mem_insert at ht ⊢, rw [finset.prod_insert hat, splits_mul_iff i ht.1 (finset.prod_ne_zero_iff.2 ht.2), ih ht.2] end lemma degree_eq_one_of_irreducible_of_splits {p : K[X]} (hp : irreducible p) (hp_splits : splits (ring_hom.id K) p) : p.degree = 1 := begin rcases hp_splits, { exfalso, simp * at *, }, { apply hp_splits hp, simp } end lemma exists_root_of_splits {f : K[X]} (hs : splits i f) (hf0 : degree f ≠ 0) : ∃ x, eval₂ i x f = 0 := exists_root_of_splits' i hs ((f.degree_map i).symm ▸ hf0) lemma roots_ne_zero_of_splits {f : K[X]} (hs : splits i f) (hf0 : nat_degree f ≠ 0) : (f.map i).roots ≠ 0 := roots_ne_zero_of_splits' i hs (ne_of_eq_of_ne (nat_degree_map i) hf0) /-- Pick a root of a polynomial that splits. This version is for polynomials over a field and has simpler assumptions. -/ def root_of_splits {f : K[X]} (hf : f.splits i) (hfd : f.degree ≠ 0) : L := root_of_splits' i hf ((f.degree_map i).symm ▸ hfd) /-- `root_of_splits'` is definitionally equal to `root_of_splits`. -/ lemma root_of_splits'_eq_root_of_splits {f : K[X]} (hf : f.splits i) (hfd) : root_of_splits' i hf hfd = root_of_splits i hf (f.degree_map i ▸ hfd) := rfl theorem map_root_of_splits {f : K[X]} (hf : f.splits i) (hfd) : f.eval₂ i (root_of_splits i hf hfd) = 0 := map_root_of_splits' i hf (ne_of_eq_of_ne (degree_map f i) hfd) lemma nat_degree_eq_card_roots {p : K[X]} {i : K →+* L} (hsplit : splits i p) : p.nat_degree = (p.map i).roots.card := (nat_degree_map i).symm.trans $ nat_degree_eq_card_roots' hsplit lemma degree_eq_card_roots {p : K[X]} {i : K →+* L} (p_ne_zero : p ≠ 0) (hsplit : splits i p) : p.degree = (p.map i).roots.card := by rw [degree_eq_nat_degree p_ne_zero, nat_degree_eq_card_roots hsplit] theorem roots_map {f : K[X]} (hf : f.splits $ ring_hom.id K) : (f.map i).roots = f.roots.map i := (roots_map_of_injective_of_card_eq_nat_degree i.injective $ by { convert (nat_degree_eq_card_roots hf).symm, rw map_id }).symm lemma image_root_set [algebra F K] [algebra F L] {p : F[X]} (h : p.splits (algebra_map F K)) (f : K →ₐ[F] L) : f '' p.root_set K = p.root_set L := begin classical, rw [root_set, ←finset.coe_image, ←multiset.to_finset_map, ←f.coe_to_ring_hom, ←roots_map ↑f ((splits_id_iff_splits (algebra_map F K)).mpr h), map_map, f.comp_algebra_map, ←root_set], end lemma adjoin_root_set_eq_range [algebra F K] [algebra F L] {p : F[X]} (h : p.splits (algebra_map F K)) (f : K →ₐ[F] L) : algebra.adjoin F (p.root_set L) = f.range ↔ algebra.adjoin F (p.root_set K) = ⊤ := begin rw [←image_root_set h f, algebra.adjoin_image, ←algebra.map_top], exact (subalgebra.map_injective f.to_ring_hom.injective).eq_iff, end lemma eq_prod_roots_of_splits {p : K[X]} {i : K →+* L} (hsplit : splits i p) : p.map i = C (i p.leading_coeff) * ((p.map i).roots.map (λ a, X - C a)).prod := begin rw ← leading_coeff_map, symmetry, apply C_leading_coeff_mul_prod_multiset_X_sub_C, rw nat_degree_map, exact (nat_degree_eq_card_roots hsplit).symm, end lemma eq_prod_roots_of_splits_id {p : K[X]} (hsplit : splits (ring_hom.id K) p) : p = C p.leading_coeff * (p.roots.map (λ a, X - C a)).prod := by simpa using eq_prod_roots_of_splits hsplit lemma eq_prod_roots_of_monic_of_splits_id {p : K[X]} (m : monic p) (hsplit : splits (ring_hom.id K) p) : p = (p.roots.map (λ a, X - C a)).prod := begin convert eq_prod_roots_of_splits_id hsplit, simp [m], end lemma eq_X_sub_C_of_splits_of_single_root {x : K} {h : K[X]} (h_splits : splits i h) (h_roots : (h.map i).roots = {i x}) : h = C h.leading_coeff * (X - C x) := begin apply polynomial.map_injective _ i.injective, rw [eq_prod_roots_of_splits h_splits, h_roots], simp, end section UFD local attribute [instance, priority 10] principal_ideal_ring.to_unique_factorization_monoid local infix ` ~ᵤ ` : 50 := associated open unique_factorization_monoid associates lemma splits_of_exists_multiset {f : K[X]} {s : multiset L} (hs : f.map i = C (i f.leading_coeff) * (s.map (λ a : L, X - C a)).prod) : splits i f := if hf0 : f = 0 then hf0.symm ▸ splits_zero i else or.inr $ λ p hp hdp, begin rw irreducible_iff_prime at hp, rw [hs, ← multiset.prod_to_list] at hdp, obtain (hd|hd) := hp.2.2 _ _ hdp, { refine (hp.2.1 $ is_unit_of_dvd_unit hd _).elim, exact is_unit_C.2 ((leading_coeff_ne_zero.2 hf0).is_unit.map i) }, { obtain ⟨q, hq, hd⟩ := hp.dvd_prod_iff.1 hd, obtain ⟨a, ha, rfl⟩ := multiset.mem_map.1 (multiset.mem_to_list.1 hq), rw degree_eq_degree_of_associated ((hp.dvd_prime_iff_associated $ prime_X_sub_C a).1 hd), exact degree_X_sub_C a }, end lemma splits_of_splits_id {f : K[X]} : splits (ring_hom.id K) f → splits i f := unique_factorization_monoid.induction_on_prime f (λ _, splits_zero _) (λ _ hu _, splits_of_degree_le_one _ ((is_unit_iff_degree_eq_zero.1 hu).symm ▸ dec_trivial)) (λ a p ha0 hp ih hfi, splits_mul _ (splits_of_degree_eq_one _ ((splits_of_splits_mul _ (mul_ne_zero hp.1 ha0) hfi).1.def.resolve_left hp.1 hp.irreducible (by rw map_id))) (ih (splits_of_splits_mul _ (mul_ne_zero hp.1 ha0) hfi).2)) end UFD lemma splits_iff_exists_multiset {f : K[X]} : splits i f ↔ ∃ (s : multiset L), f.map i = C (i f.leading_coeff) * (s.map (λ a : L, X - C a)).prod := ⟨λ hf, ⟨(f.map i).roots, eq_prod_roots_of_splits hf⟩, λ ⟨s, hs⟩, splits_of_exists_multiset i hs⟩ lemma splits_comp_of_splits (j : L →+* F) {f : K[X]} (h : splits i f) : splits (j.comp i) f := begin change i with ((ring_hom.id _).comp i) at h, rw [← splits_map_iff], rw [← splits_map_iff i] at h, exact splits_of_splits_id _ h end /-- A polynomial splits if and only if it has as many roots as its degree. -/ lemma splits_iff_card_roots {p : K[X]} : splits (ring_hom.id K) p ↔ p.roots.card = p.nat_degree := begin split, { intro H, rw [nat_degree_eq_card_roots H, map_id] }, { intro hroots, rw splits_iff_exists_multiset (ring_hom.id K), use p.roots, simp only [ring_hom.id_apply, map_id], exact (C_leading_coeff_mul_prod_multiset_X_sub_C hroots).symm }, end lemma aeval_root_derivative_of_splits [algebra K L] {P : K[X]} (hmo : P.monic) (hP : P.splits (algebra_map K L)) {r : L} (hr : r ∈ (P.map (algebra_map K L)).roots) : aeval r P.derivative = (((P.map $ algebra_map K L).roots.erase r).map (λ a, r - a)).prod := begin replace hmo := hmo.map (algebra_map K L), replace hP := (splits_id_iff_splits (algebra_map K L)).2 hP, rw [aeval_def, ← eval_map, ← derivative_map], nth_rewrite 0 [eq_prod_roots_of_monic_of_splits_id hmo hP], rw [eval_multiset_prod_X_sub_C_derivative hr] end /-- If `P` is a monic polynomial that splits, then `coeff P 0` equals the product of the roots. -/ lemma prod_roots_eq_coeff_zero_of_monic_of_split {P : K[X]} (hmo : P.monic) (hP : P.splits (ring_hom.id K)) : coeff P 0 = (-1) ^ P.nat_degree * P.roots.prod := begin nth_rewrite 0 [eq_prod_roots_of_monic_of_splits_id hmo hP], rw [coeff_zero_eq_eval_zero, eval_multiset_prod, multiset.map_map], simp_rw [function.comp_app, eval_sub, eval_X, zero_sub, eval_C], conv_lhs { congr, congr, funext, rw [neg_eq_neg_one_mul] }, rw [multiset.prod_map_mul, multiset.map_const, multiset.prod_repeat, multiset.map_id', splits_iff_card_roots.1 hP] end /-- If `P` is a monic polynomial that splits, then `P.next_coeff` equals the sum of the roots. -/ lemma sum_roots_eq_next_coeff_of_monic_of_split {P : K[X]} (hmo : P.monic) (hP : P.splits (ring_hom.id K)) : P.next_coeff = - P.roots.sum := begin nth_rewrite 0 [eq_prod_roots_of_monic_of_splits_id hmo hP], rw [monic.next_coeff_multiset_prod _ _ (λ a ha, _)], { simp_rw [next_coeff_X_sub_C, multiset.sum_map_neg'] }, { exact monic_X_sub_C a } end end splits end polynomial
f2f454d37401444c625f396450d3134f3205b18a
9028d228ac200bbefe3a711342514dd4e4458bff
/src/category_theory/yoneda.lean
f1c71e429a10b7407b5644372d277ca0b6503ab9
[ "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
8,196
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.hom_functor /-! # The Yoneda embedding The Yoneda embedding as a functor `yoneda : C ⥤ (Cᵒᵖ ⥤ Type v₁)`, along with an instance that it is `fully_faithful`. Also the Yoneda lemma, `yoneda_lemma : (yoneda_pairing C) ≅ (yoneda_evaluation C)`. ## References * [Stacks: Opposite Categories and the Yoneda Lemma](https://stacks.math.columbia.edu/tag/001L) -/ namespace category_theory open opposite universes v₁ u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation variables {C : Type u₁} [category.{v₁} C] /-- The Yoneda embedding, as a functor from `C` into presheaves on `C`. See https://stacks.math.columbia.edu/tag/001O. -/ @[simps] def yoneda : C ⥤ (Cᵒᵖ ⥤ Type v₁) := { obj := λ X, { obj := λ Y, unop Y ⟶ X, map := λ Y Y' f g, f.unop ≫ g, map_comp' := λ _ _ _ f g, begin ext, dsimp, erw [category.assoc] end, map_id' := λ Y, begin ext, dsimp, erw [category.id_comp] end }, map := λ X X' f, { app := λ Y g, g ≫ f } } /-- The co-Yoneda embedding, as a functor from `Cᵒᵖ` into co-presheaves on `C`. -/ @[simps] def coyoneda : Cᵒᵖ ⥤ (C ⥤ Type v₁) := { obj := λ X, { obj := λ Y, unop X ⟶ Y, map := λ Y Y' f g, g ≫ f, map_comp' := λ _ _ _ f g, begin ext1, dsimp, erw [category.assoc] end, map_id' := λ Y, begin ext1, dsimp, erw [category.comp_id] end }, map := λ X X' f, { app := λ Y g, f.unop ≫ g }, map_comp' := λ _ _ _ f g, begin ext, dsimp, erw [category.assoc] end, map_id' := λ X, begin ext, dsimp, erw [category.id_comp] end } namespace yoneda lemma obj_map_id {X Y : C} (f : op X ⟶ op Y) : ((@yoneda C _).obj X).map f (𝟙 X) = ((@yoneda C _).map f.unop).app (op Y) (𝟙 Y) := by obviously @[simp] lemma naturality {X Y : C} (α : yoneda.obj X ⟶ yoneda.obj Y) {Z Z' : C} (f : Z ⟶ Z') (h : Z' ⟶ X) : f ≫ α.app (op Z') h = α.app (op Z) (f ≫ h) := (functor_to_types.naturality _ _ α f.op h).symm /-- The Yoneda embedding is full. See https://stacks.math.columbia.edu/tag/001P. -/ instance yoneda_full : full (@yoneda C _) := { preimage := λ X Y f, (f.app (op X)) (𝟙 X) } /-- The Yoneda embedding is faithful. See https://stacks.math.columbia.edu/tag/001P. -/ instance yoneda_faithful : faithful (@yoneda C _) := { map_injective' := λ X Y f g p, begin injection p with h, convert (congr_fun (congr_fun h (op X)) (𝟙 X)); dsimp; simp, end } /-- Extensionality via Yoneda. The typical usage would be ``` -- Goal is `X ≅ Y` apply yoneda.ext, -- Goals are now functions `(Z ⟶ X) → (Z ⟶ Y)`, `(Z ⟶ Y) → (Z ⟶ X)`, and the fact that these functions are inverses and natural in `Z`. ``` -/ def ext (X Y : C) (p : Π {Z : C}, (Z ⟶ X) → (Z ⟶ Y)) (q : Π {Z : C}, (Z ⟶ Y) → (Z ⟶ X)) (h₁ : Π {Z : C} (f : Z ⟶ X), q (p f) = f) (h₂ : Π {Z : C} (f : Z ⟶ Y), p (q f) = f) (n : Π {Z Z' : C} (f : Z' ⟶ Z) (g : Z ⟶ X), p (f ≫ g) = f ≫ p g) : X ≅ Y := @preimage_iso _ _ _ _ yoneda _ _ _ _ (nat_iso.of_components (λ Z, { hom := p, inv := q, }) (by tidy)) /-- If `yoneda.map f` is an isomorphism, so was `f`. -/ def is_iso {X Y : C} (f : X ⟶ Y) [is_iso (yoneda.map f)] : is_iso f := is_iso_of_fully_faithful yoneda f end yoneda namespace coyoneda @[simp] lemma naturality {X Y : Cᵒᵖ} (α : coyoneda.obj X ⟶ coyoneda.obj Y) {Z Z' : C} (f : Z' ⟶ Z) (h : unop X ⟶ Z') : (α.app Z' h) ≫ f = α.app Z (h ≫ f) := begin erw [functor_to_types.naturality], refl end instance coyoneda_full : full (@coyoneda C _) := { preimage := λ X Y f, ((f.app (unop X)) (𝟙 _)).op } instance coyoneda_faithful : faithful (@coyoneda C _) := { map_injective' := λ X Y f g p, begin injection p with h, have t := (congr_fun (congr_fun h (unop X)) (𝟙 _)), simpa using congr_arg has_hom.hom.op t, end } /-- If `coyoneda.map f` is an isomorphism, so was `f`. -/ def is_iso {X Y : Cᵒᵖ} (f : X ⟶ Y) [is_iso (coyoneda.map f)] : is_iso f := is_iso_of_fully_faithful coyoneda f end coyoneda /-- A presheaf `F` is representable if there is object `X` so `F ≅ yoneda.obj X`. See https://stacks.math.columbia.edu/tag/001Q. -/ -- TODO should we make this a Prop, merely asserting existence of such an object? class representable (F : Cᵒᵖ ⥤ Type v₁) := (X : C) (w : yoneda.obj X ≅ F) end category_theory namespace category_theory -- For the rest of the file, we are using product categories, -- so need to restrict to the case morphisms are in 'Type', not 'Sort'. universes v₁ u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation open opposite variables (C : Type u₁) [category.{v₁} C] -- We need to help typeclass inference with some awkward universe levels here. instance prod_category_instance_1 : category ((Cᵒᵖ ⥤ Type v₁) × Cᵒᵖ) := category_theory.prod.{(max u₁ v₁) v₁} (Cᵒᵖ ⥤ Type v₁) Cᵒᵖ instance prod_category_instance_2 : category (Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁)) := category_theory.prod.{v₁ (max u₁ v₁)} Cᵒᵖ (Cᵒᵖ ⥤ Type v₁) open yoneda /-- The "Yoneda evaluation" functor, which sends `X : Cᵒᵖ` and `F : Cᵒᵖ ⥤ Type` to `F.obj X`, functorially in both `X` and `F`. -/ def yoneda_evaluation : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁) ⥤ Type (max u₁ v₁) := evaluation_uncurried Cᵒᵖ (Type v₁) ⋙ ulift_functor.{u₁} @[simp] lemma yoneda_evaluation_map_down (P Q : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁)) (α : P ⟶ Q) (x : (yoneda_evaluation C).obj P) : ((yoneda_evaluation C).map α x).down = α.2.app Q.1 (P.2.map α.1 x.down) := rfl /-- The "Yoneda pairing" functor, which sends `X : Cᵒᵖ` and `F : Cᵒᵖ ⥤ Type` to `yoneda.op.obj X ⟶ F`, functorially in both `X` and `F`. -/ def yoneda_pairing : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁) ⥤ Type (max u₁ v₁) := functor.prod yoneda.op (𝟭 (Cᵒᵖ ⥤ Type v₁)) ⋙ functor.hom (Cᵒᵖ ⥤ Type v₁) @[simp] lemma yoneda_pairing_map (P Q : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁)) (α : P ⟶ Q) (β : (yoneda_pairing C).obj P) : (yoneda_pairing C).map α β = yoneda.map α.1.unop ≫ β ≫ α.2 := rfl /-- The Yoneda lemma asserts that that the Yoneda pairing `(X : Cᵒᵖ, F : Cᵒᵖ ⥤ Type) ↦ (yoneda.obj (unop X) ⟶ F)` is naturally isomorphic to the evaluation `(X, F) ↦ F.obj X`. See https://stacks.math.columbia.edu/tag/001P. -/ def yoneda_lemma : yoneda_pairing C ≅ yoneda_evaluation C := { hom := { app := λ F x, ulift.up ((x.app F.1) (𝟙 (unop F.1))), naturality' := begin intros X Y f, ext, dsimp, erw [category.id_comp, ←functor_to_types.naturality], simp only [category.comp_id, yoneda_obj_map], end }, inv := { app := λ F x, { app := λ X a, (F.2.map a.op) x.down, naturality' := begin intros X Y f, ext, dsimp, rw [functor_to_types.map_comp_apply] end }, naturality' := begin intros X Y f, ext, dsimp, rw [←functor_to_types.naturality, functor_to_types.map_comp_apply] end }, hom_inv_id' := begin ext, dsimp, erw [←functor_to_types.naturality, obj_map_id], simp only [yoneda_map_app, has_hom.hom.unop_op], erw [category.id_comp], end, inv_hom_id' := begin ext, dsimp, rw [functor_to_types.map_id_apply] end }. variables {C} /-- The isomorphism between `yoneda.obj X ⟶ F` and `F.obj (op X)` (we need to insert a `ulift` to get the universes right!) given by the Yoneda lemma. -/ @[simp] def yoneda_sections (X : C) (F : Cᵒᵖ ⥤ Type v₁) : (yoneda.obj X ⟶ F) ≅ ulift.{u₁} (F.obj (op X)) := (yoneda_lemma C).app (op X, F) /-- When `C` is a small category, we can restate the isomorphism from `yoneda_sections` without having to change universes. -/ @[simp] def yoneda_sections_small {C : Type u₁} [small_category C] (X : C) (F : Cᵒᵖ ⥤ Type u₁) : (yoneda.obj X ⟶ F) ≅ F.obj (op X) := yoneda_sections X F ≪≫ ulift_trivial _ end category_theory
385b3fb764ebde85e5d646141a83ae5cbcb30b7f
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/algebra/big_operators/finprod.lean
f585d97825b2306f9ca6142e4aac26ff1cb47fac
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
38,376
lean
/- Copyright (c) 2020 Kexing Ying and Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying, Kevin Buzzard, Yury Kudryashov -/ import algebra.big_operators.order import algebra.indicator_function import data.set.pairwise /-! # Finite products and sums over types and sets We define products and sums over types and subsets of types, with no finiteness hypotheses. All infinite products and sums are defined to be junk values (i.e. one or zero). This approach is sometimes easier to use than `finset.sum`, when issues arise with `finset` and `fintype` being data. ## Main definitions We use the following variables: * `α`, `β` - types with no structure; * `s`, `t` - sets * `M`, `N` - additive or multiplicative commutative monoids * `f`, `g` - functions Definitions in this file: * `finsum f : M` : the sum of `f x` as `x` ranges over the support of `f`, if it's finite. Zero otherwise. * `finprod f : M` : the product of `f x` as `x` ranges over the multiplicative support of `f`, if it's finite. One otherwise. ## Notation * `∑ᶠ i, f i` and `∑ᶠ i : α, f i` for `finsum f` * `∏ᶠ i, f i` and `∏ᶠ i : α, f i` for `finprod f` This notation works for functions `f : p → M`, where `p : Prop`, so the following works: * `∑ᶠ i ∈ s, f i`, where `f : α → M`, `s : set α` : sum over the set `s`; * `∑ᶠ n < 5, f n`, where `f : ℕ → M` : same as `f 0 + f 1 + f 2 + f 3 + f 4`; * `∏ᶠ (n >= -2) (hn : n < 3), f n`, where `f : ℤ → M` : same as `f (-2) * f (-1) * f 0 * f 1 * f 2`. ## Implementation notes `finsum` and `finprod` is "yet another way of doing finite sums and products in Lean". However experiments in the wild (e.g. with matroids) indicate that it is a helpful approach in settings where the user is not interested in computability and wants to do reasoning without running into typeclass diamonds caused by the constructive finiteness used in definitions such as `finset` and `fintype`. By sticking solely to `set.finite` we avoid these problems. We are aware that there are other solutions but for beginner mathematicians this approach is easier in practice. Another application is the construction of a partition of unity from a collection of “bump” function. In this case the finite set depends on the point and it's convenient to have a definition that does not mention the set explicitly. The first arguments in all definitions and lemmas is the codomain of the function of the big operator. This is necessary for the heuristic in `@[to_additive]`. See the documentation of `to_additive.attr` for more information. ## Todo We did not add `is_finite (X : Type) : Prop`, because it is simply `nonempty (fintype X)`. There is work on `fincard` in the pipeline, which returns the cardinality of `X` if it is finite, and 0 otherwise. ## Tags finsum, finprod, finite sum, finite product -/ open function set /-! ### Definition and relation to `finset.sum` and `finset.prod` -/ section sort variables {M N : Type*} {α β ι : Sort*} [comm_monoid M] [comm_monoid N] open_locale big_operators section /- Note: we use classical logic only for these definitions, to ensure that we do not write lemmas with `classical.dec` in their statement. -/ open_locale classical /-- Sum of `f x` as `x` ranges over the elements of the support of `f`, if it's finite. Zero otherwise. -/ @[irreducible] noncomputable def finsum {M α} [add_comm_monoid M] (f : α → M) : M := if h : finite (support (f ∘ plift.down)) then ∑ i in h.to_finset, f i.down else 0 /-- Product of `f x` as `x` ranges over the elements of the multiplicative support of `f`, if it's finite. One otherwise. -/ @[irreducible, to_additive] noncomputable def finprod (f : α → M) : M := if h : finite (mul_support (f ∘ plift.down)) then ∏ i in h.to_finset, f i.down else 1 end localized "notation `∑ᶠ` binders `, ` r:(scoped:67 f, finsum f) := r" in big_operators localized "notation `∏ᶠ` binders `, ` r:(scoped:67 f, finprod f) := r" in big_operators @[to_additive] lemma finprod_eq_prod_plift_of_mul_support_to_finset_subset {f : α → M} (hf : finite (mul_support (f ∘ plift.down))) {s : finset (plift α)} (hs : hf.to_finset ⊆ s) : ∏ᶠ i, f i = ∏ i in s, f i.down := begin rw [finprod, dif_pos], refine finset.prod_subset hs (λ x hx hxf, _), rwa [hf.mem_to_finset, nmem_mul_support] at hxf end @[to_additive] lemma finprod_eq_prod_plift_of_mul_support_subset {f : α → M} {s : finset (plift α)} (hs : mul_support (f ∘ plift.down) ⊆ s) : ∏ᶠ i, f i = ∏ i in s, f i.down := finprod_eq_prod_plift_of_mul_support_to_finset_subset (s.finite_to_set.subset hs) $ λ x hx, by { rw finite.mem_to_finset at hx, exact hs hx } @[simp, to_additive] lemma finprod_one : ∏ᶠ i : α, (1 : M) = 1 := begin have : mul_support (λ x : plift α, (λ _, 1 : α → M) x.down) ⊆ (∅ : finset (plift α)), from λ x h, h rfl, rw [finprod_eq_prod_plift_of_mul_support_subset this, finset.prod_empty] end @[to_additive] lemma finprod_of_is_empty [is_empty α] (f : α → M) : ∏ᶠ i, f i = 1 := by { rw ← finprod_one, congr } @[simp, to_additive] lemma finprod_false (f : false → M) : ∏ᶠ i, f i = 1 := finprod_of_is_empty _ @[to_additive] lemma finprod_eq_single (f : α → M) (a : α) (ha : ∀ x ≠ a, f x = 1) : ∏ᶠ x, f x = f a := begin have : mul_support (f ∘ plift.down) ⊆ ({plift.up a} : finset (plift α)), { intro x, contrapose, simpa [plift.eq_up_iff_down_eq] using ha x.down }, rw [finprod_eq_prod_plift_of_mul_support_subset this, finset.prod_singleton], end @[to_additive] lemma finprod_unique [unique α] (f : α → M) : ∏ᶠ i, f i = f (default α) := finprod_eq_single f (default α) $ λ x hx, (hx $ unique.eq_default _).elim @[simp, to_additive] lemma finprod_true (f : true → M) : ∏ᶠ i, f i = f trivial := @finprod_unique M true _ ⟨⟨trivial⟩, λ _, rfl⟩ f @[to_additive] lemma finprod_eq_dif {p : Prop} [decidable p] (f : p → M) : ∏ᶠ i, f i = if h : p then f h else 1 := begin split_ifs, { haveI : unique p := ⟨⟨h⟩, λ _, rfl⟩, exact finprod_unique f }, { haveI : is_empty p := ⟨h⟩, exact finprod_of_is_empty f } end @[to_additive] lemma finprod_eq_if {p : Prop} [decidable p] {x : M} : ∏ᶠ i : p, x = if p then x else 1 := finprod_eq_dif (λ _, x) @[to_additive] lemma finprod_congr {f g : α → M} (h : ∀ x, f x = g x) : finprod f = finprod g := congr_arg _ $ funext h @[congr, to_additive] lemma finprod_congr_Prop {p q : Prop} {f : p → M} {g : q → M} (hpq : p = q) (hfg : ∀ h : q, f (hpq.mpr h) = g h) : finprod f = finprod g := by { subst q, exact finprod_congr hfg } attribute [congr] finsum_congr_Prop /-- To prove a property of a finite product, it suffices to prove that the property is multiplicative and holds on multipliers. -/ @[to_additive] lemma finprod_induction {f : α → M} (p : M → Prop) (hp₀ : p 1) (hp₁ : ∀ x y, p x → p y → p (x * y)) (hp₂ : ∀ i, p (f i)) : p (∏ᶠ i, f i) := begin rw finprod, split_ifs, exacts [finset.prod_induction _ _ hp₁ hp₀ (λ i hi, hp₂ _), hp₀] end /-- To prove a property of a finite sum, it suffices to prove that the property is additive and holds on summands. -/ add_decl_doc finsum_induction lemma finprod_nonneg {R : Type*} [ordered_comm_semiring R] {f : α → R} (hf : ∀ x, 0 ≤ f x) : 0 ≤ ∏ᶠ x, f x := finprod_induction (λ x, 0 ≤ x) zero_le_one (λ x y, mul_nonneg) hf @[to_additive finsum_nonneg] lemma one_le_finprod' {M : Type*} [ordered_comm_monoid M] {f : α → M} (hf : ∀ i, 1 ≤ f i) : 1 ≤ ∏ᶠ i, f i := finprod_induction _ le_rfl (λ _ _, one_le_mul) hf @[to_additive] lemma monoid_hom.map_finprod_plift (f : M →* N) (g : α → M) (h : finite (mul_support $ g ∘ plift.down)) : f (∏ᶠ x, g x) = ∏ᶠ x, f (g x) := begin rw [finprod_eq_prod_plift_of_mul_support_subset h.coe_to_finset.ge, finprod_eq_prod_plift_of_mul_support_subset, f.map_prod], rw [h.coe_to_finset], exact mul_support_comp_subset f.map_one (g ∘ plift.down) end @[to_additive] lemma monoid_hom.map_finprod_Prop {p : Prop} (f : M →* N) (g : p → M) : f (∏ᶠ x, g x) = ∏ᶠ x, f (g x) := f.map_finprod_plift g (finite.of_fintype _) @[to_additive] lemma monoid_hom.map_finprod_of_preimage_one (f : M →* N) (hf : ∀ x, f x = 1 → x = 1) (g : α → M) : f (∏ᶠ i, g i) = ∏ᶠ i, f (g i) := begin by_cases hg : (mul_support $ g ∘ plift.down).finite, { exact f.map_finprod_plift g hg }, rw [finprod, dif_neg, f.map_one, finprod, dif_neg], exacts [infinite_mono (λ x hx, mt (hf (g x.down)) hx) hg, hg] end @[to_additive] lemma monoid_hom.map_finprod_of_injective (g : M →* N) (hg : injective g) (f : α → M) : g (∏ᶠ i, f i) = ∏ᶠ i, g (f i) := g.map_finprod_of_preimage_one (λ x, (hg.eq_iff' g.map_one).mp) f @[to_additive] lemma mul_equiv.map_finprod (g : M ≃* N) (f : α → M) : g (∏ᶠ i, f i) = ∏ᶠ i, g (f i) := g.to_monoid_hom.map_finprod_of_injective g.injective f lemma finsum_smul {R M : Type*} [ring R] [add_comm_group M] [module R M] [no_zero_smul_divisors R M] (f : ι → R) (x : M) : (∑ᶠ i, f i) • x = (∑ᶠ i, (f i) • x) := begin rcases eq_or_ne x 0 with rfl|hx, { simp }, exact ((smul_add_hom R M).flip x).map_finsum_of_injective (smul_left_injective R hx) _ end lemma smul_finsum {R M : Type*} [ring R] [add_comm_group M] [module R M] [no_zero_smul_divisors R M] (c : R) (f : ι → M) : c • (∑ᶠ i, f i) = (∑ᶠ i, c • f i) := begin rcases eq_or_ne c 0 with rfl|hc, { simp }, exact (smul_add_hom R M c).map_finsum_of_injective (smul_right_injective M hc) _ end @[to_additive] lemma finprod_inv_distrib {G : Type*} [comm_group G] (f : α → G) : ∏ᶠ x, (f x)⁻¹ = (∏ᶠ x, f x)⁻¹ := ((mul_equiv.inv G).map_finprod f).symm end sort section type variables {α β ι M N : Type*} [comm_monoid M] [comm_monoid N] open_locale big_operators @[to_additive] lemma finprod_eq_mul_indicator_apply (s : set α) (f : α → M) (a : α) : ∏ᶠ (h : a ∈ s), f a = mul_indicator s f a := by convert finprod_eq_if @[simp, to_additive] lemma finprod_mem_mul_support (f : α → M) (a : α) : ∏ᶠ (h : f a ≠ 1), f a = f a := by rw [← mem_mul_support, finprod_eq_mul_indicator_apply, mul_indicator_mul_support] @[to_additive] lemma finprod_mem_def (s : set α) (f : α → M) : ∏ᶠ a ∈ s, f a = ∏ᶠ a, mul_indicator s f a := finprod_congr $ finprod_eq_mul_indicator_apply s f @[to_additive] lemma finprod_eq_prod_of_mul_support_subset (f : α → M) {s : finset α} (h : mul_support f ⊆ s) : ∏ᶠ i, f i = ∏ i in s, f i := begin have A : mul_support (f ∘ plift.down) = equiv.plift.symm '' mul_support f, { rw mul_support_comp_eq_preimage, exact (equiv.plift.symm.image_eq_preimage _).symm }, have : mul_support (f ∘ plift.down) ⊆ s.map equiv.plift.symm.to_embedding, { rw [A, finset.coe_map], exact image_subset _ h }, rw [finprod_eq_prod_plift_of_mul_support_subset this], simp end @[to_additive] lemma finprod_eq_prod_of_mul_support_to_finset_subset (f : α → M) (hf : finite (mul_support f)) {s : finset α} (h : hf.to_finset ⊆ s) : ∏ᶠ i, f i = ∏ i in s, f i := finprod_eq_prod_of_mul_support_subset _ $ λ x hx, h $ hf.mem_to_finset.2 hx @[to_additive] lemma finprod_def (f : α → M) [decidable (mul_support f).finite] : ∏ᶠ i : α, f i = if h : (mul_support f).finite then ∏ i in h.to_finset, f i else 1 := begin split_ifs, { exact finprod_eq_prod_of_mul_support_to_finset_subset _ h (finset.subset.refl _) }, { rw [finprod, dif_neg], rw [mul_support_comp_eq_preimage], exact mt (λ hf, hf.of_preimage equiv.plift.surjective) h} end @[to_additive] lemma finprod_of_infinite_mul_support {f : α → M} (hf : (mul_support f).infinite) : ∏ᶠ i, f i = 1 := by { classical, rw [finprod_def, dif_neg hf] } @[to_additive] lemma finprod_eq_prod (f : α → M) (hf : (mul_support f).finite) : ∏ᶠ i : α, f i = ∏ i in hf.to_finset, f i := by { classical, rw [finprod_def, dif_pos hf] } @[to_additive] lemma finprod_eq_prod_of_fintype [fintype α] (f : α → M) : ∏ᶠ i : α, f i = ∏ i, f i := finprod_eq_prod_of_mul_support_to_finset_subset _ (finite.of_fintype _) $ finset.subset_univ _ @[to_additive] lemma finprod_cond_eq_prod_of_cond_iff (f : α → M) {p : α → Prop} {t : finset α} (h : ∀ {x}, f x ≠ 1 → (p x ↔ x ∈ t)) : ∏ᶠ i (hi : p i), f i = ∏ i in t, f i := begin set s := {x | p x}, have : mul_support (s.mul_indicator f) ⊆ t, { rw [set.mul_support_mul_indicator], intros x hx, exact (h hx.2).1 hx.1 }, erw [finprod_mem_def, finprod_eq_prod_of_mul_support_subset _ this], refine finset.prod_congr rfl (λ x hx, mul_indicator_apply_eq_self.2 $ λ hxs, _), contrapose! hxs, exact (h hxs).2 hx end @[to_additive] lemma finprod_mem_eq_prod_of_inter_mul_support_eq (f : α → M) {s : set α} {t : finset α} (h : s ∩ mul_support f = t ∩ mul_support f) : ∏ᶠ i ∈ s, f i = ∏ i in t, f i := finprod_cond_eq_prod_of_cond_iff _ $ by simpa [set.ext_iff] using h @[to_additive] lemma finprod_mem_eq_prod_of_subset (f : α → M) {s : set α} {t : finset α} (h₁ : s ∩ mul_support f ⊆ t) (h₂ : ↑t ⊆ s) : ∏ᶠ i ∈ s, f i = ∏ i in t, f i := finprod_cond_eq_prod_of_cond_iff _ $ λ x hx, ⟨λ h, h₁ ⟨h, hx⟩, λ h, h₂ h⟩ @[to_additive] lemma finprod_mem_eq_prod (f : α → M) {s : set α} (hf : (s ∩ mul_support f).finite) : ∏ᶠ i ∈ s, f i = ∏ i in hf.to_finset, f i := finprod_mem_eq_prod_of_inter_mul_support_eq _ $ by simp [inter_assoc] @[to_additive] lemma finprod_mem_eq_prod_filter (f : α → M) (s : set α) [decidable_pred (∈ s)] (hf : (mul_support f).finite) : ∏ᶠ i ∈ s, f i = ∏ i in finset.filter (∈ s) hf.to_finset, f i := finprod_mem_eq_prod_of_inter_mul_support_eq _ $ by simp [inter_comm, inter_left_comm] @[to_additive] lemma finprod_mem_eq_to_finset_prod (f : α → M) (s : set α) [fintype s] : ∏ᶠ i ∈ s, f i = ∏ i in s.to_finset, f i := finprod_mem_eq_prod_of_inter_mul_support_eq _ $ by rw [coe_to_finset] @[to_additive] lemma finprod_mem_eq_finite_to_finset_prod (f : α → M) {s : set α} (hs : s.finite) : ∏ᶠ i ∈ s, f i = ∏ i in hs.to_finset, f i := finprod_mem_eq_prod_of_inter_mul_support_eq _ $ by rw [hs.coe_to_finset] @[to_additive] lemma finprod_mem_finset_eq_prod (f : α → M) (s : finset α) : ∏ᶠ i ∈ s, f i = ∏ i in s, f i := finprod_mem_eq_prod_of_inter_mul_support_eq _ rfl @[to_additive] lemma finprod_mem_coe_finset (f : α → M) (s : finset α) : ∏ᶠ i ∈ (s : set α), f i = ∏ i in s, f i := finprod_mem_eq_prod_of_inter_mul_support_eq _ rfl @[to_additive] lemma finprod_mem_eq_one_of_infinite {f : α → M} {s : set α} (hs : (s ∩ mul_support f).infinite) : ∏ᶠ i ∈ s, f i = 1 := begin rw finprod_mem_def, apply finprod_of_infinite_mul_support, rwa [← mul_support_mul_indicator] at hs end @[to_additive] lemma finprod_mem_inter_mul_support (f : α → M) (s : set α) : ∏ᶠ i ∈ (s ∩ mul_support f), f i = ∏ᶠ i ∈ s, f i := by rw [finprod_mem_def, finprod_mem_def, mul_indicator_inter_mul_support] @[to_additive] lemma finprod_mem_inter_mul_support_eq (f : α → M) (s t : set α) (h : s ∩ mul_support f = t ∩ mul_support f) : ∏ᶠ i ∈ s, f i = ∏ᶠ i ∈ t, f i := by rw [← finprod_mem_inter_mul_support, h, finprod_mem_inter_mul_support] @[to_additive] lemma finprod_mem_inter_mul_support_eq' (f : α → M) (s t : set α) (h : ∀ x ∈ mul_support f, x ∈ s ↔ x ∈ t) : ∏ᶠ i ∈ s, f i = ∏ᶠ i ∈ t, f i := begin apply finprod_mem_inter_mul_support_eq, ext x, exact and_congr_left (h x) end @[to_additive] lemma finprod_mem_univ (f : α → M) : ∏ᶠ i ∈ @set.univ α, f i = ∏ᶠ i : α, f i := finprod_congr $ λ i, finprod_true _ variables {f g : α → M} {a b : α} {s t : set α} @[to_additive] lemma finprod_mem_congr (h₀ : s = t) (h₁ : ∀ x ∈ t, f x = g x) : ∏ᶠ i ∈ s, f i = ∏ᶠ i ∈ t, g i := h₀.symm ▸ (finprod_congr $ λ i, finprod_congr_Prop rfl (h₁ i)) /-! ### Distributivity w.r.t. addition, subtraction, and (scalar) multiplication -/ /-- If the multiplicative supports of `f` and `g` are finite, then the product of `f i * g i` equals the product of `f i` multiplied by the product over `g i`. -/ @[to_additive] lemma finprod_mul_distrib (hf : (mul_support f).finite) (hg : (mul_support g).finite) : ∏ᶠ i, (f i * g i) = (∏ᶠ i, f i) * ∏ᶠ i, g i := begin classical, rw [finprod_eq_prod_of_mul_support_to_finset_subset _ hf (finset.subset_union_left _ _), finprod_eq_prod_of_mul_support_to_finset_subset _ hg (finset.subset_union_right _ _), ← finset.prod_mul_distrib], refine finprod_eq_prod_of_mul_support_subset _ _, simp [mul_support_mul] end /-- A more general version of `finprod_mem_mul_distrib` that requires `s ∩ mul_support f` and `s ∩ mul_support g` instead of `s` to be finite. -/ @[to_additive] lemma finprod_mem_mul_distrib' (hf : (s ∩ mul_support f).finite) (hg : (s ∩ mul_support g).finite) : ∏ᶠ i ∈ s, (f i * g i) = (∏ᶠ i ∈ s, f i) * ∏ᶠ i ∈ s, g i := begin rw [← mul_support_mul_indicator] at hf hg, simp only [finprod_mem_def, mul_indicator_mul, finprod_mul_distrib hf hg] end /-- The product of constant one over any set equals one. -/ @[to_additive] lemma finprod_mem_one (s : set α) : ∏ᶠ i ∈ s, (1 : M) = 1 := by simp /-- If a function `f` equals one on a set `s`, then the product of `f i` over `i ∈ s` equals one. -/ @[to_additive] lemma finprod_mem_of_eq_on_one (hf : eq_on f 1 s) : ∏ᶠ i ∈ s, f i = 1 := by { rw ← finprod_mem_one s, exact finprod_mem_congr rfl hf } /-- If the product of `f i` over `i ∈ s` is not equal to one, then there is some `x ∈ s` such that `f x ≠ 1`. -/ @[to_additive] lemma exists_ne_one_of_finprod_mem_ne_one (h : ∏ᶠ i ∈ s, f i ≠ 1) : ∃ x ∈ s, f x ≠ 1 := begin by_contra h', push_neg at h', exact h (finprod_mem_of_eq_on_one h') end /-- Given a finite set `s`, the product of `f i * g i` over `i ∈ s` equals the product of `f i` over `i ∈ s` times the product of `g i` over `i ∈ s`. -/ @[to_additive] lemma finprod_mem_mul_distrib (hs : s.finite) : ∏ᶠ i ∈ s, (f i * g i) = (∏ᶠ i ∈ s, f i) * ∏ᶠ i ∈ s, g i := finprod_mem_mul_distrib' (hs.inter_of_left _) (hs.inter_of_left _) @[to_additive] lemma monoid_hom.map_finprod {f : α → M} (g : M →* N) (hf : (mul_support f).finite) : g (∏ᶠ i, f i) = ∏ᶠ i, g (f i) := g.map_finprod_plift f $ hf.preimage $ equiv.plift.injective.inj_on _ /-- A more general version of `monoid_hom.map_finprod_mem` that requires `s ∩ mul_support f` and instead of `s` to be finite. -/ @[to_additive] lemma monoid_hom.map_finprod_mem' {f : α → M} (g : M →* N) (h₀ : (s ∩ mul_support f).finite) : g (∏ᶠ j ∈ s, f j) = ∏ᶠ i ∈ s, (g (f i)) := begin rw [g.map_finprod], { simp only [g.map_finprod_Prop] }, { simpa only [finprod_eq_mul_indicator_apply, mul_support_mul_indicator] } end /-- Given a monoid homomorphism `g : M →* N`, and a function `f : α → M`, the value of `g` at the product of `f i` over `i ∈ s` equals the product of `(g ∘ f) i` over `s`. -/ @[to_additive] lemma monoid_hom.map_finprod_mem (f : α → M) (g : M →* N) (hs : s.finite) : g (∏ᶠ j ∈ s, f j) = ∏ᶠ i ∈ s, g (f i) := g.map_finprod_mem' (hs.inter_of_left _) /-! ### `∏ᶠ x ∈ s, f x` and set operations -/ /-- The product of any function over an empty set is one. -/ @[to_additive] lemma finprod_mem_empty : ∏ᶠ i ∈ (∅ : set α), f i = 1 := by simp /-- A set `s` is not empty if the product of some function over `s` is not equal to one. -/ @[to_additive] lemma nonempty_of_finprod_mem_ne_one (h : ∏ᶠ i ∈ s, f i ≠ 1) : s.nonempty := ne_empty_iff_nonempty.1 $ λ h', h $ h'.symm ▸ finprod_mem_empty /-- Given finite sets `s` and `t`, the product of `f i` over `i ∈ s ∪ t` times the product of `f i` over `i ∈ s ∩ t` equals the product of `f i` over `i ∈ s` times the product of `f i` over `i ∈ t`. -/ @[to_additive] lemma finprod_mem_union_inter (hs : s.finite) (ht : t.finite) : (∏ᶠ i ∈ s ∪ t, f i) * ∏ᶠ i ∈ s ∩ t, f i = (∏ᶠ i ∈ s, f i) * ∏ᶠ i ∈ t, f i := begin unfreezingI { lift s to finset α using hs, lift t to finset α using ht }, classical, rw [← finset.coe_union, ← finset.coe_inter], simp only [finprod_mem_coe_finset, finset.prod_union_inter] end /-- A more general version of `finprod_mem_union_inter` that requires `s ∩ mul_support f` and `t ∩ mul_support f` instead of `s` and `t` to be finite. -/ @[to_additive] lemma finprod_mem_union_inter' (hs : (s ∩ mul_support f).finite) (ht : (t ∩ mul_support f).finite) : (∏ᶠ i ∈ s ∪ t, f i) * ∏ᶠ i ∈ s ∩ t, f i = (∏ᶠ i ∈ s, f i) * ∏ᶠ i ∈ t, f i := begin rw [← finprod_mem_inter_mul_support f s, ← finprod_mem_inter_mul_support f t, ← finprod_mem_union_inter hs ht, ← union_inter_distrib_right, finprod_mem_inter_mul_support, ← finprod_mem_inter_mul_support f (s ∩ t)], congr' 2, rw [inter_left_comm, inter_assoc, inter_assoc, inter_self, inter_left_comm] end /-- A more general version of `finprod_mem_union` that requires `s ∩ mul_support f` and `t ∩ mul_support f` instead of `s` and `t` to be finite. -/ @[to_additive] lemma finprod_mem_union' (hst : disjoint s t) (hs : (s ∩ mul_support f).finite) (ht : (t ∩ mul_support f).finite) : ∏ᶠ i ∈ s ∪ t, f i = (∏ᶠ i ∈ s, f i) * ∏ᶠ i ∈ t, f i := by rw [← finprod_mem_union_inter' hs ht, disjoint_iff_inter_eq_empty.1 hst, finprod_mem_empty, mul_one] /-- Given two finite disjoint sets `s` and `t`, the product of `f i` over `i ∈ s ∪ t` equals the product of `f i` over `i ∈ s` times the product of `f i` over `i ∈ t`. -/ @[to_additive] lemma finprod_mem_union (hst : disjoint s t) (hs : s.finite) (ht : t.finite) : ∏ᶠ i ∈ s ∪ t, f i = (∏ᶠ i ∈ s, f i) * ∏ᶠ i ∈ t, f i := finprod_mem_union' hst (hs.inter_of_left _) (ht.inter_of_left _) /-- A more general version of `finprod_mem_union'` that requires `s ∩ mul_support f` and `t ∩ mul_support f` instead of `s` and `t` to be disjoint -/ @[to_additive] lemma finprod_mem_union'' (hst : disjoint (s ∩ mul_support f) (t ∩ mul_support f)) (hs : (s ∩ mul_support f).finite) (ht : (t ∩ mul_support f).finite) : ∏ᶠ i ∈ s ∪ t, f i = (∏ᶠ i ∈ s, f i) * ∏ᶠ i ∈ t, f i := by rw [← finprod_mem_inter_mul_support f s, ← finprod_mem_inter_mul_support f t, ← finprod_mem_union hst hs ht, ← union_inter_distrib_right, finprod_mem_inter_mul_support] /-- The product of `f i` over `i ∈ {a}` equals `f a`. -/ @[to_additive] lemma finprod_mem_singleton : ∏ᶠ i ∈ ({a} : set α), f i = f a := by rw [← finset.coe_singleton, finprod_mem_coe_finset, finset.prod_singleton] @[simp, to_additive] lemma finprod_cond_eq_left : ∏ᶠ i = a, f i = f a := finprod_mem_singleton @[simp, to_additive] lemma finprod_cond_eq_right : ∏ᶠ i (hi : a = i), f i = f a := by simp [@eq_comm _ a] /-- A more general version of `finprod_mem_insert` that requires `s ∩ mul_support f` instead of `s` to be finite. -/ @[to_additive] lemma finprod_mem_insert' (f : α → M) (h : a ∉ s) (hs : (s ∩ mul_support f).finite) : ∏ᶠ i ∈ insert a s, f i = f a * ∏ᶠ i ∈ s, f i := begin rw [insert_eq, finprod_mem_union' _ _ hs, finprod_mem_singleton], { rwa disjoint_singleton_left }, { exact (finite_singleton a).inter_of_left _ } end /-- Given a finite set `s` and an element `a ∉ s`, the product of `f i` over `i ∈ insert a s` equals `f a` times the product of `f i` over `i ∈ s`. -/ @[to_additive] lemma finprod_mem_insert (f : α → M) (h : a ∉ s) (hs : s.finite) : ∏ᶠ i ∈ insert a s, f i = f a * ∏ᶠ i ∈ s, f i := finprod_mem_insert' f h $ hs.inter_of_left _ /-- If `f a = 1` for all `a ∉ s`, then the product of `f i` over `i ∈ insert a s` equals the product of `f i` over `i ∈ s`. -/ @[to_additive] lemma finprod_mem_insert_of_eq_one_if_not_mem (h : a ∉ s → f a = 1) : ∏ᶠ i ∈ (insert a s), f i = ∏ᶠ i ∈ s, f i := begin refine finprod_mem_inter_mul_support_eq' _ _ _ (λ x hx, ⟨_, or.inr⟩), rintro (rfl|hxs), exacts [not_imp_comm.1 h hx, hxs] end /-- If `f a = 1`, then the product of `f i` over `i ∈ insert a s` equals the product of `f i` over `i ∈ s`. -/ @[to_additive] lemma finprod_mem_insert_one (h : f a = 1) : ∏ᶠ i ∈ (insert a s), f i = ∏ᶠ i ∈ s, f i := finprod_mem_insert_of_eq_one_if_not_mem (λ _, h) /-- The product of `f i` over `i ∈ {a, b}`, `a ≠ b`, is equal to `f a * f b`. -/ @[to_additive] lemma finprod_mem_pair (h : a ≠ b) : ∏ᶠ i ∈ ({a, b} : set α), f i = f a * f b := by { rw [finprod_mem_insert, finprod_mem_singleton], exacts [h, finite_singleton b] } /-- The product of `f y` over `y ∈ g '' s` equals the product of `f (g i)` over `s` provided that `g` is injective on `s ∩ mul_support (f ∘ g)`. -/ @[to_additive] lemma finprod_mem_image' {s : set β} {g : β → α} (hg : set.inj_on g (s ∩ mul_support (f ∘ g))) : ∏ᶠ i ∈ (g '' s), f i = ∏ᶠ j ∈ s, f (g j) := begin classical, by_cases hs : finite (s ∩ mul_support (f ∘ g)), { have hg : ∀ (x ∈ hs.to_finset) (y ∈ hs.to_finset), g x = g y → x = y, by simpa only [hs.mem_to_finset], rw [finprod_mem_eq_prod _ hs, ← finset.prod_image hg], refine finprod_mem_eq_prod_of_inter_mul_support_eq f _, rw [finset.coe_image, hs.coe_to_finset, ← image_inter_mul_support_eq, inter_assoc, inter_self] }, { rw [finprod_mem_eq_one_of_infinite hs, finprod_mem_eq_one_of_infinite], rwa [image_inter_mul_support_eq, infinite_image_iff hg] } end /-- The product of `f y` over `y ∈ g '' s` equals the product of `f (g i)` over `s` provided that `g` is injective on `s`. -/ @[to_additive] lemma finprod_mem_image {β} {s : set β} {g : β → α} (hg : set.inj_on g s) : ∏ᶠ i ∈ (g '' s), f i = ∏ᶠ j ∈ s, f (g j) := finprod_mem_image' $ hg.mono $ inter_subset_left _ _ /-- The product of `f y` over `y ∈ set.range g` equals the product of `f (g i)` over all `i` provided that `g` is injective on `mul_support (f ∘ g)`. -/ @[to_additive] lemma finprod_mem_range' {g : β → α} (hg : set.inj_on g (mul_support (f ∘ g))) : ∏ᶠ i ∈ range g, f i = ∏ᶠ j, f (g j) := begin rw [← image_univ, finprod_mem_image', finprod_mem_univ], rwa univ_inter end /-- The product of `f y` over `y ∈ set.range g` equals the product of `f (g i)` over all `i` provided that `g` is injective. -/ @[to_additive] lemma finprod_mem_range {g : β → α} (hg : injective g) : ∏ᶠ i ∈ range g, f i = ∏ᶠ j, f (g j) := finprod_mem_range' (hg.inj_on _) /-- The product of `f i` over `s : set α` is equal to the product of `g j` over `t : set β` if there exists a function `e : α → β` such that `e` is bijective from `s` to `t` and for all `x` in `s` we have `f x = g (e x)`. -/ @[to_additive] lemma finprod_mem_eq_of_bij_on {s : set α} {t : set β} {f : α → M} {g : β → M} (e : α → β) (he₀ : set.bij_on e s t) (he₁ : ∀ x ∈ s, f x = g (e x)) : ∏ᶠ i ∈ s, f i = ∏ᶠ j ∈ t, g j := begin rw [← set.bij_on.image_eq he₀, finprod_mem_image he₀.2.1], exact finprod_mem_congr rfl he₁ end @[to_additive] lemma finprod_set_coe_eq_finprod_mem (s : set α) : ∏ᶠ j : s, f j = ∏ᶠ i ∈ s, f i := begin rw [← finprod_mem_range, subtype.range_coe], exact subtype.coe_injective end @[to_additive] lemma finprod_subtype_eq_finprod_cond (p : α → Prop) : ∏ᶠ j : subtype p, f j = ∏ᶠ i (hi : p i), f i := finprod_set_coe_eq_finprod_mem {i | p i} @[to_additive] lemma finprod_mem_inter_mul_diff' (t : set α) (h : (s ∩ mul_support f).finite) : (∏ᶠ i ∈ s ∩ t, f i) * ∏ᶠ i ∈ s \ t, f i = ∏ᶠ i ∈ s, f i := begin rw [← finprod_mem_union', inter_union_diff], exacts [λ x hx, hx.2.2 hx.1.2, h.subset (λ x hx, ⟨hx.1.1, hx.2⟩), h.subset (λ x hx, ⟨hx.1.1, hx.2⟩)], end @[to_additive] lemma finprod_mem_inter_mul_diff (t : set α) (h : s.finite) : (∏ᶠ i ∈ s ∩ t, f i) * ∏ᶠ i ∈ s \ t, f i = ∏ᶠ i ∈ s, f i := finprod_mem_inter_mul_diff' _ $ h.inter_of_left _ /-- A more general version of `finprod_mem_mul_diff` that requires `t ∩ mul_support f` instead of `t` to be finite. -/ @[to_additive] lemma finprod_mem_mul_diff' (hst : s ⊆ t) (ht : (t ∩ mul_support f).finite) : (∏ᶠ i ∈ s, f i) * ∏ᶠ i ∈ t \ s, f i = ∏ᶠ i ∈ t, f i := by rw [← finprod_mem_inter_mul_diff' _ ht, inter_eq_self_of_subset_right hst] /-- Given a finite set `t` and a subset `s` of `t`, the product of `f i` over `i ∈ s` times the product of `f i` over `t \ s` equals the product of `f i` over `i ∈ t`. -/ @[to_additive] lemma finprod_mem_mul_diff (hst : s ⊆ t) (ht : t.finite) : (∏ᶠ i ∈ s, f i) * ∏ᶠ i ∈ t \ s, f i = ∏ᶠ i ∈ t, f i := finprod_mem_mul_diff' hst (ht.inter_of_left _) /-- Given a family of pairwise disjoint finite sets `t i` indexed by a finite type, the product of `f a` over the union `⋃ i, t i` is equal to the product over all indexes `i` of the products of `f a` over `a ∈ t i`. -/ @[to_additive] lemma finprod_mem_Union [fintype ι] {t : ι → set α} (h : pairwise (disjoint on t)) (ht : ∀ i, (t i).finite) : ∏ᶠ a ∈ (⋃ i : ι, t i), f a = ∏ᶠ i, (∏ᶠ a ∈ t i, f a) := begin unfreezingI { lift t to ι → finset α using ht }, classical, rw [← bUnion_univ, ← finset.coe_univ, ← finset.coe_bUnion, finprod_mem_coe_finset, finset.prod_bUnion], { simp only [finprod_mem_coe_finset, finprod_eq_prod_of_fintype] }, { exact λ x _ y _ hxy, finset.disjoint_iff_disjoint_coe.2 (h x y hxy) } end /-- Given a family of sets `t : ι → set α`, a finite set `I` in the index type such that all sets `t i`, `i ∈ I`, are finite, if all `t i`, `i ∈ I`, are pairwise disjoint, then the product of `f a` over `a ∈ ⋃ i ∈ I, t i` is equal to the product over `i ∈ I` of the products of `f a` over `a ∈ t i`. -/ @[to_additive] lemma finprod_mem_bUnion {I : set ι} {t : ι → set α} (h : pairwise_on I (disjoint on t)) (hI : I.finite) (ht : ∀ i ∈ I, (t i).finite) : ∏ᶠ a ∈ ⋃ x ∈ I, t x, f a = ∏ᶠ i ∈ I, ∏ᶠ j ∈ t i, f j := begin haveI := hI.fintype, rw [← Union_subtype, finprod_mem_Union, ← finprod_set_coe_eq_finprod_mem], exacts [λ x y hxy, h x x.2 y y.2 (subtype.coe_injective.ne hxy), λ b, ht b b.2] end /-- If `t` is a finite set of pairwise disjoint finite sets, then the product of `f a` over `a ∈ ⋃₀ t` is the product over `s ∈ t` of the products of `f a` over `a ∈ s`. -/ @[to_additive] lemma finprod_mem_sUnion {t : set (set α)} (h : pairwise_on t disjoint) (ht₀ : t.finite) (ht₁ : ∀ x ∈ t, set.finite x): ∏ᶠ a ∈ ⋃₀ t, f a = ∏ᶠ s ∈ t, ∏ᶠ a ∈ s, f a := by rw [set.sUnion_eq_bUnion, finprod_mem_bUnion h ht₀ ht₁] /-- If `s : set α` and `t : set β` are finite sets, then the product over `s` commutes with the product over `t`. -/ @[to_additive] lemma finprod_mem_comm {s : set α} {t : set β} (f : α → β → M) (hs : s.finite) (ht : t.finite) : ∏ᶠ i ∈ s, ∏ᶠ j ∈ t, f i j = ∏ᶠ j ∈ t, ∏ᶠ i ∈ s, f i j := begin unfreezingI { lift s to finset α using hs, lift t to finset β using ht }, simp only [finprod_mem_coe_finset], exact finset.prod_comm end /-- To prove a property of a finite product, it suffices to prove that the property is multiplicative and holds on multipliers. -/ @[to_additive] lemma finprod_mem_induction (p : M → Prop) (hp₀ : p 1) (hp₁ : ∀ x y, p x → p y → p (x * y)) (hp₂ : ∀ x ∈ s, p $ f x) : p (∏ᶠ i ∈ s, f i) := finprod_induction _ hp₀ hp₁ $ λ x, finprod_induction _ hp₀ hp₁ $ hp₂ x lemma finprod_cond_nonneg {R : Type*} [ordered_comm_semiring R] {p : α → Prop} {f : α → R} (hf : ∀ x, p x → 0 ≤ f x) : 0 ≤ ∏ᶠ x (h : p x), f x := finprod_nonneg $ λ x, finprod_nonneg $ hf x @[to_additive] lemma single_le_finprod {M : Type*} [ordered_comm_monoid M] (i : α) {f : α → M} (hf : finite (mul_support f)) (h : ∀ j, 1 ≤ f j) : f i ≤ ∏ᶠ j, f j := by classical; calc f i ≤ ∏ j in insert i hf.to_finset, f j : finset.single_le_prod' (λ j hj, h j) (finset.mem_insert_self _ _) ... = ∏ᶠ j, f j : (finprod_eq_prod_of_mul_support_to_finset_subset _ hf (finset.subset_insert _ _)).symm lemma finprod_eq_zero {M₀ : Type*} [comm_monoid_with_zero M₀] (f : α → M₀) (x : α) (hx : f x = 0) (hf : finite (mul_support f)) : ∏ᶠ x, f x = 0 := begin nontriviality, rw [finprod_eq_prod f hf], refine finset.prod_eq_zero (hf.mem_to_finset.2 _) hx, simp [hx] end @[to_additive] lemma finprod_prod_comm (s : finset β) (f : α → β → M) (h : ∀ b ∈ s, (mul_support (λ a, f a b)).finite) : ∏ᶠ a : α, ∏ b in s, f a b = ∏ b in s, ∏ᶠ a : α, f a b := begin have hU : mul_support (λ a, ∏ b in s, f a b) ⊆ (s.finite_to_set.bUnion (λ b hb, h b (finset.mem_coe.1 hb))).to_finset, { rw finite.coe_to_finset, intros x hx, simp only [exists_prop, mem_Union, ne.def, mem_mul_support, finset.mem_coe], contrapose! hx, rw [mem_mul_support, not_not, finset.prod_congr rfl hx, finset.prod_const_one] }, rw [finprod_eq_prod_of_mul_support_subset _ hU, finset.prod_comm], refine finset.prod_congr rfl (λ b hb, (finprod_eq_prod_of_mul_support_subset _ _).symm), intros a ha, simp only [finite.coe_to_finset, mem_Union], exact ⟨b, hb, ha⟩ end @[to_additive] lemma prod_finprod_comm (s : finset α) (f : α → β → M) (h : ∀ a ∈ s, (mul_support (f a)).finite) : ∏ a in s, ∏ᶠ b : β, f a b = ∏ᶠ b : β, ∏ a in s, f a b := (finprod_prod_comm s (λ b a, f a b) h).symm lemma mul_finsum {R : Type*} [semiring R] (f : α → R) (r : R) (h : (function.support f).finite) : r * ∑ᶠ a : α, f a = ∑ᶠ a : α, r * f a := (add_monoid_hom.mul_left r).map_finsum h lemma finsum_mul {R : Type*} [semiring R] (f : α → R) (r : R) (h : (function.support f).finite) : (∑ᶠ a : α, f a) * r = ∑ᶠ a : α, f a * r := (add_monoid_hom.mul_right r).map_finsum h @[to_additive] lemma finset.mul_support_of_fiberwise_prod_subset_image [decidable_eq β] (s : finset α) (f : α → M) (g : α → β) : mul_support (λ b, (s.filter (λ a, g a = b)).prod f) ⊆ s.image g := begin simp only [finset.coe_image, set.mem_image, finset.mem_coe, function.support_subset_iff], intros b h, suffices : (s.filter (λ (a : α), g a = b)).nonempty, { simpa only [s.fiber_nonempty_iff_mem_image g b, finset.mem_image, exists_prop], }, exact finset.nonempty_of_prod_ne_one h, end /-- Note that `b ∈ (s.filter (λ ab, prod.fst ab = a)).image prod.snd` iff `(a, b) ∈ s` so we can simplify the right hand side of this lemma. However the form stated here is more useful for iterating this lemma, e.g., if we have `f : α × β × γ → M`. -/ @[to_additive] lemma finprod_mem_finset_product' [decidable_eq α] [decidable_eq β] (s : finset (α × β)) (f : α × β → M) : ∏ᶠ ab (h : ab ∈ s), f ab = ∏ᶠ a b (h : b ∈ (s.filter (λ ab, prod.fst ab = a)).image prod.snd), f (a, b) := begin have : ∀ a, ∏ (i : β) in (s.filter (λ ab, prod.fst ab = a)).image prod.snd, f (a, i) = (finset.filter (λ ab, prod.fst ab = a) s).prod f, { intros a, apply finset.prod_bij (λ b _, (a, b)); finish, }, rw finprod_mem_finset_eq_prod, simp_rw [finprod_mem_finset_eq_prod, this], rw [finprod_eq_prod_of_mul_support_subset _ (s.mul_support_of_fiberwise_prod_subset_image f prod.fst), ← finset.prod_fiberwise_of_maps_to _ f], finish, end /-- See also `finprod_mem_finset_product'`. -/ @[to_additive] lemma finprod_mem_finset_product (s : finset (α × β)) (f : α × β → M) : ∏ᶠ ab (h : ab ∈ s), f ab = ∏ᶠ a b (h : (a, b) ∈ s), f (a, b) := by { classical, rw finprod_mem_finset_product', simp, } @[to_additive] lemma finprod_mem_finset_product₃ {γ : Type*} (s : finset (α × β × γ)) (f : α × β × γ → M) : ∏ᶠ abc (h : abc ∈ s), f abc = ∏ᶠ a b c (h : (a, b, c) ∈ s), f (a, b, c) := by { classical, rw finprod_mem_finset_product', simp_rw finprod_mem_finset_product', simp, } @[to_additive] lemma finprod_curry (f : α × β → M) (hf : (mul_support f).finite) : ∏ᶠ ab, f ab = ∏ᶠ a b, f (a, b) := begin have h₁ : ∀ a, ∏ᶠ (h : a ∈ hf.to_finset), f a = f a, { simp, }, have h₂ : ∏ᶠ a, f a = ∏ᶠ a (h : a ∈ hf.to_finset), f a, { simp, }, simp_rw [h₂, finprod_mem_finset_product, h₁], end @[to_additive] lemma finprod_curry₃ {γ : Type*} (f : α × β × γ → M) (h : (mul_support f).finite) : ∏ᶠ abc, f abc = ∏ᶠ a b c, f (a, b, c) := by { rw finprod_curry f h, congr, ext a, rw finprod_curry, simp [h], } @[to_additive] lemma finprod_dmem {s : set α} [decidable_pred (∈ s)] (f : (Π (a : α), a ∈ s → M)) : ∏ᶠ (a : α) (h : a ∈ s), f a h = ∏ᶠ (a : α) (h : a ∈ s), if h' : a ∈ s then f a h' else 1 := finprod_congr (λ a, finprod_congr (λ ha, (dif_pos ha).symm)) @[to_additive] lemma finprod_emb_domain' {f : α → β} (hf : function.injective f) [decidable_pred (∈ set.range f)] (g : α → M) : ∏ᶠ (b : β), (if h : b ∈ set.range f then g (classical.some h) else 1) = ∏ᶠ (a : α), g a := begin simp_rw [← finprod_eq_dif], rw [finprod_dmem, finprod_mem_range hf, finprod_congr (λ a, _)], rw [dif_pos (set.mem_range_self a), hf (classical.some_spec (set.mem_range_self a))] end @[to_additive] lemma finprod_emb_domain (f : α ↪ β) [decidable_pred (∈ set.range f)] (g : α → M) : ∏ᶠ (b : β), (if h : b ∈ set.range f then g (classical.some h) else 1) = ∏ᶠ (a : α), g a := finprod_emb_domain' f.injective g end type
ce8da36011c83eecad31a49da018d6c232c999d0
3f7026ea8bef0825ca0339a275c03b911baef64d
/src/data/equiv/algebra.lean
024ae2c43fdaa35e55b09ff4ecb28eeab9a12472
[ "Apache-2.0" ]
permissive
rspencer01/mathlib
b1e3afa5c121362ef0881012cc116513ab09f18c
c7d36292c6b9234dc40143c16288932ae38fdc12
refs/heads/master
1,595,010,346,708
1,567,511,503,000
1,567,511,503,000
206,071,681
0
0
Apache-2.0
1,567,513,643,000
1,567,513,643,000
null
UTF-8
Lean
false
false
12,747
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import data.equiv.basic algebra.field /-! # equivs in the algebraic hierarchy The role of this file is twofold. In the first part there are theorems of the following form: if α has a group structure and α ≃ β then β has a group structure, and similarly for monoids, semigroups, rings, integral domains, fields and so on. In the second part there are extensions of equiv called add_equiv, mul_equiv, and ring_equiv, which are datatypes representing isomorphisms of add_monoids/add_groups, monoids/groups and rings. ## Notations The extended equivs all have coercions to functions, and the coercions are the canonical notation when treating the isomorphisms as maps. ## Implementation notes Bundling structures means that many things turn into definitions, meaning that to_additive cannot do much work for us, and conversely that we have to do a lot of naming for it. The fields for mul_equiv and add_equiv now avoid the unbundled `is_mul_hom` and `is_add_hom`, as these are deprecated. However ring_equiv still relies on `is_ring_hom`; this should be rewritten in future. ## Tags equiv, mul_equiv, add_equiv, ring_equiv -/ universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} namespace equiv section group variables [group α] @[to_additive] protected def mul_left (a : α) : α ≃ α := { to_fun := λx, a * x, inv_fun := λx, a⁻¹ * x, left_inv := assume x, show a⁻¹ * (a * x) = x, from inv_mul_cancel_left a x, right_inv := assume x, show a * (a⁻¹ * x) = x, from mul_inv_cancel_left a x } @[to_additive] protected def mul_right (a : α) : α ≃ α := { to_fun := λx, x * a, inv_fun := λx, x * a⁻¹, left_inv := assume x, show (x * a) * a⁻¹ = x, from mul_inv_cancel_right x a, right_inv := assume x, show (x * a⁻¹) * a = x, from inv_mul_cancel_right x a } @[to_additive] protected def inv (α) [group α] : α ≃ α := { to_fun := λa, a⁻¹, inv_fun := λa, a⁻¹, left_inv := assume a, inv_inv a, right_inv := assume a, inv_inv a } def units_equiv_ne_zero (α : Type*) [field α] : units α ≃ {a : α | a ≠ 0} := ⟨λ a, ⟨a.1, units.ne_zero _⟩, λ a, units.mk0 _ a.2, λ ⟨_, _, _, _⟩, units.ext rfl, λ ⟨_, _⟩, rfl⟩ @[simp] lemma coe_units_equiv_ne_zero [field α] (a : units α) : ((units_equiv_ne_zero α a) : α) = a := rfl end group section instances variables (e : α ≃ β) protected def has_zero [has_zero β] : has_zero α := ⟨e.symm 0⟩ lemma zero_def [has_zero β] : @has_zero.zero _ (equiv.has_zero e) = e.symm 0 := rfl protected def has_one [has_one β] : has_one α := ⟨e.symm 1⟩ lemma one_def [has_one β] : @has_one.one _ (equiv.has_one e) = e.symm 1 := rfl protected def has_mul [has_mul β] : has_mul α := ⟨λ x y, e.symm (e x * e y)⟩ lemma mul_def [has_mul β] (x y : α) : @has_mul.mul _ (equiv.has_mul e) x y = e.symm (e x * e y) := rfl protected def has_add [has_add β] : has_add α := ⟨λ x y, e.symm (e x + e y)⟩ lemma add_def [has_add β] (x y : α) : @has_add.add _ (equiv.has_add e) x y = e.symm (e x + e y) := rfl protected def has_inv [has_inv β] : has_inv α := ⟨λ x, e.symm (e x)⁻¹⟩ lemma inv_def [has_inv β] (x : α) : @has_inv.inv _ (equiv.has_inv e) x = e.symm (e x)⁻¹ := rfl protected def has_neg [has_neg β] : has_neg α := ⟨λ x, e.symm (-e x)⟩ lemma neg_def [has_neg β] (x : α) : @has_neg.neg _ (equiv.has_neg e) x = e.symm (-e x) := rfl protected def semigroup [semigroup β] : semigroup α := { mul_assoc := by simp [mul_def, mul_assoc], ..equiv.has_mul e } protected def comm_semigroup [comm_semigroup β] : comm_semigroup α := { mul_comm := by simp [mul_def, mul_comm], ..equiv.semigroup e } protected def monoid [monoid β] : monoid α := { one_mul := by simp [mul_def, one_def], mul_one := by simp [mul_def, one_def], ..equiv.semigroup e, ..equiv.has_one e } protected def comm_monoid [comm_monoid β] : comm_monoid α := { ..equiv.comm_semigroup e, ..equiv.monoid e } protected def group [group β] : group α := { mul_left_inv := by simp [mul_def, inv_def, one_def], ..equiv.monoid e, ..equiv.has_inv e } protected def comm_group [comm_group β] : comm_group α := { ..equiv.group e, ..equiv.comm_semigroup e } protected def add_semigroup [add_semigroup β] : add_semigroup α := @additive.add_semigroup _ (@equiv.semigroup _ _ e multiplicative.semigroup) protected def add_comm_semigroup [add_comm_semigroup β] : add_comm_semigroup α := @additive.add_comm_semigroup _ (@equiv.comm_semigroup _ _ e multiplicative.comm_semigroup) protected def add_monoid [add_monoid β] : add_monoid α := @additive.add_monoid _ (@equiv.monoid _ _ e multiplicative.monoid) protected def add_comm_monoid [add_comm_monoid β] : add_comm_monoid α := @additive.add_comm_monoid _ (@equiv.comm_monoid _ _ e multiplicative.comm_monoid) protected def add_group [add_group β] : add_group α := @additive.add_group _ (@equiv.group _ _ e multiplicative.group) protected def add_comm_group [add_comm_group β] : add_comm_group α := @additive.add_comm_group _ (@equiv.comm_group _ _ e multiplicative.comm_group) protected def semiring [semiring β] : semiring α := { right_distrib := by simp [mul_def, add_def, add_mul], left_distrib := by simp [mul_def, add_def, mul_add], zero_mul := by simp [mul_def, zero_def], mul_zero := by simp [mul_def, zero_def], ..equiv.has_zero e, ..equiv.has_mul e, ..equiv.has_add e, ..equiv.monoid e, ..equiv.add_comm_monoid e } protected def comm_semiring [comm_semiring β] : comm_semiring α := { ..equiv.semiring e, ..equiv.comm_monoid e } protected def ring [ring β] : ring α := { ..equiv.semiring e, ..equiv.add_comm_group e } protected def comm_ring [comm_ring β] : comm_ring α := { ..equiv.comm_monoid e, ..equiv.ring e } protected def zero_ne_one_class [zero_ne_one_class β] : zero_ne_one_class α := { zero_ne_one := by simp [zero_def, one_def], ..equiv.has_zero e, ..equiv.has_one e } protected def nonzero_comm_ring [nonzero_comm_ring β] : nonzero_comm_ring α := { ..equiv.zero_ne_one_class e, ..equiv.comm_ring e } protected def domain [domain β] : domain α := { eq_zero_or_eq_zero_of_mul_eq_zero := by simp [mul_def, zero_def, equiv.eq_symm_apply], ..equiv.has_zero e, ..equiv.zero_ne_one_class e, ..equiv.has_mul e, ..equiv.ring e } protected def integral_domain [integral_domain β] : integral_domain α := { ..equiv.domain e, ..equiv.nonzero_comm_ring e } protected def division_ring [division_ring β] : division_ring α := { inv_mul_cancel := λ _, by simp [mul_def, inv_def, zero_def, one_def, (equiv.symm_apply_eq _).symm]; exact inv_mul_cancel, mul_inv_cancel := λ _, by simp [mul_def, inv_def, zero_def, one_def, (equiv.symm_apply_eq _).symm]; exact mul_inv_cancel, ..equiv.has_zero e, ..equiv.has_one e, ..equiv.domain e, ..equiv.has_inv e } protected def field [field β] : field α := { ..equiv.integral_domain e, ..equiv.division_ring e } protected def discrete_field [discrete_field β] : discrete_field α := { has_decidable_eq := equiv.decidable_eq e, inv_zero := by simp [mul_def, inv_def, zero_def], ..equiv.has_mul e, ..equiv.has_inv e, ..equiv.has_zero e, ..equiv.field e } end instances end equiv set_option old_structure_cmd true /-- add_equiv α β is the type of an equiv α ≃ β which preserves addition. -/ structure add_equiv (α β : Type*) [has_add α] [has_add β] extends α ≃ β := (map_add' : ∀ x y : α, to_fun (x + y) = to_fun x + to_fun y) /-- mul_equiv α β is the type of an equiv α ≃ β which preserves multiplication. -/ @[to_additive] structure mul_equiv (α β : Type*) [has_mul α] [has_mul β] extends α ≃ β := (map_mul' : ∀ x y : α, to_fun (x * y) = to_fun x * to_fun y) infix ` ≃* `:25 := mul_equiv infix ` ≃+ `:25 := add_equiv namespace mul_equiv @[to_additive] instance {α β} [has_mul α] [has_mul β] : has_coe_to_fun (α ≃* β) := ⟨_, mul_equiv.to_fun⟩ variables [has_mul α] [has_mul β] [has_mul γ] /-- A multiplicative isomorphism preserves multiplication (canonical form). -/ @[to_additive] def map_mul (f : α ≃* β) : ∀ x y : α, f (x * y) = f x * f y := f.map_mul' /-- A multiplicative isomorphism preserves multiplication (deprecated). -/ @[to_additive] instance (h : α ≃* β) : is_mul_hom h := ⟨h.map_mul⟩ /-- The identity map is a multiplicative isomorphism. -/ @[refl, to_additive] def refl (α : Type*) [has_mul α] : α ≃* α := { map_mul' := λ _ _,rfl, ..equiv.refl _} /-- The inverse of an isomorphism is an isomorphism. -/ @[symm, to_additive] def symm (h : α ≃* β) : β ≃* α := { map_mul' := λ n₁ n₂, function.injective_of_left_inverse h.left_inv begin show h.to_equiv (h.to_equiv.symm (n₁ * n₂)) = h ((h.to_equiv.symm n₁) * (h.to_equiv.symm n₂)), rw h.map_mul, show _ = h.to_equiv (_) * h.to_equiv (_), rw [h.to_equiv.apply_symm_apply, h.to_equiv.apply_symm_apply, h.to_equiv.apply_symm_apply], end, ..h.to_equiv.symm} @[simp, to_additive] theorem to_equiv_symm (f : α ≃* β) : f.symm.to_equiv = f.to_equiv.symm := rfl /-- Transitivity of multiplication-preserving isomorphisms -/ @[trans, to_additive] def trans (h1 : α ≃* β) (h2 : β ≃* γ) : (α ≃* γ) := { 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.right_inv in canonical form -/ @[simp, to_additive] def apply_symm_apply (e : α ≃* β) : ∀ (y : β), e (e.symm y) = y := e.to_equiv.apply_symm_apply /-- e.left_inv in canonical form -/ @[simp, to_additive] def symm_apply_apply (e : α ≃* β) : ∀ (x : α), e.symm (e x) = x := equiv.symm_apply_apply (e.to_equiv) /-- a multiplicative equiv of monoids sends 1 to 1 (and is hence a monoid isomorphism) -/ @[simp, to_additive] def map_one {α β} [monoid α] [monoid β] (h : α ≃* β) : h 1 = 1 := by rw [←mul_one (h 1), ←h.apply_symm_apply 1, ←h.map_mul, one_mul] /-- A multiplicative bijection between two monoids is an isomorphism. -/ @[to_additive to_add_monoid_hom] def to_monoid_hom {α β} [monoid α] [monoid β] (h : α ≃* β) : (α →* β) := { to_fun := h, map_mul' := h.map_mul, map_one' := h.map_one } /-- A multiplicative bijection between two monoids is a monoid hom (deprecated -- use to_monoid_hom). -/ @[to_additive is_add_monoid_hom] instance is_monoid_hom {α β} [monoid α] [monoid β] (h : α ≃* β) : is_monoid_hom h := ⟨h.map_one⟩ /-- A multiplicative bijection between two groups is a group hom (deprecated -- use to_monoid_hom). -/ @[to_additive is_add_group_hom] instance is_group_hom {α β} [group α] [group β] (h : α ≃* β) : is_group_hom h := { map_mul := h.map_mul } end mul_equiv namespace units variables [monoid α] [monoid β] [monoid γ] (f : α → β) (g : β → γ) [is_monoid_hom f] [is_monoid_hom g] def map_equiv (h : α ≃* β) : units α ≃* units β := { 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 } end units structure ring_equiv (α β : Type*) [ring α] [ring β] extends α ≃ β := (hom : is_ring_hom to_fun) infix ` ≃r `:25 := ring_equiv namespace ring_equiv variables [ring α] [ring β] [ring γ] instance (h : α ≃r β) : is_ring_hom h.to_equiv := h.hom instance ring_equiv.is_ring_hom' (h : α ≃r β) : is_ring_hom h.to_fun := h.hom def to_mul_equiv (e : α ≃r β) : α ≃* β := { map_mul' := e.hom.map_mul, .. e.to_equiv } def to_add_equiv (e : α ≃r β) : α ≃+ β := { map_add' := e.hom.map_add, .. e.to_equiv } protected def refl (α : Type*) [ring α] : α ≃r α := { hom := is_ring_hom.id, .. equiv.refl α } protected def symm {α β : Type*} [ring α] [ring β] (e : α ≃r β) : β ≃r α := { hom := { map_one := e.to_mul_equiv.symm.map_one, map_mul := e.to_mul_equiv.symm.map_mul, map_add := e.to_add_equiv.symm.map_add }, .. e.to_equiv.symm } protected def trans {α β γ : Type*} [ring α] [ring β] [ring γ] (e₁ : α ≃r β) (e₂ : β ≃r γ) : α ≃r γ := { hom := is_ring_hom.comp _ _, .. e₁.to_equiv.trans e₂.to_equiv } instance symm.is_ring_hom {e : α ≃r β} : is_ring_hom e.to_equiv.symm := hom e.symm @[simp] lemma to_equiv_symm (e : α ≃r β) : e.symm.to_equiv = e.to_equiv.symm := rfl @[simp] lemma to_equiv_symm_apply (e : α ≃r β) (x : β) : e.symm.to_equiv x = e.to_equiv.symm x := rfl end ring_equiv
097ff4bad40e433279c789b1c63d04bd447808ee
1a61aba1b67cddccce19532a9596efe44be4285f
/hott/algebra/category/category.hlean
f055789a762da5a5fff57a22cb1fa2b22e72c5a3
[ "Apache-2.0" ]
permissive
eigengrau/lean
07986a0f2548688c13ba36231f6cdbee82abf4c6
f8a773be1112015e2d232661ce616d23f12874d0
refs/heads/master
1,610,939,198,566
1,441,352,386,000
1,441,352,494,000
41,903,576
0
0
null
1,441,352,210,000
1,441,352,210,000
null
UTF-8
Lean
false
false
2,481
hlean
/- Copyright (c) 2014 Jakob von Raumer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jakob von Raumer -/ import .iso open iso is_equiv eq is_trunc -- A category is a precategory extended by a witness -- that the function from paths to isomorphisms, -- is an equivalecnce. namespace category definition is_univalent [reducible] {ob : Type} (C : precategory ob) := Π(a b : ob), is_equiv (iso_of_eq : a = b → a ≅ b) structure category [class] (ob : Type) extends parent : precategory ob := mk' :: (iso_of_path_equiv : is_univalent parent) attribute category [multiple-instances] abbreviation iso_of_path_equiv := @category.iso_of_path_equiv definition category.mk [reducible] {ob : Type} (C : precategory ob) (H : Π (a b : ob), is_equiv (iso_of_eq : a = b → a ≅ b)) : category ob := precategory.rec_on C category.mk' H section basic variables {ob : Type} [C : category ob] include C -- Make iso_of_path_equiv a class instance -- TODO: Unsafe class instance? attribute iso_of_path_equiv [instance] definition eq_of_iso [reducible] {a b : ob} : a ≅ b → a = b := iso_of_eq⁻¹ᶠ definition iso_of_eq_eq_of_iso {a b : ob} (p : a ≅ b) : iso_of_eq (eq_of_iso p) = p := right_inv iso_of_eq p definition hom_of_eq_eq_of_iso {a b : ob} (p : a ≅ b) : hom_of_eq (eq_of_iso p) = to_hom p := ap to_hom !iso_of_eq_eq_of_iso definition inv_of_eq_eq_of_iso {a b : ob} (p : a ≅ b) : inv_of_eq (eq_of_iso p) = to_inv p := ap to_inv !iso_of_eq_eq_of_iso definition is_trunc_1_ob : is_trunc 1 ob := begin apply is_trunc_succ_intro, intro a b, fapply is_trunc_is_equiv_closed, exact (@eq_of_iso _ _ a b), apply is_equiv_inv, end end basic -- Bundled version of categories -- we don't use Category.carrier explicitly, but rather use Precategory.carrier (to_Precategory C) structure Category : Type := (carrier : Type) (struct : category carrier) attribute Category.struct [instance] [coercion] definition Category.to_Precategory [coercion] [reducible] (C : Category) : Precategory := Precategory.mk (Category.carrier C) C definition category.Mk [reducible] := Category.mk definition category.MK [reducible] (C : Precategory) (H : is_univalent C) : Category := Category.mk C (category.mk C H) definition Category.eta (C : Category) : Category.mk C C = C := Category.rec (λob c, idp) C end category