source
stringlengths
17
118
lean4
stringlengths
0
335k
.lake/packages/mathlib/Mathlib/Tactic/Linarith/Frontend.lean
import Mathlib.Control.Basic import Mathlib.Tactic.Linarith.Verification import Mathlib.Tactic.Linarith.Preprocessing import Mathlib.Tactic.Linarith.Oracle.SimplexAlgorithm import Mathlib.Tactic.Ring.Basic import Mathlib.Util.ElabWithoutMVars /-! # `linarith`: solving linear arithmetic goals `linarith` is a tactic for solving goals with linear arithmetic. Suppose we have a set of hypotheses in `n` variables `S = {a₁x₁ + a₂x₂ + ... + aₙxₙ R b₁x₁ + b₂x₂ + ... + bₙxₙ}`, where `R ∈ {<, ≤, =, ≥, >}`. Our goal is to determine if the inequalities in `S` are jointly satisfiable, that is, if there is an assignment of values to `x₁, ..., xₙ` such that every inequality in `S` is true. Specifically, we aim to show that they are *not* satisfiable. This amounts to proving a contradiction. If our goal is also a linear inequality, we negate it and move it to a hypothesis before trying to prove `False`. When the inequalities are over a dense linear order, `linarith` is a decision procedure: it will prove `False` if and only if the inequalities are unsatisfiable. `linarith` will also run on some types like `ℤ` that are not dense orders, but it will fail to prove `False` on some unsatisfiable problems. It will run over concrete types like `ℕ`, `ℚ`, and `ℝ`, as well as abstract types that are instances of `CommRing`, `LinearOrder` and `IsStrictOrderedRing`. ## Algorithm sketch First, the inequalities in the set `S` are rearranged into the form `tᵢ Rᵢ 0`, where `Rᵢ ∈ {<, ≤, =}` and each `tᵢ` is of the form `∑ cⱼxⱼ`. `linarith` uses an untrusted oracle to search for a certificate of unsatisfiability. The oracle searches for a list of natural number coefficients `kᵢ` such that `∑ kᵢtᵢ = 0`, where for at least one `i`, `kᵢ > 0` and `Rᵢ = <`. Given a list of such coefficients, `linarith` verifies that `∑ kᵢtᵢ = 0` using a normalization tactic such as `ring`. It proves that `∑ kᵢtᵢ < 0` by transitivity, since each component of the sum is either equal to, less than or equal to, or less than zero by hypothesis. This produces a contradiction. ## Preprocessing `linarith` does some basic preprocessing before running. Most relevantly, inequalities over natural numbers are cast into inequalities about integers, and rational division by numerals is canceled into multiplication. We do this so that we can guarantee the coefficients in the certificate are natural numbers, which allows the tactic to solve goals over types that are not fields. Preprocessors are allowed to branch, that is, to case split on disjunctions. `linarith` will succeed overall if it succeeds in all cases. This leads to exponential blowup in the number of `linarith` calls, and should be used sparingly. The default preprocessor set does not include case splits. ## Oracles There are two oracles that can be used in `linarith` so far. 1. **Fourier-Motzkin elimination.** This technique transforms a set of inequalities in `n` variables to an equisatisfiable set in `n - 1` variables. Once all variables have been eliminated, we conclude that the original set was unsatisfiable iff the comparison `0 < 0` is in the resulting set. While performing this elimination, we track the history of each derived comparison. This allows us to represent any comparison at any step as a positive combination of comparisons from the original set. In particular, if we derive `0 < 0`, we can find our desired list of coefficients by counting how many copies of each original comparison appear in the history. This oracle was historically implemented earlier, and is sometimes faster on small states, but it has [bugs](https://github.com/leanprover-community/mathlib4/issues/2717) and cannot handle large problems. You can use it with `linarith (oracle := .fourierMotzkin)`. 2. **Simplex Algorithm (default).** This oracle reduces the search for a unsatisfiability certificate to some Linear Programming problem. The problem is then solved by a standard Simplex Algorithm. We use [Bland's pivot rule](https://en.wikipedia.org/wiki/Bland%27s_rule) to guarantee that the algorithm terminates. The default version of the algorithm operates with sparse matrices as it is usually faster. You can invoke the dense version by `linarith (oracle := .simplexAlgorithmDense)`. ## Implementation details `linarith` homogenizes numerical constants: the expression `1` is treated as a variable `t₀`. Often `linarith` is called on goals that have comparison hypotheses over multiple types. This creates multiple `linarith` problems, each of which is handled separately; the goal is solved as soon as one problem is found to be contradictory. Disequality hypotheses `t ≠ 0` do not fit in this pattern. `linarith` will attempt to prove equality goals by splitting them into two weak inequalities and running twice. But it does not split disequality hypotheses, since this would lead to a number of runs exponential in the number of disequalities in the context. The oracle is very modular. It can easily be replaced with another function of type `List Comp → ℕ → MetaM ((Std.HashMap ℕ ℕ))`, which takes a list of comparisons and the largest variable index appearing in those comparisons, and returns a map from comparison indices to coefficients. An alternate oracle can be specified in the `LinarithConfig` object. A variant, `nlinarith`, adds an extra preprocessing step to handle some basic nonlinear goals. There is a hook in the `LinarithConfig` configuration object to add custom preprocessing routines. The certificate checking step is *not* by reflection. `linarith` converts the certificate into a proof term of type `False`. Some of the behavior of `linarith` can be inspected with the option `set_option trace.linarith true`. However, both oracles mainly runs outside the tactic monad, so we cannot trace intermediate steps there. ## File structure The components of `linarith` are spread between a number of files for the sake of organization. * `Lemmas.lean` contains proofs of some arithmetic lemmas that are used in preprocessing and in verification. * `Datatypes.lean` contains data structures that are used across multiple files, along with some useful auxiliary functions. * `Preprocessing.lean` contains functions used at the beginning of the tactic to transform hypotheses into a shape suitable for the main routine. * `Parsing.lean` contains functions used to compute the linear structure of an expression. * The `Oracle` folder contains files implementing the oracles that can be used to produce a certificate of unsatisfiability. * `Verification.lean` contains the certificate checking functions that produce a proof of `False`. * `Frontend.lean` contains the control methods and user-facing components of the tactic. ## Tags linarith, nlinarith, lra, nra, Fourier-Motzkin, linear arithmetic, linear programming -/ open Lean Elab Parser Tactic Meta open Batteries namespace Mathlib.Tactic.Linarith /-! ### Config objects The config object is defined in the frontend, instead of in `Datatypes.lean`, since the oracles must be in context to choose a default. -/ section /-- A configuration object for `linarith`. -/ structure LinarithConfig : Type where /-- Discharger to prove that a candidate linear combination of hypothesis is zero. -/ -- TODO There should be a def for this, rather than calling `evalTactic`? discharger : TacticM Unit := do evalTactic (← `(tactic| ring1)) -- We can't actually store a `Type` here, -- as we want `LinarithConfig : Type` rather than ` : Type 1`, -- so that we can define `elabLinarithConfig : Lean.Syntax → Lean.Elab.TermElabM LinarithConfig`. -- For now, we simply don't support restricting the type. -- (restrict_type : Option Type := none) /-- Prove goals which are not linear comparisons by first calling `exfalso`. -/ exfalso : Bool := true /-- Transparency mode for identifying atomic expressions in comparisons. -/ transparency : TransparencyMode := .reducible /-- Split conjunctions in hypotheses. -/ splitHypotheses : Bool := true /-- Split `≠` in hypotheses, by branching in cases `<` and `>`. -/ splitNe : Bool := false /-- If true, `linarith?` attempts to greedily remove unused hypotheses from its suggestion. -/ minimize : Bool := true /-- Override the list of preprocessors. -/ preprocessors : List GlobalBranchingPreprocessor := defaultPreprocessors /-- Specify an oracle for identifying candidate contradictions. `.simplexAlgorithmSparse`, `.simplexAlgorithmSparse`, and `.fourierMotzkin` are available. -/ oracle : CertificateOracle := .simplexAlgorithmSparse /-- `cfg.updateReducibility reduce_default` will change the transparency setting of `cfg` to `default` if `reduce_default` is true. In this case, it also sets the discharger to `ring!`, since this is typically needed when using stronger unification. -/ def LinarithConfig.updateReducibility (cfg : LinarithConfig) (reduce_default : Bool) : LinarithConfig := if reduce_default then { cfg with transparency := .default, discharger := do evalTactic (← `(tactic| ring1!)) } else cfg end /-! ### Control -/ /-- If `e` is a comparison `a R b` or the negation of a comparison `¬ a R b`, found in the target, `getContrLemma e` returns the name of a lemma that will change the goal to an implication, along with the type of `a` and `b`. For example, if `e` is `(a : ℕ) < b`, returns ``(`lt_of_not_ge, ℕ)``. -/ def getContrLemma (e : Expr) : MetaM (Name × Expr) := do match ← e.ineqOrNotIneq? with | (true, Ineq.lt, t, _) => pure (``lt_of_not_ge, t) | (true, Ineq.le, t, _) => pure (``le_of_not_gt, t) | (true, Ineq.eq, t, _) => pure (``eq_of_not_lt_of_not_gt, t) | (false, _, t, _) => pure (``Not.intro, t) /-- `applyContrLemma` inspects the target to see if it can be moved to a hypothesis by negation. For example, a goal `⊢ a ≤ b` can become `b < a ⊢ false`. If this is the case, it applies the appropriate lemma and introduces the new hypothesis. It returns the type of the terms in the comparison (e.g. the type of `a` and `b` above) and the newly introduced local constant. Otherwise returns `none`. -/ def applyContrLemma (g : MVarId) : MetaM (Option (Expr × Expr) × MVarId) := do try let (nm, tp) ← getContrLemma (← withReducible g.getType') let [g] ← g.apply (← mkConst' nm) | failure let (f, g) ← g.intro1P return (some (tp, .fvar f), g) catch _ => return (none, g) /-- A map of keys to values, where the keys are `Expr` up to defeq and one key can be associated to multiple values. -/ abbrev ExprMultiMap α := Array (Expr × List α) /-- Retrieves the list of values at a key, as well as the index of the key for later modification. (If the key is not in the map it returns `self.size` as the index.) -/ def ExprMultiMap.find {α : Type} (self : ExprMultiMap α) (k : Expr) : MetaM (Nat × List α) := do for h : i in [:self.size] do let (k', vs) := self[i] if ← isDefEq k' k then return (i, vs) return (self.size, []) /-- Insert a new value into the map at key `k`. This does a defeq check with all other keys in the map. -/ def ExprMultiMap.insert {α : Type} (self : ExprMultiMap α) (k : Expr) (v : α) : MetaM (ExprMultiMap α) := do for h : i in [:self.size] do if ← isDefEq self[i].1 k then return self.modify i fun (k, vs) => (k, v::vs) return self.push (k, [v]) /-- `partitionByTypeIdx l` takes a list `l` of pairs `(h, i)` where `h` is a proof of a comparison and `i` records the original position of `h`. The proofs are grouped by the type of the variables appearing in the comparison, e.g. `(a : ℚ) < 1` and `(b : ℤ) > c` will be separated. The resulting map associates each type with the list of `(h, i)` pairs over that type. -/ def partitionByTypeIdx (l : List (Expr × Nat)) : MetaM (ExprMultiMap (Expr × Nat)) := l.foldlM (fun m ⟨h, i⟩ => do m.insert (← typeOfIneqProof h) (h, i)) #[] /-- Given a list `ls` of pairs `(α, L)` where each `L` is a list of indexed proofs of comparisons over the type `α`, `findLinarithContradiction cfg g ls` tries each list in succession, invoking `linarith` until one produces a contradiction. It returns the resulting proof of `False` together with the indices of the hypotheses that had nonzero coefficients in the final certificate. -/ def findLinarithContradiction (cfg : LinarithConfig) (g : MVarId) (ls : List (Expr × List (Expr × Nat))) : MetaM (Expr × List Nat) := try ls.firstM (fun ⟨α, L⟩ => withTraceNode `linarith (return m!"{exceptEmoji ·} running on type {α}") do let (pf, idxs) ← proveFalseByLinarith cfg.transparency cfg.oracle cfg.discharger g (L.map Prod.fst) let idxs := idxs.map fun i => L[i]!.2 return (pf, idxs)) catch e => throwError "linarith failed to find a contradiction\n{g}\n{e.toMessageData}" /-- Given a list `hyps` of proofs of comparisons, `runLinarith cfg prefType g hyps` preprocesses `hyps` according to the list of preprocessors in `cfg`. This results in a list of branches (typically only one), each of which must succeed in order to close the goal. In each branch, the hypotheses are partitioned by type and `linarith` is run on each class in turn; one of these must succeed in order for `linarith` to succeed on the branch. If `prefType` is provided, the corresponding class is tried first. On success, the metavariable `g` is assigned and the function returns the indices of the original hypotheses that were used with nonzero coefficient in the final proof. -/ -- If it succeeds, the passed metavariable should have been assigned. def runLinarith (cfg : LinarithConfig) (prefType : Option Expr) (g : MVarId) (hyps : List Expr) : MetaM (List Nat) := do let singleProcess (g : MVarId) (hyps : List (Expr × Nat)) : MetaM (Expr × List Nat) := g.withContext do linarithTraceProofs s!"after preprocessing, linarith has {hyps.length} facts:" (hyps.map Prod.fst) let mut hyp_set ← partitionByTypeIdx hyps trace[linarith] "hypotheses appear in {hyp_set.size} different types" -- If we have a preferred type, strip it from `hyp_set` and prepare a handler with a custom -- trace message let pref : MetaM _ ← do if let some t := prefType then let (i, vs) ← hyp_set.find t hyp_set := hyp_set.eraseIdxIfInBounds i pure <| withTraceNode `linarith (return m!"{exceptEmoji ·} running on preferred type {t}") do let (pf, idxs) ← proveFalseByLinarith cfg.transparency cfg.oracle cfg.discharger g (vs.map Prod.fst) let idxs := idxs.map fun j => vs[j]!.2 return (pf, idxs) else pure failure pref <|> findLinarithContradiction cfg g hyp_set.toList let mut preprocessors := cfg.preprocessors if cfg.splitNe then preprocessors := Linarith.removeNe :: preprocessors if cfg.splitHypotheses then preprocessors := Linarith.splitConjunctions.globalize.branching :: preprocessors let branches ← preprocess preprocessors g hyps let mut used : List Nat := [] for (g, es) in branches do let esIdx := es.zipIdx let (r, idxs) ← singleProcess g esIdx g.assign r used := idxs ++ used -- Verify that we closed the goal. Failure here should only result from a bad `Preprocessor`. (Expr.mvar g).ensureHasNoMVars return used.eraseDups -- /-- -- `filterHyps restr_type hyps` takes a list of proofs of comparisons `hyps`, and filters it -- to only those that are comparisons over the type `restr_type`. -- -/ -- def filterHyps (restr_type : Expr) (hyps : List Expr) : MetaM (List Expr) := -- hyps.filterM (fun h => do -- let ht ← inferType h -- match getContrLemma ht with -- | some (_, htype) => isDefEq htype restr_type -- | none => return false) /-- `linarithUsedHyps only_on hyps cfg g` runs `linarith` with the supplied hypotheses. It fails if the goal cannot be closed. When successful, it returns the subset of `hyps` that were actually used (i.e. had a nonzero coefficient) in the final certificate. * `hyps` is a list of proofs of comparisons to include in the search. * If `only_on` is true, the search will be restricted to `hyps`. Otherwise it will use all comparisons in the local context. * If `cfg.transparency := semireducible`, it will unfold semireducible definitions when trying to match atomic expressions. -/ partial def linarithUsedHyps (only_on : Bool) (hyps : List Expr) (cfg : LinarithConfig := {}) (g : MVarId) : MetaM (List Expr) := g.withContext do -- if the target is an equality, we run `linarith` twice, to prove ≤ and ≥. if (← whnfR (← instantiateMVars (← g.getType))).isEq then trace[linarith] "target is an equality: splitting" if let some [g₁, g₂] ← try? (g.apply (← mkConst' ``eq_of_not_lt_of_not_gt)) then let h₁ ← withTraceNode `linarith (return m!"{exceptEmoji ·} proving ≥") <| linarithUsedHyps only_on hyps cfg g₁ let h₂ ← withTraceNode `linarith (return m!"{exceptEmoji ·} proving ≤") <| linarithUsedHyps only_on hyps cfg g₂ return h₁ ++ h₂ /- If we are proving a comparison goal (and not just `False`), we consider the type of the elements in the comparison to be the "preferred" type. That is, if we find comparison hypotheses in multiple types, we will run `linarith` on the goal type first. In this case we also receive a new variable from moving the goal to a hypothesis. Otherwise, there is no preferred type and no new variable; we simply change the goal to `False`. -/ let (g, target_type, new_var) ← match ← applyContrLemma g with | (none, g) => if cfg.exfalso then trace[linarith] "using exfalso" pure (← g.exfalso, none, none) else pure (g, none, none) | (some (t, v), g) => pure (g, some t, some v) g.withContext do -- set up the list of hypotheses, considering the `only_on` and `restrict_type` options let hyps ← (if only_on then return new_var.toList ++ hyps else return (← getLocalHyps).toList ++ hyps) -- TODO in mathlib3 we could specify a restriction to a single type. -- I haven't done that here because I don't know how to store a `Type` in `LinarithConfig`. -- There's only one use of the `restrict_type` configuration option in mathlib3, -- and it can be avoided just by using `linarith only`. linarithTraceProofs "linarith is running on the following hypotheses:" hyps let usedIdxs ← runLinarith cfg target_type g hyps let used := usedIdxs.filterMap (hyps[·]?) let used := match new_var with | some nv => used.filter (fun h => !(h == nv)) | none => used return used /-- Run the core `linarith` procedure on the goal `g` using the hypotheses `hyps`. If `only_on` is true, the search is restricted to `hyps`; otherwise all suitable local hypotheses are considered. This is the workhorse behind the user-facing `linarith` tactic. -/ partial def linarith (only_on : Bool) (hyps : List Expr) (cfg : LinarithConfig := {}) (g : MVarId) : MetaM Unit := do discard <| linarithUsedHyps only_on hyps cfg g end Linarith /-! ### User facing functions -/ open Syntax /-- Syntax for the arguments of `linarith`, after the optional `!`. -/ syntax linarithArgsRest := optConfig (&" only")? (" [" term,* "]")? /-- `linarith` attempts to find a contradiction between hypotheses that are linear (in)equalities. Equivalently, it can prove a linear inequality by assuming its negation and proving `False`. In theory, `linarith` should prove any goal that is true in the theory of linear arithmetic over the rationals. While there is some special handling for non-dense orders like `Nat` and `Int`, this tactic is not complete for these theories and will not prove every true goal. It will solve goals over arbitrary types that instantiate `CommRing`, `LinearOrder` and `IsStrictOrderedRing`. An example: ```lean example (x y z : ℚ) (h1 : 2*x < 3*y) (h2 : -4*x + 2*z < 0) (h3 : 12*y - 4* z < 0) : False := by linarith ``` `linarith` will use all appropriate hypotheses and the negation of the goal, if applicable. Disequality hypotheses require case splitting and are not normally considered (see the `splitNe` option below). `linarith [t1, t2, t3]` will additionally use proof terms `t1, t2, t3`. `linarith only [h1, h2, h3, t1, t2, t3]` will use only the goal (if relevant), local hypotheses `h1`, `h2`, `h3`, and proofs `t1`, `t2`, `t3`. It will ignore the rest of the local context. `linarith!` will use a stronger reducibility setting to try to identify atoms. For example, ```lean example (x : ℚ) : id x ≥ x := by linarith ``` will fail, because `linarith` will not identify `x` and `id x`. `linarith!` will. This can sometimes be expensive. `linarith (config := { .. })` takes a config object with five optional arguments: * `discharger` specifies a tactic to be used for reducing an algebraic equation in the proof stage. The default is `ring`. Other options include `simp` for basic problems. * `transparency` controls how hard `linarith` will try to match atoms to each other. By default it will only unfold `reducible` definitions. * If `splitHypotheses` is true, `linarith` will split conjunctions in the context into separate hypotheses. * If `splitNe` is `true`, `linarith` will case split on disequality hypotheses. For a given `x ≠ y` hypothesis, `linarith` is run with both `x < y` and `x > y`, and so this runs linarith exponentially many times with respect to the number of disequality hypotheses. (`false` by default.) * If `exfalso` is `false`, `linarith` will fail when the goal is neither an inequality nor `False`. (`true` by default.) * If `minimize` is `false`, `linarith?` will report all hypotheses appearing in its initial proof without attempting to drop redundancies. (`true` by default.) * `restrict_type` (not yet implemented in mathlib4) will only use hypotheses that are inequalities over `tp`. This is useful if you have e.g. both integer- and rational-valued inequalities in the local context, which can sometimes confuse the tactic. A variant, `nlinarith`, does some basic preprocessing to handle some nonlinear goals. The option `set_option trace.linarith true` will trace certain intermediate stages of the `linarith` routine. -/ syntax (name := linarith) "linarith" "!"? linarithArgsRest : tactic /-- `linarith?` behaves like `linarith` but, on success, it prints a suggestion of the form `linarith only [...]` listing a minimized set of hypotheses used in the final proof. Use `linarith?!` for the higher-reducibility variant and set the `minimize` flag in the configuration to control whether greedy minimization is performed. -/ syntax (name := linarith?) "linarith?" "!"? linarithArgsRest : tactic @[inherit_doc linarith] macro "linarith!" rest:linarithArgsRest : tactic => `(tactic| linarith ! $rest:linarithArgsRest) @[inherit_doc linarith?] macro "linarith?!" rest:linarithArgsRest : tactic => `(tactic| linarith? ! $rest:linarithArgsRest) /-- An extension of `linarith` with some preprocessing to allow it to solve some nonlinear arithmetic problems. (Based on Coq's `nra` tactic.) See `linarith` for the available syntax of options, which are inherited by `nlinarith`; that is, `nlinarith!` and `nlinarith only [h1, h2]` all work as in `linarith`. The preprocessing is as follows: * For every subterm `a ^ 2` or `a * a` in a hypothesis or the goal, the assumption `0 ≤ a ^ 2` or `0 ≤ a * a` is added to the context. * For every pair of hypotheses `a1 R1 b1`, `a2 R2 b2` in the context, `R1, R2 ∈ {<, ≤, =}`, the assumption `0 R' (b1 - a1) * (b2 - a2)` is added to the context (non-recursively), where `R ∈ {<, ≤, =}` is the appropriate comparison derived from `R1, R2`. -/ syntax (name := nlinarith) "nlinarith" "!"? linarithArgsRest : tactic @[inherit_doc nlinarith] macro "nlinarith!" rest:linarithArgsRest : tactic => `(tactic| nlinarith ! $rest:linarithArgsRest) /-- Allow elaboration of `LinarithConfig` arguments to tactics. -/ declare_config_elab elabLinarithConfig Linarith.LinarithConfig elab_rules : tactic | `(tactic| linarith $[!%$bang]? $cfg:optConfig $[only%$o]? $[[$args,*]]?) => withMainContext do let args ← ((args.map (TSepArray.getElems)).getD {}).mapM (elabTermWithoutNewMVars `linarith) let cfg := (← elabLinarithConfig cfg).updateReducibility bang.isSome commitIfNoEx do liftMetaFinishingTactic <| Linarith.linarith o.isSome args.toList cfg elab_rules : tactic | `(tactic| linarith?%$tk $[!%$bang]? $cfg:optConfig $[only%$o]? $[[$args,*]]?) => withMainContext do let args ← ((args.map (TSepArray.getElems)).getD {}).mapM (elabTermWithoutNewMVars `linarith) let cfg := (← elabLinarithConfig cfg).updateReducibility bang.isSome let g ← getMainGoal let st ← saveState try let used₀ ← Linarith.linarithUsedHyps o.isSome args.toList cfg g -- Check that all used hypotheses are fvars (not arbitrary terms) if used₀.any (fun e => e.fvarId?.isNone) then throwError "linarith? currently only supports named hypothesis, not terms" let used ← if cfg.minimize then let rec minimize (hs : List Expr) (i : Nat) : TacticM (List Expr) := do if _h : i < hs.length then let rest := hs.eraseIdx i st.restore try let _ ← Linarith.linarith true rest cfg g minimize rest i catch _ => minimize hs (i+1) else return hs minimize used₀ 0 else pure used₀ st.restore discard <| Linarith.linarith true used cfg g replaceMainGoal [] -- TODO: we should check for, and deal with, shadowed names here. let idsList ← used.mapM fun e => do pure (Lean.mkIdent (← e.fvarId!.getUserName)) let sugg ← `(tactic| linarith only [$(idsList.toArray),*]) Lean.Meta.Tactic.TryThis.addSuggestion tk sugg catch e => discard <| st.restore throw e -- TODO restore this when `add_tactic_doc` is ported -- add_tactic_doc -- { name := "linarith", -- category := doc_category.tactic, -- decl_names := [`tactic.interactive.linarith], -- tags := ["arithmetic", "decision procedure", "finishing"] } open Linarith elab_rules : tactic | `(tactic| nlinarith $[!%$bang]? $cfg:optConfig $[only%$o]? $[[$args,*]]?) => withMainContext do let args ← ((args.map (TSepArray.getElems)).getD {}).mapM (elabTermWithoutNewMVars `nlinarith) let cfg := (← elabLinarithConfig cfg).updateReducibility bang.isSome let cfg := { cfg with preprocessors := cfg.preprocessors.concat nlinarithExtras } commitIfNoEx do liftMetaFinishingTactic <| Linarith.linarith o.isSome args.toList cfg -- TODO restore this when `add_tactic_doc` is ported -- add_tactic_doc -- { name := "nlinarith", -- category := doc_category.tactic, -- decl_names := [`tactic.interactive.nlinarith], -- tags := ["arithmetic", "decision procedure", "finishing"] } end Mathlib.Tactic
.lake/packages/mathlib/Mathlib/Tactic/Linarith/Oracle/SimplexAlgorithm.lean
import Mathlib.Tactic.Linarith.Datatypes import Mathlib.Tactic.Linarith.Oracle.SimplexAlgorithm.PositiveVector /-! # The oracle based on Simplex Algorithm This file contains hooks to enable the use of the Simplex Algorithm in `linarith`. The algorithm's entry point is the function `Linarith.SimplexAlgorithm.findPositiveVector`. See the file `PositiveVector.lean` for details of how the procedure works. -/ namespace Mathlib.Tactic.Linarith.SimplexAlgorithm /-- Preprocess the goal to pass it to `Linarith.SimplexAlgorithm.findPositiveVector`. -/ def preprocess (matType : ℕ → ℕ → Type) [UsableInSimplexAlgorithm matType] (hyps : List Comp) (maxVar : ℕ) : matType (maxVar + 1) (hyps.length) × List Nat := let values : List (ℕ × ℕ × ℚ) := hyps.foldlIdx (init := []) fun idx cur comp => cur ++ comp.coeffs.map fun (var, c) => (var, idx, c) let strictIndexes := hyps.findIdxs (·.str == Ineq.lt) (ofValues values, strictIndexes) /-- Extract the certificate from the `vec` found by `Linarith.SimplexAlgorithm.findPositiveVector`. -/ def postprocess (vec : Array ℚ) : Std.HashMap ℕ ℕ := let common_den : ℕ := vec.foldl (fun acc item => acc.lcm item.den) 1 let vecNat : Array ℕ := vec.map (fun x : ℚ => (x * common_den).floor.toNat) (∅ : Std.HashMap Nat Nat).insertMany <| vecNat.zipIdx.filterMap fun ⟨item, idx⟩ => if item != 0 then some (idx, item) else none end SimplexAlgorithm open SimplexAlgorithm /-- An oracle that uses the Simplex Algorithm. -/ def CertificateOracle.simplexAlgorithmSparse : CertificateOracle where produceCertificate hyps maxVar := do let (A, strictIndexes) := preprocess SparseMatrix hyps maxVar let vec ← findPositiveVector A strictIndexes return postprocess vec /-- The same oracle as `CertificateOracle.simplexAlgorithmSparse`, but uses dense matrices. Works faster on dense states. -/ def CertificateOracle.simplexAlgorithmDense : CertificateOracle where produceCertificate hyps maxVar := do let (A, strictIndexes) := preprocess DenseMatrix hyps maxVar let vec ← findPositiveVector A strictIndexes return postprocess vec end Mathlib.Tactic.Linarith
.lake/packages/mathlib/Mathlib/Tactic/Linarith/Oracle/FourierMotzkin.lean
import Batteries.Lean.HashMap import Mathlib.Tactic.Linarith.Datatypes /-! # The Fourier-Motzkin elimination procedure The Fourier-Motzkin procedure is a variable elimination method for linear inequalities. <https://en.wikipedia.org/wiki/Fourier%E2%80%93Motzkin_elimination> Given a set of linear inequalities `comps = {tᵢ Rᵢ 0}`, we aim to eliminate a single variable `a` from the set. We partition `comps` into `comps_pos`, `comps_neg`, and `comps_zero`, where `comps_pos` contains the comparisons `tᵢ Rᵢ 0` in which the coefficient of `a` in `tᵢ` is positive, and similar. For each pair of comparisons `tᵢ Rᵢ 0 ∈ comps_pos`, `tⱼ Rⱼ 0 ∈ comps_neg`, we compute coefficients `vᵢ, vⱼ ∈ ℕ` such that `vᵢ*tᵢ + vⱼ*tⱼ` cancels out `a`. We collect these sums `vᵢ*tᵢ + vⱼ*tⱼ R' 0` in a set `S` and set `comps' = S ∪ comps_zero`, a new set of comparisons in which `a` has been eliminated. Theorem: `comps` and `comps'` are equisatisfiable. We recursively eliminate all variables from the system. If we derive an empty clause `0 < 0`, we conclude that the original system was unsatisfiable. -/ open Batteries open Std (format ToFormat TreeSet) namespace Std.TreeSet variable {α : Type*} {cmp} /-- `O(n₂ * log (n₁ + n₂))`. Merges the maps `t₁` and `t₂`. If equal keys exist in both, the key from `t₂` is preferred. -/ def union (t₁ t₂ : TreeSet α cmp) : TreeSet α cmp := t₂.foldl .insert t₁ instance : Union (TreeSet α cmp) := ⟨TreeSet.union⟩ /-- `O(n₁ * (log n₁ + log n₂))`. Constructs the set of all elements of `t₁` that are not in `t₂`. -/ def sdiff (t₁ t₂ : TreeSet α cmp) : TreeSet α cmp := t₁.filter (!t₂.contains ·) instance : SDiff (TreeSet α cmp) := ⟨TreeSet.sdiff⟩ end Std.TreeSet namespace Mathlib.Tactic.Linarith /-! ### Datatypes The `CompSource` and `PComp` datatypes are specific to the FM elimination routine; they are not shared with other components of `linarith`. -/ /-- `CompSource` tracks the source of a comparison. The atomic source of a comparison is an assumption, indexed by a natural number. Two comparisons can be added to produce a new comparison, and one comparison can be scaled by a natural number to produce a new comparison. -/ inductive CompSource : Type | assump : Nat → CompSource | add : CompSource → CompSource → CompSource | scale : Nat → CompSource → CompSource deriving Inhabited /-- Given a `CompSource` `cs`, `cs.flatten` maps an assumption index to the number of copies of that assumption that appear in the history of `cs`. For example, suppose `cs` is produced by scaling assumption 2 by 5, and adding to that the sum of assumptions 1 and 2. `cs.flatten` maps `1 ↦ 1, 2 ↦ 6`. -/ def CompSource.flatten : CompSource → Std.HashMap Nat Nat | (CompSource.assump n) => (∅ : Std.HashMap Nat Nat).insert n 1 | (CompSource.add c1 c2) => (CompSource.flatten c1).mergeWith (fun _ b b' => b + b') (CompSource.flatten c2) | (CompSource.scale n c) => (CompSource.flatten c).map (fun _ v => v * n) /-- Formats a `CompSource` for printing. -/ def CompSource.toString : CompSource → String | (CompSource.assump e) => ToString.toString e | (CompSource.add c1 c2) => CompSource.toString c1 ++ " + " ++ CompSource.toString c2 | (CompSource.scale n c) => ToString.toString n ++ " * " ++ CompSource.toString c instance : ToFormat CompSource := ⟨fun a => CompSource.toString a⟩ /-- A `PComp` stores a linear comparison `Σ cᵢ*xᵢ R 0`, along with information about how this comparison was derived. The original expressions fed into `linarith` are each assigned a unique natural number label. The *historical set* `PComp.history` stores the labels of expressions that were used in deriving the current `PComp`. Variables are also indexed by natural numbers. The sets `PComp.effective`, `PComp.implicit`, and `PComp.vars` contain variable indices. * `PComp.vars` contains the variables that appear in any inequality in the historical set. * `PComp.effective` contains the variables that have been effectively eliminated from `PComp`. A variable `n` is said to be *effectively eliminated* in `p : PComp` if the elimination of `n` produced at least one of the ancestors of `p` (or `p` itself). * `PComp.implicit` contains the variables that have been implicitly eliminated from `PComp`. A variable `n` is said to be *implicitly eliminated* in `p` if it satisfies the following properties: - `n` appears in some inequality in the historical set (i.e. in `p.vars`). - `n` does not appear in `p.c.vars` (i.e. it has been eliminated). - `n` was not effectively eliminated. We track these sets in order to compute whether the history of a `PComp` is *minimal*. Checking this directly is expensive, but effective approximations can be defined in terms of these sets. During the variable elimination process, a `PComp` with non-minimal history can be discarded. -/ structure PComp : Type where /-- The comparison `Σ cᵢ*xᵢ R 0`. -/ c : Comp /-- We track how the comparison was constructed by adding and scaling previous comparisons, back to the original assumptions. -/ src : CompSource /-- The set of original assumptions which have been used in constructing this comparison. -/ history : TreeSet ℕ Ord.compare /-- The variables which have been *effectively eliminated*, i.e. by running the elimination algorithm on that variable. -/ effective : TreeSet ℕ Ord.compare /-- The variables which have been *implicitly eliminated*. These are variables that appear in the historical set, do not appear in `c` itself, and are not in `effective. -/ implicit : TreeSet ℕ Ord.compare /-- The union of all variables appearing in those original assumptions which appear in the `history` set. -/ vars : TreeSet ℕ Ord.compare /-- Any comparison whose history is not minimal is redundant, and need not be included in the new set of comparisons. `elimedGE : ℕ` is a natural number such that all variables with index ≥ `elimedGE` have been removed from the system. This test is an overapproximation to minimality. It gives necessary but not sufficient conditions. If the history of `c` is minimal, then `c.maybeMinimal` is true, but `c.maybeMinimal` may also be true for some `c` with non-minimal history. Thus, if `c.maybeMinimal` is false, `c` is known not to be minimal and must be redundant. See https://doi.org/10.1016/B978-0-444-88771-9.50019-2 (Theorem 13). The condition described there considers only implicitly eliminated variables that have been officially eliminated from the system. This is not the case for every implicitly eliminated variable. Consider eliminating `z` from `{x + y + z < 0, x - y - z < 0}`. The result is the set `{2*x < 0}`; `y` is implicitly but not officially eliminated. This implementation of Fourier-Motzkin elimination processes variables in decreasing order of indices. Immediately after a step that eliminates variable `k`, variable `k'` has been eliminated iff `k' ≥ k`. Thus we can compute the intersection of officially and implicitly eliminated variables by taking the set of implicitly eliminated variables with indices ≥ `elimedGE`. -/ def PComp.maybeMinimal (c : PComp) (elimedGE : ℕ) : Bool := c.history.size ≤ 1 + ((c.implicit.filter (· ≥ elimedGE)).union c.effective).size /-- The `src : CompSource` field is ignored when comparing `PComp`s. Two `PComp`s proving the same comparison, with different sources, are considered equivalent. -/ def PComp.cmp (p1 p2 : PComp) : Ordering := p1.c.cmp p2.c /-- `PComp.scale c n` scales the coefficients of `c` by `n` and notes this in the `CompSource`. -/ def PComp.scale (c : PComp) (n : ℕ) : PComp := { c with c := c.c.scale n, src := c.src.scale n } /-- `PComp.add c1 c2 elimVar` creates the result of summing the linear comparisons `c1` and `c2`, during the process of eliminating the variable `elimVar`. The computation assumes, but does not enforce, that `elimVar` appears in both `c1` and `c2` and does not appear in the sum. Computing the sum of the two comparisons is easy; the complicated details lie in tracking the additional fields of `PComp`. * The historical set `pcomp.history` of `c1 + c2` is the union of the two historical sets. * `vars` is the union of `c1.vars` and `c2.vars`. * The effectively eliminated variables of `c1 + c2` are the union of the two effective sets, with `elim_var` inserted. * The implicitly eliminated variables of `c1 + c2` are those that appear in `vars` but not `c.vars` or `effective`. (Note that the description of the implicitly eliminated variables of `c1 + c2` in the algorithm described in Section 6 of https://doi.org/10.1016/B978-0-444-88771-9.50019-2 seems to be wrong: that says it should be `(c1.implicit.union c2.implicit).sdiff explicit`. Since the implicitly eliminated sets start off empty for the assumption, this formula would leave them always empty.) -/ def PComp.add (c1 c2 : PComp) (elimVar : ℕ) : PComp := let c := c1.c.add c2.c let src := c1.src.add c2.src let history := c1.history.union c2.history let vars := c1.vars.union c2.vars let effective := (c1.effective.union c2.effective).insert elimVar let implicit := (vars.sdiff (.ofList c.vars _)).sdiff effective ⟨c, src, history, effective, implicit, vars⟩ /-- `PComp.assump c n` creates a `PComp` whose comparison is `c` and whose source is `CompSource.assump n`, that is, `c` is derived from the `n`th hypothesis. The history is the singleton set `{n}`. No variables have been eliminated (effectively or implicitly). -/ def PComp.assump (c : Comp) (n : ℕ) : PComp where c := c src := CompSource.assump n history := {n} effective := .empty implicit := .empty vars := .ofList c.vars _ instance : ToFormat PComp := ⟨fun p => format p.c.coeffs ++ toString p.c.str ++ "0"⟩ instance : ToString PComp := ⟨fun p => toString p.c.coeffs ++ toString p.c.str ++ "0"⟩ /-- A collection of comparisons. -/ abbrev PCompSet := TreeSet PComp PComp.cmp /-! ### Elimination procedure -/ /-- If `c1` and `c2` both contain variable `a` with opposite coefficients, produces `v1` and `v2` such that `a` has been cancelled in `v1*c1 + v2*c2`. -/ def elimVar (c1 c2 : Comp) (a : ℕ) : Option (ℕ × ℕ) := let v1 := c1.coeffOf a let v2 := c2.coeffOf a if v1 * v2 < 0 then let vlcm := Nat.lcm v1.natAbs v2.natAbs some ⟨vlcm / v1.natAbs, vlcm / v2.natAbs⟩ else none /-- `pelimVar p1 p2` calls `elimVar` on the `Comp` components of `p1` and `p2`. If this returns `v1` and `v2`, it creates a new `PComp` equal to `v1*p1 + v2*p2`, and tracks this in the `CompSource`. -/ def pelimVar (p1 p2 : PComp) (a : ℕ) : Option PComp := do let (n1, n2) ← elimVar p1.c p2.c a return (p1.scale n1).add (p2.scale n2) a /-- A `PComp` represents a contradiction if its `Comp` field represents a contradiction. -/ def PComp.isContr (p : PComp) : Bool := p.c.isContr /-- `elimWithSet a p comps` collects the result of calling `pelimVar p p' a` for every `p' ∈ comps`. -/ def elimWithSet (a : ℕ) (p : PComp) (comps : PCompSet) : PCompSet := comps.foldl (fun s pc => match pelimVar p pc a with | some pc => if pc.maybeMinimal a then s.insert pc else s | none => s) TreeSet.empty /-- The state for the elimination monad. * `maxVar`: the largest variable index that has not been eliminated. * `comps`: a set of comparisons The elimination procedure proceeds by eliminating variable `v` from `comps` progressively in decreasing order. -/ structure LinarithData : Type where /-- The largest variable index that has not been (officially) eliminated. -/ maxVar : ℕ /-- The set of comparisons. -/ comps : PCompSet /-- The linarith monad extends an exceptional monad with a `LinarithData` state. An exception produces a contradictory `PComp`. -/ abbrev LinarithM : Type → Type := StateT LinarithData (ExceptT PComp Lean.Core.CoreM) /-- Returns the current max variable. -/ def getMaxVar : LinarithM ℕ := LinarithData.maxVar <$> get /-- Return the current comparison set. -/ def getPCompSet : LinarithM PCompSet := LinarithData.comps <$> get /-- Throws an exception if a contradictory `PComp` is contained in the current state. -/ def validate : LinarithM Unit := do match (← getPCompSet).toList.find? (fun p : PComp => p.isContr) with | none => return () | some c => throwThe _ c /-- Updates the current state with a new max variable and comparisons, and calls `validate` to check for a contradiction. -/ def update (maxVar : ℕ) (comps : PCompSet) : LinarithM Unit := do StateT.set ⟨maxVar, comps⟩ validate /-- `splitSetByVarSign a comps` partitions the set `comps` into three parts. * `pos` contains the elements of `comps` in which `a` has a positive coefficient. * `neg` contains the elements of `comps` in which `a` has a negative coefficient. * `notPresent` contains the elements of `comps` in which `a` has coefficient 0. Returns `(pos, neg, notPresent)`. -/ def splitSetByVarSign (a : ℕ) (comps : PCompSet) : PCompSet × PCompSet × PCompSet := comps.foldl (fun ⟨pos, neg, notPresent⟩ pc => let n := pc.c.coeffOf a if n > 0 then ⟨pos.insert pc, neg, notPresent⟩ else if n < 0 then ⟨pos, neg.insert pc, notPresent⟩ else ⟨pos, neg, notPresent.insert pc⟩) ⟨TreeSet.empty, TreeSet.empty, TreeSet.empty⟩ /-- `elimVarM a` performs one round of Fourier-Motzkin elimination, eliminating the variable `a` from the `linarith` state. -/ def elimVarM (a : ℕ) : LinarithM Unit := do let vs ← getMaxVar if (a ≤ vs) then Lean.Core.checkSystem decl_name%.toString let ⟨pos, neg, notPresent⟩ := splitSetByVarSign a (← getPCompSet) update (vs - 1) (← pos.foldlM (fun s p => do Lean.Core.checkSystem decl_name%.toString pure (s.union (elimWithSet a p neg))) notPresent) else pure () /-- `elimAllVarsM` eliminates all variables from the linarith state, leaving it with a set of ground comparisons. If this succeeds without exception, the original `linarith` state is consistent. -/ def elimAllVarsM : LinarithM Unit := do for i in (List.range ((← getMaxVar) + 1)).reverse do elimVarM i /-- `mkLinarithData hyps vars` takes a list of hypotheses and the largest variable present in those hypotheses. It produces an initial state for the elimination monad. -/ def mkLinarithData (hyps : List Comp) (maxVar : ℕ) : LinarithData := ⟨maxVar, .ofList (hyps.mapIdx fun n cmp => PComp.assump cmp n) _⟩ /-- An oracle that uses Fourier-Motzkin elimination. -/ def CertificateOracle.fourierMotzkin : CertificateOracle where produceCertificate hyps maxVar := do let linarithData := mkLinarithData hyps maxVar let result ← (ExceptT.run (StateT.run (do validate; elimAllVarsM : LinarithM Unit) linarithData) :) match result with | (Except.ok _) => failure | (Except.error contr) => return contr.src.flatten end Mathlib.Tactic.Linarith
.lake/packages/mathlib/Mathlib/Tactic/Linarith/Oracle/SimplexAlgorithm/Gauss.lean
import Mathlib.Tactic.Linarith.Oracle.SimplexAlgorithm.Datatypes /-! # Gaussian Elimination algorithm The first step of `Linarith.SimplexAlgorithm.findPositiveVector` is finding initial feasible solution which is done by standard Gaussian Elimination algorithm implemented in this file. -/ namespace Mathlib.Tactic.Linarith.SimplexAlgorithm.Gauss /-- The monad for the Gaussian Elimination algorithm. -/ abbrev GaussM (n m : Nat) (matType : Nat → Nat → Type) := StateT (matType n m) Lean.CoreM variable {n m : Nat} {matType : Nat → Nat → Type} [UsableInSimplexAlgorithm matType] /-- Finds the first row starting from the `rowStart` with nonzero element in the column `col`. -/ def findNonzeroRow (rowStart col : Nat) : GaussM n m matType <| Option Nat := do for i in [rowStart:n] do if (← get)[(i, col)]! != 0 then return i return none /-- Implementation of `getTableau` in `GaussM` monad. -/ def getTableauImp : GaussM n m matType <| Tableau matType := do let mut free : Array Nat := #[] let mut basic : Array Nat := #[] let mut row : Nat := 0 let mut col : Nat := 0 while row < n && col < m do Lean.Core.checkSystem decl_name%.toString match ← findNonzeroRow row col with | none => free := free.push col col := col + 1 continue | some rowToSwap => modify fun mat => swapRows mat row rowToSwap modify fun mat => divideRow mat row mat[(row, col)]! for i in [:n] do if i == row then continue let coef := (← get)[(i, col)]! if coef != 0 then modify fun mat => subtractRow mat row i coef basic := basic.push col row := row + 1 col := col + 1 for i in [col:m] do free := free.push i let ansMatrix : matType basic.size free.size := ← do let vals := getValues (← get) |>.filterMap fun (i, j, v) => if j == basic[i]! then none else some (i, free.findIdx? (· == j) |>.get!, -v) return ofValues vals return ⟨basic, free, ansMatrix⟩ /-- Given matrix `A`, solves the linear equation `A x = 0` and returns the solution as a tableau where some variables are free and others (basic) variable are expressed as linear combinations of the free ones. -/ def getTableau (A : matType n m) : Lean.CoreM (Tableau matType) := do return (← getTableauImp.run A).fst end Mathlib.Tactic.Linarith.SimplexAlgorithm.Gauss
.lake/packages/mathlib/Mathlib/Tactic/Linarith/Oracle/SimplexAlgorithm/SimplexAlgorithm.lean
import Mathlib.Tactic.Linarith.Oracle.SimplexAlgorithm.Datatypes /-! # Simplex Algorithm To obtain required vector in `Linarith.SimplexAlgorithm.findPositiveVector` we run the Simplex Algorithm. We use Bland's rule for pivoting, which guarantees that the algorithm terminates. -/ namespace Mathlib.Tactic.Linarith.SimplexAlgorithm /-- An exception in the `SimplexAlgorithmM` monad. -/ inductive SimplexAlgorithmException /-- The solution is infeasible. -/ | infeasible : SimplexAlgorithmException /-- The monad for the Simplex Algorithm. -/ abbrev SimplexAlgorithmM (matType : Nat → Nat → Type) [UsableInSimplexAlgorithm matType] := ExceptT SimplexAlgorithmException <| StateT (Tableau matType) Lean.CoreM variable {matType : Nat → Nat → Type} [UsableInSimplexAlgorithm matType] /-- Given indexes `exitIdx` and `enterIdx` of exiting and entering variables in the `basic` and `free` arrays, performs pivot operation, i.e. expresses one through the other and makes the free one basic and vice versa. -/ def doPivotOperation (exitIdx enterIdx : Nat) : SimplexAlgorithmM matType Unit := modify fun s : Tableau matType => Id.run do let mut mat := s.mat let intersectCoef := mat[(exitIdx, enterIdx)]! for i in [:s.basic.size] do if i == exitIdx then continue let coef := mat[(i, enterIdx)]! / intersectCoef if coef != 0 then mat := subtractRow mat exitIdx i coef mat := setElem mat i enterIdx coef mat := setElem mat exitIdx enterIdx (-1) mat := divideRow mat exitIdx (-intersectCoef) let newBasic := s.basic.set! exitIdx s.free[enterIdx]! let newFree := s.free.set! enterIdx s.basic[exitIdx]! have hb : newBasic.size = s.basic.size := by apply Array.size_setIfInBounds have hf : newFree.size = s.free.size := by apply Array.size_setIfInBounds return (⟨newBasic, newFree, hb ▸ hf ▸ mat⟩ : Tableau matType) /-- Check if the solution is found: the objective function is positive and all basic variables are nonnegative. -/ def checkSuccess : SimplexAlgorithmM matType Bool := do let lastIdx := (← get).free.size - 1 return (← get).mat[(0, lastIdx)]! > 0 && (← (← get).basic.size.allM (fun i _ => do return (← get).mat[(i, lastIdx)]! ≥ 0)) /-- Chooses an entering variable: among the variables with a positive coefficient in the objective function, the one with the smallest index (in the initial indexing). -/ def chooseEnteringVar : SimplexAlgorithmM matType Nat := do let mut enterIdxOpt : Option Nat := none -- index of entering variable in the `free` array let mut minIdx := 0 for i in [:(← get).free.size - 1] do if (← get).mat[(0, i)]! > 0 && (enterIdxOpt.isNone || (← get).free[i]! < minIdx) then enterIdxOpt := i minIdx := (← get).free[i]! /- If there is no such variable the solution does not exist for sure. -/ match enterIdxOpt with | none => throwThe SimplexAlgorithmException SimplexAlgorithmException.infeasible | some enterIdx => return enterIdx /-- Chooses an exiting variable: the variable imposing the strictest limit on the increase of the entering variable, breaking ties by choosing the variable with smallest index. -/ def chooseExitingVar (enterIdx : Nat) : SimplexAlgorithmM matType Nat := do let mut exitIdxOpt : Option Nat := none -- index of entering variable in the `basic` array let mut minCoef := 0 let mut minIdx := 0 for i in [1:(← get).basic.size] do if (← get).mat[(i, enterIdx)]! >= 0 then continue let lastIdx := (← get).free.size - 1 let coef := -(← get).mat[(i, lastIdx)]! / (← get).mat[(i, enterIdx)]! if exitIdxOpt.isNone || coef < minCoef || (coef == minCoef && (← get).basic[i]! < minIdx) then exitIdxOpt := i minCoef := coef minIdx := (← get).basic[i]! return exitIdxOpt.get! -- such variable always exists because our problem is bounded /-- Chooses entering and exiting variables using (Bland's rule)[(https://en.wikipedia.org/wiki/Bland%27s_rule)] that guarantees that the Simplex Algorithm terminates. -/ def choosePivots : SimplexAlgorithmM matType (Nat × Nat) := do let enterIdx ← chooseEnteringVar let exitIdx ← chooseExitingVar enterIdx return ⟨exitIdx, enterIdx⟩ /-- Runs the Simplex Algorithm inside the `SimplexAlgorithmM`. It always terminates, finding solution if such exists. -/ def runSimplexAlgorithm : SimplexAlgorithmM matType Unit := do while !(← checkSuccess) do Lean.Core.checkSystem decl_name%.toString let ⟨exitIdx, enterIdx⟩ ← choosePivots doPivotOperation exitIdx enterIdx end Mathlib.Tactic.Linarith.SimplexAlgorithm
.lake/packages/mathlib/Mathlib/Tactic/Linarith/Oracle/SimplexAlgorithm/PositiveVector.lean
import Lean.Meta.Basic import Mathlib.Tactic.Linarith.Oracle.SimplexAlgorithm.SimplexAlgorithm import Mathlib.Tactic.Linarith.Oracle.SimplexAlgorithm.Gauss /-! # `linarith` certificate search as an LP problem `linarith` certificate search can easily be reduced to the following problem: given the matrix `A` and the list `strictIndexes`, find the nonnegative vector `v` such that some of its coordinates from the `strictIndexes` are positive and `A v = 0`. The function `findPositiveVector` solves this problem. ## Algorithm sketch 1. We translate the problem stated above to some Linear Programming problem. See `stateLP` for details. Let us denote the corresponding matrix `B`. 2. We solve the equation `B x = 0` using Gauss Elimination, splitting the set of variables into *free* variables, which can take any value, and *basic* variables which are linearly expressed through the free one. This gives us an initial tableau for the Simplex Algorithm. See `Linarith.SimplexAlgorithm.Gauss.getTableau`. 3. We run the Simplex Algorithm until it finds a solution. See the file `SimplexAlgorithm.lean`. -/ namespace Mathlib.Tactic.Linarith.SimplexAlgorithm variable {matType : Nat → Nat → Type} [UsableInSimplexAlgorithm matType] /-- Given matrix `A` and list `strictIndexes` of strict inequalities' indexes, we want to state the Linear Programming problem which solution would give us a solution for the initial problem (see `findPositiveVector`). As an objective function (that we are trying to maximize) we use sum of coordinates from `strictIndexes`: it suffices to find the nonnegative vector that makes this function positive. We introduce two auxiliary variables and one constraint: * The variable `y` is interpreted as "homogenized" `1`. We need it because dealing with a homogenized problem is easier, but having some "unit" is necessary. * To bound the problem we add the constraint `x₁ + ... + xₘ + z = y` introducing new variable `z`. The objective function also interpreted as an auxiliary variable with constraint `f = ∑ i ∈ strictIndexes, xᵢ`. The variable `f` has to always be basic while `y` has to be free. Our Gauss method implementation greedy collects basic variables moving from left to right. So we place `f` before `x`-s and `y` after them. We place `z` between `f` and `x` because in this case `z` will be basic and `Gauss.getTableau` produce tableau with nonnegative last column, meaning that we are starting from a feasible point. -/ def stateLP {n m : Nat} (A : matType n m) (strictIndexes : List Nat) : matType (n + 2) (m + 3) := /- +2 due to shifting by `f` and `z` -/ let objectiveRow : List (Nat × Nat × Rat) := (0, 0, -1) :: strictIndexes.map fun idx => (0, idx + 2, 1) let constraintRow : List (Nat × Nat × Rat) := [(1, 1, 1), (1, m + 2, -1)] ++ (List.range m).map (fun i => (1, i + 2, 1)) let valuesA := getValues A |>.map fun (i, j, v) => (i + 2, j + 2, v) ofValues (objectiveRow ++ constraintRow ++ valuesA) /-- Extracts target vector from the tableau, putting auxiliary variables aside (see `stateLP`). -/ def extractSolution (tableau : Tableau matType) : Array Rat := Id.run do let mut ans : Array Rat := Array.replicate (tableau.basic.size + tableau.free.size - 3) 0 for h : i in [1:tableau.basic.size] do ans := ans.set! (tableau.basic[i] - 2) <| tableau.mat[(i, tableau.free.size - 1)]! return ans /-- Finds a nonnegative vector `v`, such that `A v = 0` and some of its coordinates from `strictCoords` are positive, in the case such `v` exists. If not, throws the error. The latter prevents `linarith` from doing useless post-processing. -/ def findPositiveVector {n m : Nat} {matType : Nat → Nat → Type} [UsableInSimplexAlgorithm matType] (A : matType n m) (strictIndexes : List Nat) : Lean.Meta.MetaM <| Array Rat := do /- State the linear programming problem. -/ let B := stateLP A strictIndexes /- Using Gaussian elimination split variable into free and basic forming the tableau that will be operated by the Simplex Algorithm. -/ let initTableau ← Gauss.getTableau B /- Run the Simplex Algorithm and extract the solution. -/ let res ← runSimplexAlgorithm.run initTableau if res.fst.isOk then return extractSolution res.snd else throwError "Simplex Algorithm failed" end Mathlib.Tactic.Linarith.SimplexAlgorithm
.lake/packages/mathlib/Mathlib/Tactic/Linarith/Oracle/SimplexAlgorithm/Datatypes.lean
import Mathlib.Init import Std.Data.HashMap.Basic /-! # Datatypes for the Simplex Algorithm implementation -/ namespace Mathlib.Tactic.Linarith.SimplexAlgorithm /-- Specification for matrix types over ℚ which can be used in the Gauss Elimination and the Simplex Algorithm. It was introduced to unify dense matrices and sparse matrices. -/ class UsableInSimplexAlgorithm (α : Nat → Nat → Type) where /-- Returns `mat[i, j]`. -/ getElem {n m : Nat} (mat : α n m) (i j : Nat) : Rat /-- Sets `mat[i, j]`. -/ setElem {n m : Nat} (mat : α n m) (i j : Nat) (v : Rat) : α n m /-- Returns the list of elements of `mat` in the form `(i, j, mat[i, j])`. -/ getValues {n m : Nat} (mat : α n m) : List (Nat × Nat × Rat) /-- Creates a matrix from a list of elements in the form `(i, j, mat[i, j])`. -/ ofValues {n m : Nat} (values : List (Nat × Nat × Rat)) : α n m /-- Swaps two rows. -/ swapRows {n m : Nat} (mat : α n m) (i j : Nat) : α n m /-- Subtracts `i`-th row multiplied by `coef` from `j`-th row. -/ subtractRow {n m : Nat} (mat : α n m) (i j : Nat) (coef : Rat) : α n m /-- Divides the `i`-th row by `coef`. -/ divideRow {n m : Nat} (mat : α n m) (i : Nat) (coef : Rat) : α n m export UsableInSimplexAlgorithm (setElem getValues ofValues swapRows subtractRow divideRow) instance (n m : Nat) (matType : Nat → Nat → Type) [UsableInSimplexAlgorithm matType] : GetElem (matType n m) (Nat × Nat) Rat fun _ p => p.1 < n ∧ p.2 < m where getElem mat p _ := UsableInSimplexAlgorithm.getElem mat p.1 p.2 /-- Structure for matrices over ℚ. So far it is just a 2d-array carrying dimensions (that are supposed to match with the actual dimensions of `data`), but the plan is to add some `Prop`-data and make the structure strict and safe. Note: we avoid using `Matrix` because it is far more efficient to store a matrix as its entries than as function between `Fin`-s. -/ structure DenseMatrix (n m : Nat) where /-- The content of the matrix. -/ data : Array (Array Rat) instance : UsableInSimplexAlgorithm DenseMatrix where getElem mat i j := mat.data[i]![j]! setElem mat i j v := ⟨mat.data.modify i fun row => row.set! j v⟩ getValues mat := mat.data.zipIdx.foldl (init := []) fun acc (row, i) => let rowVals := Array.toList <| row.zipIdx.filterMap fun (v, j) => if v != 0 then some (i, j, v) else none rowVals ++ acc ofValues {n m : Nat} vals : DenseMatrix _ _ := Id.run do let mut data : Array (Array Rat) := Array.replicate n <| Array.replicate m 0 for ⟨i, j, v⟩ in vals do data := data.modify i fun row => row.set! j v return ⟨data⟩ swapRows mat i j := ⟨mat.data.swapIfInBounds i j⟩ subtractRow mat i j coef := let newData : Array (Array Rat) := mat.data.modify j fun row => Array.zipWith (fun x y => x - coef * y) row mat.data[i]! ⟨newData⟩ divideRow mat i coef := ⟨mat.data.modify i (·.map (· / coef))⟩ /-- Structure for sparse matrices over ℚ, implemented as an array of hashmaps, containing only nonzero values. -/ structure SparseMatrix (n m : Nat) where /-- The content of the matrix. -/ data : Array <| Std.HashMap Nat Rat instance : UsableInSimplexAlgorithm SparseMatrix where getElem mat i j := mat.data[i]!.getD j 0 setElem mat i j v := if v == 0 then ⟨mat.data.modify i fun row => row.erase j⟩ else ⟨mat.data.modify i fun row => row.insert j v⟩ getValues mat := mat.data.zipIdx.foldl (init := []) fun acc (row, i) => let rowVals := row.toList.map fun (j, v) => (i, j, v) rowVals ++ acc ofValues {n _ : Nat} vals := Id.run do let mut data : Array (Std.HashMap Nat Rat) := Array.replicate n ∅ for ⟨i, j, v⟩ in vals do if v != 0 then data := data.modify i fun row => row.insert j v return ⟨data⟩ swapRows mat i j := ⟨mat.data.swapIfInBounds i j⟩ subtractRow mat i j coef := let newData := mat.data.modify j fun row => mat.data[i]!.fold (fun cur k val => let newVal := (cur.getD k 0) - coef * val if newVal != 0 then cur.insert k newVal else cur.erase k ) row ⟨newData⟩ divideRow mat i coef := let newData : Array (Std.HashMap Nat Rat) := mat.data.modify i fun row => row.fold (fun cur k v => cur.insert k (v / coef)) row ⟨newData⟩ /-- `Tableau` is a structure the Simplex Algorithm operates on. The `i`-th row of `mat` expresses the variable `basic[i]` as a linear combination of variables from `free`. -/ structure Tableau (matType : Nat → Nat → Type) [UsableInSimplexAlgorithm matType] where /-- Array containing the basic variables' indexes -/ basic : Array Nat /-- Array containing the free variables' indexes -/ free : Array Nat /-- Matrix of coefficients the basic variables expressed through the free ones. -/ mat : matType basic.size free.size end Mathlib.Tactic.Linarith.SimplexAlgorithm
.lake/packages/mathlib/Mathlib/Tactic/Bound/Init.lean
import Mathlib.Init import Aesop.Frontend.Command /-! # Bound Rule Set This module defines the `Bound` Aesop rule set which is used by the `bound` tactic. Aesop rule sets only become visible once the file in which they're declared is imported, so we must put this declaration into its own file. -/ declare_aesop_rule_sets [Bound]
.lake/packages/mathlib/Mathlib/Tactic/Bound/Attribute.lean
import Mathlib.Tactic.Bound.Init import Qq import Aesop /-! # The `bound` attribute Any lemma tagged with `@[bound]` is registered as an apply rule for the `bound` tactic, by converting it to either `norm apply` or `safe apply <priority>`. The classification is based on the number and types of the lemma's hypotheses. -/ open Lean (MetaM) open Qq namespace Mathlib.Tactic.Bound initialize Lean.registerTraceClass `bound.attribute variable {u : Lean.Level} {α : Q(Type u)} /-- Check if an expression is zero -/ def isZero (e : Q($α)) : MetaM Bool := match e with | ~q(@OfNat.ofNat.{u} _ (nat_lit 0) $i) => return true | _ => return false /-- Map the arguments of an inequality expression to a score -/ def ineqPriority (a b : Q($α)) : MetaM Nat := do return if (← isZero a) || (← isZero b) then 1 else 10 /-- Map a hypothesis type to a score -/ partial def hypPriority (hyp : Q(Prop)) : MetaM Nat := do match hyp with -- Conjunctions add scores | ~q($a ∧ $b) => pure <| (← hypPriority a) + (← hypPriority b) -- Guessing (disjunction) gets a big penalty | ~q($a ∨ $b) => pure <| 100 + (← hypPriority a) + (← hypPriority b) -- Inequalities get score 1 if they contain zero, 10 otherwise | ~q(@LE.le _ $i $a $b) => ineqPriority a b | ~q(@LT.lt _ $i $a $b) => ineqPriority a b | ~q(@GE.ge _ $i $b $a) => ineqPriority a b | ~q(@GT.gt _ $i $b $a) => ineqPriority a b -- Assume anything else is non-relevant | _ => pure 0 /-- Map a type to a score -/ def typePriority (decl : Lean.Name) (type : Lean.Expr) : MetaM Nat := Lean.Meta.forallTelescope type fun xs t ↦ do checkResult t xs.foldlM (fun (t : Nat) x ↦ do return t + (← argPriority x)) 0 where /-- Score the type of argument `x` -/ argPriority (x : Lean.Expr) : MetaM Nat := do hypPriority (← Lean.Meta.inferType x) /-- Insist that our conclusion is an inequality -/ checkResult (t : Q(Prop)) : MetaM Unit := do match t with | ~q(@LE.le _ $i $a $b) => return () | ~q(@LT.lt _ $i $a $b) => return () | ~q(@GE.ge _ $i $b $a) => return () | ~q(@GT.gt _ $i $b $a) => return () | _ => throwError (f!"`{decl}` has invalid type `{type}` as a 'bound' lemma: \ it should be an inequality") /-- Map a theorem decl to a score (0 means `norm apply`, `0 <` means `safe apply`) -/ def declPriority (decl : Lean.Name) : Lean.MetaM Nat := do match (← Lean.getEnv).find? decl with | some info => do typePriority decl info.type | none => throwError "unknown declaration {decl}" /-- Map a score to either `norm apply` or `safe apply <priority>` -/ def scoreToConfig (decl : Lean.Name) (score : Nat) : Aesop.Frontend.RuleConfig := let (phase, priority) := match score with | 0 => (Aesop.PhaseName.norm, 0) -- No hypotheses: this rule closes the goal immediately | s => (Aesop.PhaseName.safe, s) { term? := some (Lean.mkIdent decl) phase? := phase priority? := some (Aesop.Frontend.Priority.int priority) builder? := some (.regular .apply) builderOptions := {} ruleSets := ⟨#[`Bound]⟩ } /-- Register a lemma as an `apply` rule for the `bound` tactic. A lemma is appropriate for `bound` if it proves an inequality using structurally simpler inequalities, "recursing" on the structure of the expressions involved, assuming positivity or nonnegativity where useful. Examples include 1. `gcongr`-like inequalities over `<` and `≤` such as `f x ≤ f y` where `f` is monotone (note that `gcongr` supports other relations). 2. `mul_le_mul` which proves `a * b ≤ c * d` from `a ≤ c ∧ b ≤ d ∧ 0 ≤ b ∧ 0 ≤ c` 3. Positivity or nonnegativity inequalities such as `sub_nonneg`: `a ≤ b → 0 ≤ b - a` 4. Inequalities involving `1` such as `one_le_div` or `Real.one_le_exp` 5. Disjunctions where the natural recursion branches, such as `a ^ n ≤ a ^ m` when the inequality for `n,m` depends on whether `1 ≤ a ∨ a ≤ 1`. Each `@[bound]` lemma is assigned a score based on the number and complexity of its hypotheses, and the `aesop` implementation chooses lemmas with lower scores first: 1. Inequality hypotheses involving `0` add 1 to the score. 2. General inequalities add `10`. 3. Disjunctions `a ∨ b` add `100` plus the sum of the scores of `a` and `b`. The functionality of `bound` overlaps with `positivity` and `gcongr`, but can jump back and forth between `0 ≤ x` and `x ≤ y`-type inequalities. For example, `bound` proves `0 ≤ c → b ≤ a → 0 ≤ a * c - b * c` by turning the goal into `b * c ≤ a * c`, then using `mul_le_mul_of_nonneg_right`. `bound` also uses specialized lemmas for goals of the form `1 ≤ x, 1 < x, x ≤ 1, x < 1`. See also `@[bound_forward]` which marks a lemma as a forward rule for `bound`: these lemmas are applied to hypotheses to extract inequalities (e.g. `HasPowerSeriesOnBall.r_pos`). -/ initialize Lean.registerBuiltinAttribute { name := `bound descr := "Register a theorem as an apply rule for the `bound` tactic." applicationTime := .afterCompilation add := fun decl stx attrKind => Lean.withRef stx do let score ← Aesop.runTermElabMAsCoreM <| declPriority decl trace[bound.attribute] "'{decl}' has score '{score}'" let context ← Aesop.runMetaMAsCoreM Aesop.ElabM.Context.forAdditionalGlobalRules let (rule, ruleSets) ← Aesop.runTermElabMAsCoreM <| (scoreToConfig decl score).buildGlobalRule.run context for ruleSet in ruleSets do Aesop.Frontend.addGlobalRule ruleSet rule attrKind (checkNotExists := true) erase := fun decl => let ruleFilter := { name := decl, scope := .global, builders := #[], phases := #[] } Aesop.Frontend.eraseGlobalRules Aesop.RuleSetNameFilter.all ruleFilter (checkExists := true) } /-- Attribute for `forward` rules for the `bound` tactic. `@[bound_forward]` lemmas should produce inequalities given other hypotheses that might be in the context. A typical example is exposing an inequality field of a structure, such as `HasPowerSeriesOnBall.r_pos`. -/ macro "bound_forward" : attr => `(attr|aesop safe forward (rule_sets := [$(Lean.mkIdent `Bound):ident])) end Mathlib.Tactic.Bound
.lake/packages/mathlib/Mathlib/Tactic/Measurability/Init.lean
import Mathlib.Init import Aesop /-! # Measurability Rule Set This module defines the `Measurable` Aesop rule set which is used by the `measurability` tactic. Aesop rule sets only become visible once the file in which they're declared is imported, so we must put this declaration into its own file. -/ declare_aesop_rule_sets [Measurable]
.lake/packages/mathlib/Mathlib/Tactic/CC/Lemmas.lean
import Mathlib.Init /-! Lemmas use by the congruence closure module -/ namespace Mathlib.Tactic.CC theorem iff_eq_of_eq_true_left {a b : Prop} (h : a = True) : (a ↔ b) = b := h.symm ▸ true_iff _ theorem iff_eq_of_eq_true_right {a b : Prop} (h : b = True) : (a ↔ b) = a := h.symm ▸ iff_true _ theorem iff_eq_true_of_eq {a b : Prop} (h : a = b) : (a ↔ b) = True := h ▸ iff_self _ theorem and_eq_of_eq_true_left {a b : Prop} (h : a = True) : (a ∧ b) = b := h.symm ▸ true_and _ theorem and_eq_of_eq_true_right {a b : Prop} (h : b = True) : (a ∧ b) = a := h.symm ▸ and_true _ theorem and_eq_of_eq_false_left {a b : Prop} (h : a = False) : (a ∧ b) = False := h.symm ▸ false_and _ theorem and_eq_of_eq_false_right {a b : Prop} (h : b = False) : (a ∧ b) = False := h.symm ▸ and_false _ theorem and_eq_of_eq {a b : Prop} (h : a = b) : (a ∧ b) = a := h ▸ propext and_self_iff theorem or_eq_of_eq_true_left {a b : Prop} (h : a = True) : (a ∨ b) = True := h.symm ▸ true_or _ theorem or_eq_of_eq_true_right {a b : Prop} (h : b = True) : (a ∨ b) = True := h.symm ▸ or_true _ theorem or_eq_of_eq_false_left {a b : Prop} (h : a = False) : (a ∨ b) = b := h.symm ▸ false_or _ theorem or_eq_of_eq_false_right {a b : Prop} (h : b = False) : (a ∨ b) = a := h.symm ▸ or_false _ theorem or_eq_of_eq {a b : Prop} (h : a = b) : (a ∨ b) = a := h ▸ propext or_self_iff theorem imp_eq_of_eq_true_left {a b : Prop} (h : a = True) : (a → b) = b := h.symm ▸ propext ⟨fun h ↦ h trivial, fun h₁ _ ↦ h₁⟩ theorem imp_eq_of_eq_true_right {a b : Prop} (h : b = True) : (a → b) = True := h.symm ▸ propext ⟨fun _ ↦ trivial, fun h₁ _ ↦ h₁⟩ theorem imp_eq_of_eq_false_left {a b : Prop} (h : a = False) : (a → b) = True := h.symm ▸ propext ⟨fun _ ↦ trivial, fun _ h₂ ↦ False.elim h₂⟩ theorem imp_eq_of_eq_false_right {a b : Prop} (h : b = False) : (a → b) = Not a := h.symm ▸ propext ⟨fun h ↦ h, fun hna ha ↦ hna ha⟩ /- Remark: the congruence closure module will only use the following lemma is `CCConfig.em` is `true`. -/ theorem not_imp_eq_of_eq_false_right {a b : Prop} (h : b = False) : (Not a → b) = a := h.symm ▸ propext (Iff.intro ( fun h' ↦ Classical.byContradiction fun hna ↦ h' hna) fun ha hna ↦ hna ha) theorem imp_eq_true_of_eq {a b : Prop} (h : a = b) : (a → b) = True := h ▸ propext ⟨fun _ ↦ trivial, fun _ ha ↦ ha⟩ theorem not_eq_of_eq_true {a : Prop} (h : a = True) : Not a = False := h.symm ▸ propext not_true theorem not_eq_of_eq_false {a : Prop} (h : a = False) : Not a = True := h.symm ▸ propext not_false_iff theorem false_of_a_eq_not_a {a : Prop} (h : a = Not a) : False := have : Not a := fun ha ↦ absurd ha (Eq.mp h ha) absurd (Eq.mpr h this) this universe u theorem if_eq_of_eq_true {c : Prop} [d : Decidable c] {α : Sort u} (t e : α) (h : c = True) : @ite α c d t e = t := if_pos (of_eq_true h) theorem if_eq_of_eq_false {c : Prop} [d : Decidable c] {α : Sort u} (t e : α) (h : c = False) : @ite α c d t e = e := if_neg (of_eq_false h) theorem if_eq_of_eq (c : Prop) [d : Decidable c] {α : Sort u} {t e : α} (h : t = e) : @ite α c d t e = t := match d with | isTrue _ => rfl | isFalse _ => Eq.symm h theorem eq_true_of_and_eq_true_left {a b : Prop} (h : (a ∧ b) = True) : a = True := eq_true (And.left (of_eq_true h)) theorem eq_true_of_and_eq_true_right {a b : Prop} (h : (a ∧ b) = True) : b = True := eq_true (And.right (of_eq_true h)) theorem eq_false_of_or_eq_false_left {a b : Prop} (h : (a ∨ b) = False) : a = False := eq_false fun ha ↦ False.elim (Eq.mp h (Or.inl ha)) theorem eq_false_of_or_eq_false_right {a b : Prop} (h : (a ∨ b) = False) : b = False := eq_false fun hb ↦ False.elim (Eq.mp h (Or.inr hb)) theorem eq_false_of_not_eq_true {a : Prop} (h : Not a = True) : a = False := eq_false fun ha ↦ absurd ha (Eq.mpr h trivial) /- Remark: the congruence closure module will only use the following lemma is `CCConfig.em` is `true`. -/ theorem eq_true_of_not_eq_false {a : Prop} (h : Not a = False) : a = True := eq_true (Classical.byContradiction fun hna ↦ Eq.mp h hna) end Mathlib.Tactic.CC
.lake/packages/mathlib/Mathlib/Tactic/CC/MkProof.lean
import Mathlib.Tactic.CC.Datatypes import Mathlib.Tactic.CC.Lemmas import Mathlib.Tactic.Relation.Rfl import Mathlib.Tactic.Relation.Symm /-! # Make proofs from a congruence closure -/ open Lean Meta Elab Tactic Std namespace Mathlib.Tactic.CC /-- The monad for the `cc` tactic stores the current state of the tactic. -/ abbrev CCM := StateRefT CCStructure MetaM namespace CCM /-- Run a computation in the `CCM` monad. -/ @[inline] def run {α : Type} (x : CCM α) (c : CCStructure) : MetaM (α × CCStructure) := StateRefT'.run x c /-- Update the `cache` field of the state. -/ @[inline] def modifyCache (f : CCCongrTheoremCache → CCCongrTheoremCache) : CCM Unit := modify fun cc => { cc with cache := f cc.cache } /-- Read the `cache` field of the state. -/ @[inline] def getCache : CCM CCCongrTheoremCache := do return (← get).cache /-- Look up an entry associated with the given expression. -/ def getEntry (e : Expr) : CCM (Option Entry) := do return (← get).entries[e]? /-- Use the normalizer to normalize `e`. If no normalizer was configured, returns `e` itself. -/ def normalize (e : Expr) : CCM Expr := do if let some normalizer := (← get).normalizer then normalizer.normalize e else return e /-- Return the root expression of the expression's congruence class. -/ def getRoot (e : Expr) : CCM Expr := do return (← get).root e /-- Is `e` the root of its congruence class? -/ def isCgRoot (e : Expr) : CCM Bool := do return (← get).isCgRoot e /-- Return true iff the given function application are congruent `e₁` should have the form `f a` and `e₂` the form `g b`. See paper: Congruence Closure for Intensional Type Theory. -/ partial def isCongruent (e₁ e₂ : Expr) : CCM Bool := do let .app f a := e₁ | failure let .app g b := e₂ | failure -- If they are non-dependent functions, then we can compare all arguments at once. if (← getEntry e₁).any Entry.fo then e₁.withApp fun f₁ args₁ => e₂.withApp fun f₂ args₂ => do if ha : args₁.size = args₂.size then for hi : i in [:args₁.size] do if (← getRoot args₁[i]) != (← getRoot (args₂[i]'(ha.symm ▸ hi.2.1))) then return false if f₁ == f₂ then return true else if (← getRoot f₁) != (← getRoot f₂) then -- `f₁` and `f₂` are not equivalent return false else if ← pureIsDefEq (← inferType f₁) (← inferType f₂) then return true else return false else return false else -- Given `e₁ := f a`, `e₂ := g b` if (← getRoot a) != (← getRoot b) then -- `a` and `b` are not equivalent return false else if (← getRoot f) != (← getRoot g) then -- `f` and `g` are not equivalent return false else if ← pureIsDefEq (← inferType f) (← inferType g) then /- Case 1: `f` and `g` have the same type, then we can create a congruence proof for `f a ≍ g b` -/ return true else if f.isApp && g.isApp then -- Case 2: `f` and `g` are congruent isCongruent f g else /- f and g are not congruent nor they have the same type. We can't generate a congruence proof in this case because the following lemma `hcongr : f₁ ≍ f₂ → a₁ ≍ a₂ → f₁ a₁ ≍ f₂ a₂` is not provable. Remark: it is also not provable in MLTT, Coq and Agda (even if we assume UIP). -/ return false /-- Try to find a congruence theorem for an application of `fn` with `nargs` arguments, with support for `HEq`. -/ def mkCCHCongrTheorem (fn : Expr) (nargs : Nat) : CCM (Option CCCongrTheorem) := do let cache ← getCache -- Check if `{ fn, nargs }` is in the cache let key₁ : CCCongrTheoremKey := { fn, nargs } if let some it := cache[key₁]? then return it -- Try automatically generated congruence lemma with support for heterogeneous equality. let lemm ← mkCCHCongrWithArity fn nargs if let some lemm := lemm then modifyCache fun ccc => ccc.insert key₁ (some lemm) return lemm -- cache failure modifyCache fun ccc => ccc.insert key₁ none return none /-- Try to find a congruence theorem for the expression `e` with support for `HEq`. -/ def mkCCCongrTheorem (e : Expr) : CCM (Option CCCongrTheorem) := do let fn := e.getAppFn let nargs := e.getAppNumArgs mkCCHCongrTheorem fn nargs /-- Treat the entry associated with `e` as a first-order function. -/ def setFO (e : Expr) : CCM Unit := modify fun ccs => { ccs with entries := ccs.entries.modify e fun d => { d with fo := true } } /-- Update the modification time of the congruence class of `e`. -/ partial def updateMT (e : Expr) : CCM Unit := do let r ← getRoot e let some ps := (← get).parents[r]? | return for p in ps do let some it ← getEntry p.expr | failure let gmt := (← get).gmt if it.mt < gmt then let newIt := { it with mt := gmt } modify fun ccs => { ccs with entries := ccs.entries.insert p.expr newIt } updateMT p.expr /-- Does the congruence class with root `root` have any `HEq` proofs? -/ def hasHEqProofs (root : Expr) : CCM Bool := do let some n ← getEntry root | failure guard (n.root == root) return n.heqProofs /-- Apply symmetry to `H`, which is an `Eq` or a `HEq`. * If `heqProofs` is true, ensure the result is a `HEq` (otherwise it is assumed to be `Eq`). * If `flipped` is true, apply `symm`, otherwise keep the same direction. -/ def flipProofCore (H : Expr) (flipped heqProofs : Bool) : CCM Expr := do let mut newH := H if ← liftM <| pure heqProofs <&&> Expr.isEq <$> (inferType H >>= whnf) then newH ← mkAppM ``heq_of_eq #[H] if !flipped then return newH else if heqProofs then mkHEqSymm newH else mkEqSymm newH /-- In a delayed way, apply symmetry to `H`, which is an `Eq` or a `HEq`. * If `heqProofs` is true, ensure the result is a `HEq` (otherwise it is assumed to be `Eq`). * If `flipped` is true, apply `symm`, otherwise keep the same direction. -/ def flipDelayedProofCore (H : DelayedExpr) (flipped heqProofs : Bool) : CCM DelayedExpr := do let mut newH := H if heqProofs then newH := .heqOfEq H if !flipped then return newH else if heqProofs then return .heqSymm newH else return .eqSymm newH /-- Apply symmetry to `H`, which is an `Eq` or a `HEq`. * If `heqProofs` is true, ensure the result is a `HEq` (otherwise it is assumed to be `Eq`). * If `flipped` is true, apply `symm`, otherwise keep the same direction. -/ def flipProof (H : EntryExpr) (flipped heqProofs : Bool) : CCM EntryExpr := match H with | .ofExpr H => EntryExpr.ofExpr <$> flipProofCore H flipped heqProofs | .ofDExpr H => EntryExpr.ofDExpr <$> flipDelayedProofCore H flipped heqProofs | _ => return H /-- Are `e₁` and `e₂` known to be in the same equivalence class? -/ def isEqv (e₁ e₂ : Expr) : CCM Bool := do let some n₁ ← getEntry e₁ | return false let some n₂ ← getEntry e₂ | return false return n₁.root == n₂.root /-- Is `e₁ ≠ e₂` known to be true? Note that this is stronger than `not (isEqv e₁ e₂)`: only if we can prove they are distinct this returns `true`. -/ def isNotEqv (e₁ e₂ : Expr) : CCM Bool := do let tmp ← mkEq e₁ e₂ if ← isEqv tmp (.const ``False []) then return true let tmp ← mkHEq e₁ e₂ isEqv tmp (.const ``False []) /-- Is the proposition `e` known to be true? -/ @[inline] def isEqTrue (e : Expr) : CCM Bool := isEqv e (.const ``True []) /-- Is the proposition `e` known to be false? -/ @[inline] def isEqFalse (e : Expr) : CCM Bool := isEqv e (.const ``False []) /-- Apply transitivity to `H₁` and `H₂`, which are both `Eq` or `HEq` depending on `heqProofs`. -/ def mkTrans (H₁ H₂ : Expr) (heqProofs : Bool) : MetaM Expr := if heqProofs then mkHEqTrans H₁ H₂ else mkEqTrans H₁ H₂ /-- Apply transitivity to `H₁?` and `H₂`, which are both `Eq` or `HEq` depending on `heqProofs`. If `H₁?` is `none`, return `H₂` instead. -/ def mkTransOpt (H₁? : Option Expr) (H₂ : Expr) (heqProofs : Bool) : MetaM Expr := match H₁? with | some H₁ => mkTrans H₁ H₂ heqProofs | none => pure H₂ mutual /-- Use congruence on arguments to prove `lhs = rhs`. That is, tries to prove that `lhsFn lhsArgs[0] ... lhsArgs[n-1] = lhsFn rhsArgs[0] ... rhsArgs[n-1]` by showing that `lhsArgs[i] = rhsArgs[i]` for all `i`. Fails if the head function of `lhs` is not that of `rhs`. -/ partial def mkCongrProofCore (lhs rhs : Expr) (heqProofs : Bool) : CCM Expr := do let mut lhsArgsRev : Array Expr := #[] let mut rhsArgsRev : Array Expr := #[] let mut lhsIt := lhs let mut rhsIt := rhs -- Collect the arguments to `lhs` and `rhs`. -- As an optimization, we stop collecting arguments as soon as the functions are defeq, -- so `lhsFn` and `rhsFn` might end up still of the form `(f x y z)` and `(f x' y' z')`. if lhs != rhs then repeat let .app lhsItFn lhsItArg := lhsIt | failure let .app rhsItFn rhsItArg := rhsIt | failure lhsArgsRev := lhsArgsRev.push lhsItArg rhsArgsRev := rhsArgsRev.push rhsItArg lhsIt := lhsItFn rhsIt := rhsItFn if lhsIt == rhsIt then break if ← pureIsDefEq lhsIt rhsIt then break if ← isEqv lhsIt rhsIt <&&> inferType lhsIt >>= fun i₁ => inferType rhsIt >>= fun i₂ => pureIsDefEq i₁ i₂ then break -- If we collect no arguments, the expressions themselves are defeq; return `rfl`. if lhsArgsRev.isEmpty then if heqProofs then return (← mkHEqRefl lhs) else return (← mkEqRefl lhs) let lhsArgs := lhsArgsRev.reverse let rhsArgs := rhsArgsRev.reverse -- Ensure that `lhsFn = rhsFn`, they have the same type and the same list of arguments. let PLift.up ha ← if ha : lhsArgs.size = rhsArgs.size then pure (PLift.up ha) else failure let lhsFn := lhsIt let rhsFn := rhsIt guard (← isEqv lhsFn rhsFn <||> pureIsDefEq lhsFn rhsFn) guard (← pureIsDefEq (← inferType lhsFn) (← inferType rhsFn)) /- Create `r`, a proof for `lhsFn lhsArgs[0] ... lhsArgs[n-1] = lhsFn rhsArgs[0] ... rhsArgs[n-1]` where `n := lhsArgs.size` -/ let some specLemma ← mkCCHCongrTheorem lhsFn lhsArgs.size | failure let mut kindsIt := specLemma.argKinds let mut lemmaArgs : Array Expr := #[] for hi : i in [:lhsArgs.size] do guard !kindsIt.isEmpty lemmaArgs := lemmaArgs.push lhsArgs[i] |>.push (rhsArgs[i]'(ha.symm ▸ hi.2.1)) if kindsIt[0]! matches CongrArgKind.heq then let some p ← getHEqProof lhsArgs[i] (rhsArgs[i]'(ha.symm ▸ hi.2.1)) | failure lemmaArgs := lemmaArgs.push p else guard (kindsIt[0]! matches .eq) let some p ← getEqProof lhsArgs[i] (rhsArgs[i]'(ha.symm ▸ hi.2.1)) | failure lemmaArgs := lemmaArgs.push p kindsIt := kindsIt.eraseIdx! 0 let mut r := mkAppN specLemma.proof lemmaArgs if specLemma.heqResult && !heqProofs then r ← mkAppM ``eq_of_heq #[r] else if !specLemma.heqResult && heqProofs then r ← mkAppM ``heq_of_eq #[r] if ← pureIsDefEq lhsFn rhsFn then return r /- Convert `r` into a proof of `lhs = rhs` using `Eq.rec` and the proof that `lhsFn = rhsFn` -/ let some lhsFnEqRhsFn ← getEqProof lhsFn rhsFn | failure let motive ← withLocalDeclD `x (← inferType lhsFn) fun x => do let motiveRhs := mkAppN x rhsArgs let motive ← if heqProofs then mkHEq lhs motiveRhs else mkEq lhs motiveRhs let hType ← mkEq lhsFn x withLocalDeclD `h hType fun h => mkLambdaFVars #[x, h] motive mkEqRec motive r lhsFnEqRhsFn /-- If `e₁ : R lhs₁ rhs₁`, `e₂ : R lhs₂ rhs₂` and `lhs₁ = rhs₂`, where `R` is a symmetric relation, prove `R lhs₁ rhs₁` is equivalent to `R lhs₂ rhs₂`. * if `lhs₁` is known to equal `lhs₂`, return `none` * if `lhs₁` is not known to equal `rhs₂`, fail. -/ partial def mkSymmCongrProof (e₁ e₂ : Expr) (heqProofs : Bool) : CCM (Option Expr) := do let some (R₁, lhs₁, rhs₁) ← e₁.relSidesIfSymm? | return none let some (R₂, lhs₂, rhs₂) ← e₂.relSidesIfSymm? | return none if R₁ != R₂ then return none if (← isEqv lhs₁ lhs₂) then return none guard (← isEqv lhs₁ rhs₂) /- We must apply symmetry. The symm congruence table is implicitly using symmetry. That is, we have `e₁ := lhs₁ ~R₁~ rhs₁` and `e2 := lhs₂ ~R₁~ rhs₂` But, `lhs₁ ~R₁~ rhs₂` and `rhs₁ ~R₁~ lhs₂` -/ /- Given `e₁ := lhs₁ ~R₁~ rhs₁`, create proof for `lhs₁ ~R₁~ rhs₁` = `rhs₁ ~R₁~ lhs₁` -/ let newE₁ ← mkRel R₁ rhs₁ lhs₁ let e₁IffNewE₁ ← withLocalDeclD `h₁ e₁ fun h₁ => withLocalDeclD `h₂ newE₁ fun h₂ => do mkAppM ``Iff.intro #[← mkLambdaFVars #[h₁] (← h₁.applySymm), ← mkLambdaFVars #[h₂] (← h₂.applySymm)] let mut e₁EqNewE₁ := mkApp3 (.const ``propext []) e₁ newE₁ e₁IffNewE₁ let newE₁EqE₂ ← mkCongrProofCore newE₁ e₂ heqProofs if heqProofs then e₁EqNewE₁ ← mkAppM ``heq_of_eq #[e₁EqNewE₁] return some (← mkTrans e₁EqNewE₁ newE₁EqE₂ heqProofs) /-- Use congruence on arguments to prove `e₁ = e₂`. Special case: if `e₁` and `e₂` have the form `R lhs₁ rhs₁` and `R lhs₂ rhs₂` such that `R` is symmetric and `lhs₁ = rhs₂`, then use those facts instead. -/ partial def mkCongrProof (e₁ e₂ : Expr) (heqProofs : Bool) : CCM Expr := do if let some r ← mkSymmCongrProof e₁ e₂ heqProofs then return r else mkCongrProofCore e₁ e₂ heqProofs /-- Turn a delayed proof into an actual proof term. -/ partial def mkDelayedProof (H : DelayedExpr) : CCM Expr := do match H with | .ofExpr H => return H | .eqProof lhs rhs => liftOption (← getEqProof lhs rhs) | .congrArg f h => mkCongrArg f (← mkDelayedProof h) | .congrFun h a => mkCongrFun (← mkDelayedProof h) (← liftOption a.toExpr) | .eqSymm h => mkEqSymm (← mkDelayedProof h) | .eqSymmOpt a₁ a₂ h => mkAppOptM ``Eq.symm #[none, ← liftOption a₁.toExpr, ← liftOption a₂.toExpr, ← mkDelayedProof h] | .eqTrans h₁ h₂ => mkEqTrans (← mkDelayedProof h₁) (← mkDelayedProof h₂) | .eqTransOpt a₁ a₂ a₃ h₁ h₂ => mkAppOptM ``Eq.trans #[none, ← liftOption a₁.toExpr, ← liftOption a₂.toExpr, ← liftOption a₃.toExpr, ← mkDelayedProof h₁, ← mkDelayedProof h₂] | .heqOfEq h => mkAppM ``heq_of_eq #[← mkDelayedProof h] | .heqSymm h => mkHEqSymm (← mkDelayedProof h) /-- Use the format of `H` to try and construct a proof or `lhs = rhs`: * If `H = .congr`, then use congruence. * If `H = .eqTrue`, try to prove `lhs = True` or `rhs = True`, if they have the format `R a b`, by proving `a = b`. * Otherwise, return the (delayed) proof encoded by `H` itself. -/ partial def mkProof (lhs rhs : Expr) (H : EntryExpr) (heqProofs : Bool) : CCM Expr := do match H with | .congr => mkCongrProof lhs rhs heqProofs | .eqTrue => let (flip, some (R, a, b)) ← if lhs == .const ``True [] then ((true, ·)) <$> rhs.relSidesIfRefl? else ((false, ·)) <$> lhs.relSidesIfRefl? | failure let aRb ← if R == ``Eq then getEqProof a b >>= liftOption else if R == ``HEq then getHEqProof a b >>= liftOption else -- TODO(Leo): the following code assumes R is homogeneous. -- We should add support arbitrary heterogeneous reflexive relations. getEqProof a b >>= liftOption >>= fun aEqb => liftM (liftFromEq R aEqb) let aRbEqTrue ← mkEqTrue aRb if flip then mkEqSymm aRbEqTrue else return aRbEqTrue | .refl => let type ← if heqProofs then mkHEq lhs rhs else mkEq lhs rhs let proof ← if heqProofs then mkHEqRefl lhs else mkEqRefl lhs mkExpectedTypeHint proof type | .ofExpr H => return H | .ofDExpr H => mkDelayedProof H /-- If `asHEq` is `true`, then build a proof for `e₁ ≍ e₂`. Otherwise, build a proof for `e₁ = e₂`. The result is `none` if `e₁` and `e₂` are not in the same equivalence class. -/ partial def getEqProofCore (e₁ e₂ : Expr) (asHEq : Bool) : CCM (Option Expr) := do if e₁.hasExprMVar || e₂.hasExprMVar then return none if ← pureIsDefEq e₁ e₂ then if asHEq then return some (← mkHEqRefl e₁) else return some (← mkEqRefl e₁) let some n₁ ← getEntry e₁ | return none let some n₂ ← getEntry e₂ | return none if n₁.root != n₂.root then return none let heqProofs ← hasHEqProofs n₁.root -- 1. Retrieve "path" from `e₁` to `root` let mut path₁ : Array Expr := #[] let mut Hs₁ : Array EntryExpr := #[] let mut visited : ExprSet := ∅ let mut it₁ := e₁ repeat visited := visited.insert it₁ let some it₁N ← getEntry it₁ | failure let some t := it₁N.target | break path₁ := path₁.push t let some p := it₁N.proof | failure Hs₁ := Hs₁.push (← flipProof p it₁N.flipped heqProofs) it₁ := t guard (it₁ == n₁.root) -- 2. The path from `e₂` to root must have at least one element `c` in visited -- Retrieve "path" from `e₂` to `c` let mut path₂ : Array Expr := #[] let mut Hs₂ : Array EntryExpr := #[] let mut it₂ := e₂ repeat if visited.contains it₂ then break -- found common let some it₂N ← getEntry it₂ | failure let some t := it₂N.target | failure path₂ := path₂.push it₂ let some p := it₂N.proof | failure Hs₂ := Hs₂.push (← flipProof p (!it₂N.flipped) heqProofs) it₂ := t -- `it₂` is the common element... -- 3. Shrink `path₁`/`Hs₁` until we find `it₂` (the common element) repeat if path₁.isEmpty then guard (it₂ == e₁) break if path₁.back! == it₂ then -- found it! break path₁ := path₁.pop Hs₁ := Hs₁.pop -- 4. Build transitivity proof let mut pr? : Option Expr := none let mut lhs := e₁ for h : i in [:path₁.size] do pr? ← some <$> mkTransOpt pr? (← mkProof lhs path₁[i] Hs₁[i]! heqProofs) heqProofs lhs := path₁[i] let mut i := Hs₂.size while i > 0 do i := i - 1 pr? ← some <$> mkTransOpt pr? (← mkProof lhs path₂[i]! Hs₂[i]! heqProofs) heqProofs lhs := path₂[i]! let mut some pr := pr? | failure if heqProofs && !asHEq then pr ← mkAppM ``eq_of_heq #[pr] else if !heqProofs && asHEq then pr ← mkAppM ``heq_of_eq #[pr] return pr /-- Build a proof for `e₁ = e₂`. The result is `none` if `e₁` and `e₂` are not in the same equivalence class. -/ @[inline] partial def getEqProof (e₁ e₂ : Expr) : CCM (Option Expr) := getEqProofCore e₁ e₂ false /-- Build a proof for `e₁ ≍ e₂`. The result is `none` if `e₁` and `e₂` are not in the same equivalence class. -/ @[inline] partial def getHEqProof (e₁ e₂ : Expr) : CCM (Option Expr) := getEqProofCore e₁ e₂ true end /-- Build a proof for `e = True`. Fails if `e` is not known to be true. -/ def getEqTrueProof (e : Expr) : CCM Expr := do guard (← isEqTrue e) let some p ← getEqProof e (.const ``True []) | failure return p /-- Build a proof for `e = False`. Fails if `e` is not known to be false. -/ def getEqFalseProof (e : Expr) : CCM Expr := do guard (← isEqFalse e) let some p ← getEqProof e (.const ``False []) | failure return p /-- Build a proof for `a = b`. Fails if `a` and `b` are not known to be equal. -/ def getPropEqProof (a b : Expr) : CCM Expr := do guard (← isEqv a b) let some p ← getEqProof a b | failure return p /-- Build a proof of `False` if the context is inconsistent. Returns `none` if `False` is not known to be true. -/ def getInconsistencyProof : CCM (Option Expr) := do guard !(← get).frozePartitions if let some p ← getEqProof (.const ``True []) (.const ``False []) then return some (← mkAppM ``false_of_true_eq_false #[p]) else return none /-- Given `a`, `a₁` and `a₁NeB : a₁ ≠ b`, return a proof of `a ≠ b` if `a` and `a₁` are in the same equivalence class. -/ def mkNeOfEqOfNe (a a₁ a₁NeB : Expr) : CCM (Option Expr) := do guard (← isEqv a a₁) if a == a₁ then return some a₁NeB let aEqA₁ ← getEqProof a a₁ match aEqA₁ with | none => return none -- failed to build proof | some aEqA₁ => mkAppM ``ne_of_eq_of_ne #[aEqA₁, a₁NeB] /-- Given `aNeB₁ : a ≠ b₁`, `b₁` and `b`, return a proof of `a ≠ b` if `b` and `b₁` are in the same equivalence class. -/ def mkNeOfNeOfEq (aNeB₁ b₁ b : Expr) : CCM (Option Expr) := do guard (← isEqv b b₁) if b == b₁ then return some aNeB₁ let b₁EqB ← getEqProof b b₁ match b₁EqB with | none => return none -- failed to build proof | some b₁EqB => mkAppM ``ne_of_ne_of_eq #[aNeB₁, b₁EqB] /-- Return the proof of `e₁ = e₂` using `ac_rfl` tactic. -/ def mkACProof (e₁ e₂ : Expr) : MetaM Expr := do let eq ← mkEq e₁ e₂ let .mvar m ← mkFreshExprSyntheticOpaqueMVar eq | failure AC.rewriteUnnormalizedRefl m let pr ← instantiateMVars (.mvar m) mkExpectedTypeHint pr eq /-- Given `tr := t*r` `sr := s*r` `tEqs : t = s`, return a proof for `tr = sr` We use `a*b` to denote an AC application. That is, `(a*b)*(c*a)` is the term `a*a*b*c`. -/ def mkACSimpProof (tr t s r sr : ACApps) (tEqs : DelayedExpr) : MetaM DelayedExpr := do if tr == t then return tEqs else if tr == sr then let some tre := tr.toExpr | failure DelayedExpr.ofExpr <$> mkEqRefl tre else let .apps op _ := tr | failure let some re := r.toExpr | failure let some te := t.toExpr | failure let some se := s.toExpr | failure let some tre := tr.toExpr | failure let some sre := sr.toExpr | failure let opr := op.app re -- `(*) r` let rt := mkApp2 op re te -- `r * t` let rs := mkApp2 op re se -- `r * s` let rtEqrs := DelayedExpr.congrArg opr tEqs let trEqrt ← mkACProof tre rt let rsEqsr ← mkACProof rs sre return .eqTrans (.eqTrans trEqrt rtEqrs) rsEqsr /-- Given `e := lhs * r` and `H : lhs = rhs`, return `rhs * r` and the proof of `e = rhs * r`. -/ def simplifyACCore (e lhs rhs : ACApps) (H : DelayedExpr) : CCM (ACApps × DelayedExpr) := do guard (lhs.isSubset e) if e == lhs then return (rhs, H) else let .apps op _ := e | failure let newArgs := e.diff lhs let r : ACApps := if newArgs.isEmpty then default else .mkApps op newArgs let newArgs := ACApps.append op rhs newArgs let newE := ACApps.mkApps op newArgs let some true := (← get).opInfo[op]? | failure let newPr ← mkACSimpProof e lhs rhs r newE H return (newE, newPr) /-- The single step of `simplifyAC`. Simplifies an expression `e` by either simplifying one argument to the AC operator, or the whole expression. -/ def simplifyACStep (e : ACApps) : CCM (Option (ACApps × DelayedExpr)) := do if let .apps _ args := e then for h : i in [:args.size] do if i == 0 || args[i] != (args[i - 1]'(Nat.lt_of_le_of_lt (i.sub_le 1) h.2.1)) then let some ae := (← get).acEntries[args[i]]? | failure let occs := ae.RLHSOccs let mut Rlhs? : Option ACApps := none for Rlhs in occs do if Rlhs.isSubset e then Rlhs? := some Rlhs break if let some Rlhs := Rlhs? then let some (Rrhs, H) := (← get).acR[Rlhs]? | failure return (some <| ← simplifyACCore e Rlhs Rrhs H) else if let some p := (← get).acR[e]? then return some p return none /-- If `e` can be simplified by the AC module, return the simplified term and the proof term of the equality. -/ def simplifyAC (e : ACApps) : CCM (Option (ACApps × DelayedExpr)) := do let mut some (curr, pr) ← simplifyACStep e | return none repeat let some (newCurr, newPr) ← simplifyACStep curr | break pr := .eqTransOpt e curr newCurr pr newPr curr := newCurr return some (curr, pr) end Mathlib.Tactic.CC.CCM
.lake/packages/mathlib/Mathlib/Tactic/CC/Addition.lean
import Mathlib.Data.Option.Defs import Mathlib.Tactic.CC.MkProof /-! # Process when an new equation is added to a congruence closure -/ universe u open Lean Meta Elab Tactic Std MessageData namespace Mathlib.Tactic.CC.CCM /-- Update the `todo` field of the state. -/ @[inline] def modifyTodo (f : Array TodoEntry → Array TodoEntry) : CCM Unit := modify fun cc => { cc with todo := f cc.todo } /-- Update the `acTodo` field of the state. -/ @[inline] def modifyACTodo (f : Array ACTodoEntry → Array ACTodoEntry) : CCM Unit := modify fun cc => { cc with acTodo := f cc.acTodo } /-- Read the `todo` field of the state. -/ @[inline] def getTodo : CCM (Array TodoEntry) := do return (← get).todo /-- Read the `acTodo` field of the state. -/ @[inline] def getACTodo : CCM (Array ACTodoEntry) := do return (← get).acTodo /-- Add a new entry to the end of the todo list. See also `pushEq`, `pushHEq` and `pushReflEq`. -/ def pushTodo (lhs rhs : Expr) (H : EntryExpr) (heqProof : Bool) : CCM Unit := do modifyTodo fun todo => todo.push (lhs, rhs, H, heqProof) /-- Add the equality proof `H : lhs = rhs` to the end of the todo list. -/ @[inline] def pushEq (lhs rhs : Expr) (H : EntryExpr) : CCM Unit := pushTodo lhs rhs H false /-- Add the heterogeneous equality proof `H : lhs ≍ rhs` to the end of the todo list. -/ @[inline] def pushHEq (lhs rhs : Expr) (H : EntryExpr) : CCM Unit := pushTodo lhs rhs H true /-- Add `rfl : lhs = rhs` to the todo list. -/ @[inline] def pushReflEq (lhs rhs : Expr) : CCM Unit := pushEq lhs rhs .refl /-- Update the `child` so its parent becomes `parent`. -/ def addOccurrence (parent child : Expr) (symmTable : Bool) : CCM Unit := do let childRoot ← getRoot child modify fun ccs => { ccs with parents := ccs.parents.alter childRoot fun ps? => let ps := ps?.getD ∅ ps.insert { expr := parent, symmTable } } /-- Record the instance `e` and add it to the set of known defeq instances. -/ def propagateInstImplicit (e : Expr) : CCM Unit := do let type ← inferType e let type ← normalize type match (← get).instImplicitReprs[type]? with | some l => for e' in l do if ← pureIsDefEq e e' then pushReflEq e e' return modify fun ccs => { ccs with instImplicitReprs := ccs.instImplicitReprs.insert type (e :: l) } | none => modify fun ccs => { ccs with instImplicitReprs := ccs.instImplicitReprs.insert type [e] } /-- Return the `CongruencesKey` associated with an expression of the form `f a`. -/ def mkCongruencesKey (e : Expr) : CCM CongruencesKey := do let .app f a := e | failure if (← getEntry e).any Entry.fo then -- first-order case, where we do not consider all partial applications e.withApp fun fn args => do return .fo (← getRoot fn) (← args.mapM getRoot) else return .ho (← getRoot f) (← getRoot a) /-- Return the `SymmCongruencesKey` associated with the equality `lhs = rhs`. -/ def mkSymmCongruencesKey (lhs rhs : Expr) : CCM SymmCongruencesKey := do let lhs ← getRoot lhs let rhs ← getRoot rhs if hash lhs > hash rhs then return { h₁ := rhs, h₂ := lhs } else return { h₁ := lhs, h₂ := rhs } /-- Auxiliary function for comparing `lhs₁ ~ rhs₁` and `lhs₂ ~ rhs₂`, when `~` is symmetric/commutative. It returns `true` (equal) for `a ~ b` `b ~ a`. -/ def compareSymmAux (lhs₁ rhs₁ lhs₂ rhs₂ : Expr) : CCM Bool := do let lhs₁ ← getRoot lhs₁ let rhs₁ ← getRoot rhs₁ let lhs₂ ← getRoot lhs₂ let rhs₂ ← getRoot rhs₂ let (lhs₁, rhs₁) := if rhs₁.lt lhs₁ then (rhs₁, lhs₁) else (lhs₁, rhs₁) let (lhs₂, rhs₂) := if rhs₂.lt lhs₂ then (rhs₂, lhs₂) else (lhs₂, rhs₂) return lhs₁ == lhs₂ && rhs₁ == rhs₂ /-- Given ``k₁ := (R₁ lhs₁ rhs₁, `R₁)`` and ``k₂ := (R₂ lhs₂ rhs₂, `R₂)``, return `true` if `R₁ lhs₁ rhs₁` is equivalent to `R₂ lhs₂ rhs₂` modulo the symmetry of `R₁` and `R₂`. -/ def compareSymm : (k₁ k₂ : Expr × Name) → CCM Bool | (e₁, n₁), (e₂, n₂) => do if n₁ != n₂ then return false if n₁ == ``Eq || n₁ == ``Iff then compareSymmAux e₁.appFn!.appArg! e₁.appArg! e₂.appFn!.appArg! e₂.appArg! else let some (_, lhs₁, rhs₁) ← e₁.relSidesIfSymm? | failure let some (_, lhs₂, rhs₂) ← e₂.relSidesIfSymm? | failure compareSymmAux lhs₁ rhs₁ lhs₂ rhs₂ /-- Given `e := R lhs rhs`, if `R` is a reflexive relation and `lhs` is equivalent to `rhs`, add equality `e = True`. -/ def checkEqTrue (e : Expr) : CCM Unit := do let some (_, lhs, rhs) ← e.relSidesIfRefl? | return if ← isEqv e (.const ``True []) then return -- it is already equivalent to `True` let lhsR ← getRoot lhs let rhsR ← getRoot rhs if lhsR != rhsR then return -- Add `e = True` pushEq e (.const ``True []) .eqTrue /-- If the congruence table (`congruences` field) has congruent expression to `e`, add the equality to the todo list. If not, add `e` to the congruence table. -/ def addCongruenceTable (e : Expr) : CCM Unit := do guard e.isApp let k ← mkCongruencesKey e if let some es := (← get).congruences[k]? then for oldE in es do if ← isCongruent e oldE then -- Found new equivalence: `e ~ oldE` -- 1. Update `cgRoot` field for `e` let some currEntry ← getEntry e | failure let newEntry := { currEntry with cgRoot := oldE } modify fun ccs => { ccs with entries := ccs.entries.insert e newEntry } -- 2. Put new equivalence in the todo queue -- TODO(Leo): check if the following line is a bottleneck let heqProof ← (!·) <$> pureIsDefEq (← inferType e) (← inferType oldE) pushTodo e oldE .congr heqProof return modify fun ccs => { ccs with congruences := ccs.congruences.insert k (e :: es) } else modify fun ccs => { ccs with congruences := ccs.congruences.insert k [e] } /-- If the symm congruence table (`symmCongruences` field) has congruent expression to `e`, add the equality to the todo list. If not, add `e` to the symm congruence table. -/ def addSymmCongruenceTable (e : Expr) : CCM Unit := do let some (rel, lhs, rhs) ← e.relSidesIfSymm? | failure let k ← mkSymmCongruencesKey lhs rhs let newP := (e, rel) if let some ps := (← get).symmCongruences[k]? then for p in ps do if ← compareSymm newP p then -- Found new equivalence: `e ~ p.1` -- 1. Update `cgRoot` field for `e` let some currEntry ← getEntry e | failure let newEntry := { currEntry with cgRoot := p.1 } modify fun ccs => { ccs with entries := ccs.entries.insert e newEntry } -- 2. Put new equivalence in the TODO queue -- NOTE(gabriel): support for symmetric relations is pretty much broken, -- since it ignores all arguments except the last two ones. -- e.g. this would claim that `ModEq n a b` and `ModEq m a b` are equivalent. -- Whitelist some relations to contain breakage: if rel == ``Eq || e.getAppNumArgs == 2 then pushEq e p.1 .congr checkEqTrue e return modify fun ccs => { ccs with symmCongruences := ccs.symmCongruences.insert k (newP :: ps) } checkEqTrue e else modify fun ccs => { ccs with symmCongruences := ccs.symmCongruences.insert k [newP] } checkEqTrue e /-- Given subsingleton elements `a` and `b` which are not necessarily of the same type, if the types of `a` and `b` are equivalent, add the (heterogeneous) equality proof between `a` and `b` to the todo list. -/ def pushSubsingletonEq (a b : Expr) : CCM Unit := do -- Remark: we must normalize here because we have to do so before -- internalizing the types of `a` and `b`. let A ← normalize (← inferType a) let B ← normalize (← inferType b) -- TODO(Leo): check if the following test is a performance bottleneck if ← pureIsDefEq A B then let proof ← mkAppM ``FastSubsingleton.elim #[a, b] pushEq a b proof else let some AEqB ← getEqProof A B | failure let proof ← mkAppM ``FastSubsingleton.helim #[AEqB, a, b] pushHEq a b proof /-- Given the equivalent expressions `oldRoot` and `newRoot` the root of `oldRoot` is `newRoot`, if `oldRoot` has root representative of subsingletons, try to push the equality proof between their root representatives to the todo list, or update the root representative to `newRoot`. -/ def checkNewSubsingletonEq (oldRoot newRoot : Expr) : CCM Unit := do guard (← isEqv oldRoot newRoot) guard ((← getRoot oldRoot) == newRoot) let some it₁ := (← get).subsingletonReprs[oldRoot]? | return if let some it₂ := (← get).subsingletonReprs[newRoot]? then pushSubsingletonEq it₁ it₂ else modify fun ccs => { ccs with subsingletonReprs := ccs.subsingletonReprs.insert newRoot it₁ } /-- Get all lambda expressions in the equivalence class of `e` and append to `r`. `e` must be the root of its equivalence class. -/ def getEqcLambdas (e : Expr) (r : Array Expr := #[]) : CCM (Array Expr) := do guard ((← getRoot e) == e) let mut r := r let some ee ← getEntry e | failure unless ee.hasLambdas do return r let mut it := e repeat if it.isLambda then r := r.push it let some itN ← getEntry it | failure it := itN.next until it == e return r /-- Remove `fn` and expressions whose type isn't def-eq to `fn`'s type out from `lambdas`, return the remaining lambdas applied to the reversed arguments. -/ def propagateBeta (fn : Expr) (revArgs : Array Expr) (lambdas : Array Expr) (newLambdaApps : Array Expr := #[]) : CCM (Array Expr) := do let mut newLambdaApps := newLambdaApps for lambda in lambdas do guard lambda.isLambda if fn != lambda then if ← pureIsDefEq (← inferType fn) (← inferType lambda) then let newApp := mkAppRev lambda revArgs newLambdaApps := newLambdaApps.push newApp return newLambdaApps /-- Given `lhs`, `rhs`, and `header := "my header:"`, Trace `my header: lhs = rhs`. -/ def dbgTraceACEq (header : String) (lhs rhs : ACApps) : CCM Unit := do let ccs ← get trace[Debug.Meta.Tactic.cc.ac] group (ofFormat (header ++ .line) ++ ccs.ppACApps lhs ++ ofFormat (.line ++ "=" ++ .line) ++ ccs.ppACApps rhs) /-- Trace the state of AC module. -/ def dbgTraceACState : CCM Unit := do let ccs ← get trace[Debug.Meta.Tactic.cc.ac] group ("state: " ++ nest 6 ccs.ppAC) /-- Insert or erase `lhs` to the occurrences of `arg` on an equality in `acR`. -/ def insertEraseROcc (arg : Expr) (lhs : ACApps) (inLHS isInsert : Bool) : CCM Unit := do let some entry := (← get).acEntries[arg]? | failure let occs := entry.ROccs inLHS let newOccs := if isInsert then occs.insert lhs else occs.erase lhs let newEntry := if inLHS then { entry with RLHSOccs := newOccs } else { entry with RRHSOccs := newOccs } modify fun ccs => { ccs with acEntries := ccs.acEntries.insert arg newEntry } /-- Insert or erase `lhs` to the occurrences of arguments of `e` on an equality in `acR`. -/ def insertEraseROccs (e lhs : ACApps) (inLHS isInsert : Bool) : CCM Unit := do match e with | .apps _ args => insertEraseROcc args[0]! lhs inLHS isInsert for h : i in [1:args.size] do if args[i] != args[i - 1]! then insertEraseROcc args[i] lhs inLHS isInsert | .ofExpr e => insertEraseROcc e lhs inLHS isInsert /-- Insert `lhs` to the occurrences of arguments of `e` on an equality in `acR`. -/ @[inline] def insertROccs (e lhs : ACApps) (inLHS : Bool) : CCM Unit := insertEraseROccs e lhs inLHS true /-- Erase `lhs` to the occurrences of arguments of `e` on an equality in `acR`. -/ @[inline] def eraseROccs (e lhs : ACApps) (inLHS : Bool) : CCM Unit := insertEraseROccs e lhs inLHS false /-- Insert `lhs` to the occurrences on an equality in `acR` corresponding to the equality `lhs := rhs`. -/ @[inline] def insertRBHSOccs (lhs rhs : ACApps) : CCM Unit := do insertROccs lhs lhs true insertROccs rhs lhs false /-- Erase `lhs` to the occurrences on an equality in `acR` corresponding to the equality `lhs := rhs`. -/ @[inline] def eraseRBHSOccs (lhs rhs : ACApps) : CCM Unit := do eraseROccs lhs lhs true eraseROccs rhs lhs false /-- Insert `lhs` to the occurrences of arguments of `e` on the right-hand side of an equality in `acR`. -/ @[inline] def insertRRHSOccs (e lhs : ACApps) : CCM Unit := insertROccs e lhs false /-- Erase `lhs` to the occurrences of arguments of `e` on the right-hand side of an equality in `acR`. -/ @[inline] def eraseRRHSOccs (e lhs : ACApps) : CCM Unit := eraseROccs e lhs false /-- Try to simplify the right-hand sides of equalities in `acR` by `H : lhs = rhs`. -/ def composeAC (lhs rhs : ACApps) (H : DelayedExpr) : CCM Unit := do let some x := (← get).getVarWithLeastRHSOccs lhs | failure let some ent := (← get).acEntries[x]? | failure let occs := ent.RRHSOccs for Rlhs in occs do let some (Rrhs, RH) := (← get).acR[Rlhs]? | failure if lhs.isSubset Rrhs then let (newRrhs, RrhsEqNewRrhs) ← simplifyACCore Rrhs lhs rhs H let newRH := DelayedExpr.eqTransOpt Rlhs Rrhs newRrhs RH RrhsEqNewRrhs modify fun ccs => { ccs with acR := ccs.acR.insert Rlhs (newRrhs, newRH) } eraseRRHSOccs Rrhs Rlhs insertRRHSOccs newRrhs Rlhs let ccs ← get trace[Debug.Meta.Tactic.cc.ac] group <| let oldRw := paren (ccs.ppACApps Rlhs ++ ofFormat (Format.line ++ "-->" ++ .line) ++ ccs.ppACApps Rrhs) let newRw := paren (ccs.ppACApps lhs ++ ofFormat (Format.line ++ "-->" ++ .line) ++ ccs.ppACApps rhs) "compose: " ++ nest 9 (group (oldRw ++ ofFormat (Format.line ++ "with" ++ .line) ++ newRw) ++ ofFormat (Format.line ++ ":=" ++ .line) ++ ccs.ppACApps newRrhs) /-- Try to simplify the left-hand sides of equalities in `acR` by `H : lhs = rhs`. -/ def collapseAC (lhs rhs : ACApps) (H : DelayedExpr) : CCM Unit := do let some x := (← get).getVarWithLeastLHSOccs lhs | failure let some ent := (← get).acEntries[x]? | failure let occs := ent.RLHSOccs for Rlhs in occs do if lhs.isSubset Rlhs then let some (Rrhs, RH) := (← get).acR[Rlhs]? | failure eraseRBHSOccs Rlhs Rrhs modify fun ccs => { ccs with acR := ccs.acR.erase Rlhs } let (newRlhs, RlhsEqNewRlhs) ← simplifyACCore Rlhs lhs rhs H let newRlhsEqRlhs := DelayedExpr.eqSymmOpt Rlhs newRlhs RlhsEqNewRlhs let newRH := DelayedExpr.eqTransOpt newRlhs Rlhs Rrhs newRlhsEqRlhs RH modifyACTodo fun todo => todo.push (newRlhs, Rrhs, newRH) let ccs ← get trace[Debug.Meta.Tactic.cc.ac] group <| let newRw := paren (ccs.ppACApps lhs ++ ofFormat (Format.line ++ "-->" ++ .line) ++ ccs.ppACApps rhs) let oldRw := paren (ccs.ppACApps Rrhs ++ ofFormat (Format.line ++ "<--" ++ .line) ++ ccs.ppACApps Rlhs) "collapse: " ++ nest 10 (group (newRw ++ ofFormat (Format.line ++ "at" ++ .line) ++ oldRw) ++ ofFormat (Format.line ++ ":=" ++ .line) ++ ccs.ppACApps newRlhs) /-- Given `ra := a*r` `sb := b*s` `ts := t*s` `tr := t*r` `tsEqa : t*s = a` `trEqb : t*r = b`, return a proof for `ra = sb`. We use `a*b` to denote an AC application. That is, `(a*b)*(c*a)` is the term `a*a*b*c`. -/ def mkACSuperposeProof (ra sb a b r s ts tr : ACApps) (tsEqa trEqb : DelayedExpr) : MetaM DelayedExpr := do let .apps _ _ := tr | failure let .apps op _ := ts | failure let some tse := ts.toExpr | failure let some re := r.toExpr | failure let some tre := tr.toExpr | failure let some se := s.toExpr | failure let some ae := a.toExpr | failure let some be := b.toExpr | failure let some rae := ra.toExpr | failure let some sbe := sb.toExpr | failure let tsrEqar := DelayedExpr.congrFun (.congrArg op tsEqa) r -- `(t * s) * r = a * r` let trsEqbs := DelayedExpr.congrFun (.congrArg op trEqb) s -- `(t * r) * s = b * s` let tsr := mkApp2 op tse re -- `(t * s) * r` let trs := mkApp2 op tre se -- `(t * r) * s` let ar := mkApp2 op ae re -- `a * r` let bs := mkApp2 op be se -- `b * r` let tsrEqtrs ← mkACProof tsr trs -- `(t * s) * r = (t * r) * s` let raEqar ← mkACProof rae ar -- `r * a = a * r` let bsEqsb ← mkACProof bs sbe -- `b * s = s * b` return .eqTrans raEqar (.eqTrans (.eqSymm tsrEqar) (.eqTrans tsrEqtrs (.eqTrans trsEqbs bsEqsb))) /-- Given `tsEqa : ts = a`, for each equality `trEqb : tr = b` in `acR` where the intersection `t` of `ts` and `tr` is nonempty, let `ts = t*s` and `tr := t*r`, add a new equality `r*a = s*b`. -/ def superposeAC (ts a : ACApps) (tsEqa : DelayedExpr) : CCM Unit := do let .apps op args := ts | return for hi : i in [:args.size] do if i == 0 || args[i] != (args[i - 1]'(Nat.lt_of_le_of_lt (i.sub_le 1) hi.2.1)) then let some ent := (← get).acEntries[args[i]]? | failure let occs := ent.RLHSOccs for tr in occs do let .apps optr _ := tr | continue unless optr == op do continue let some (b, trEqb) := (← get).acR[tr]? | failure let tArgs := ts.intersection tr guard !tArgs.isEmpty let t := ACApps.mkApps op tArgs let sArgs := ts.diff t guard !sArgs.isEmpty let rArgs := tr.diff t guard !rArgs.isEmpty let s := ACApps.mkApps op sArgs let r := ACApps.mkApps op rArgs let ra := ACApps.mkFlatApps op r a let sb := ACApps.mkFlatApps op s b let some true := (← get).opInfo[op]? | failure let raEqsb ← mkACSuperposeProof ra sb a b r s ts tr tsEqa trEqb modifyACTodo fun todo => todo.push (ra, sb, raEqsb) let ccs ← get trace[Debug.Meta.Tactic.cc.ac] group <| let rw₁ := paren (ccs.ppACApps ts ++ ofFormat (Format.line ++ "-->" ++ .line) ++ ccs.ppACApps a) let rw₂ := paren (ccs.ppACApps tr ++ ofFormat (Format.line ++ "-->" ++ .line) ++ ccs.ppACApps b) let eq := paren (ccs.ppACApps ra ++ ofFormat (Format.line ++ "-->" ++ .line) ++ ccs.ppACApps sb) "superpose: " ++ nest 11 (group (rw₁ ++ ofFormat (Format.line ++ "with" ++ .line) ++ rw₂) ++ ofFormat (Format.line ++ ":=" ++ .line) ++ eq) /-- Process the tasks in the `acTodo` field. -/ def processAC : CCM Unit := do repeat let acTodo ← getACTodo let mut some (lhs, rhs, H) := acTodo.back? | break modifyACTodo fun _ => acTodo.pop let lhs₀ := lhs let rhs₀ := rhs dbgTraceACEq "process eq:" lhs rhs -- Forward simplification lhs/rhs if let some p ← simplifyAC lhs then H := .eqTransOpt p.1 lhs rhs (.eqSymmOpt lhs p.1 p.2) H lhs := p.1 if let some p ← simplifyAC rhs then H := .eqTransOpt lhs rhs p.1 H p.2 rhs := p.1 if lhs != lhs₀ || rhs != rhs₀ then dbgTraceACEq "after simp:" lhs rhs -- Skip propagation if the equality is trivial. if lhs == rhs then trace[Debug.Meta.Tactic.cc.ac] "trivial" continue -- Propagate new equality to congruence closure module if let .ofExpr lhse := lhs then if let .ofExpr rhse := rhs then if (← getRoot lhse) != (← getRoot rhse) then pushEq lhse rhse (.ofDExpr H) -- Orient if compare lhs rhs == .lt then H := .eqSymmOpt lhs rhs H (lhs, rhs) := (rhs, lhs) -- Backward simplification composeAC lhs rhs H collapseAC lhs rhs H -- Superposition superposeAC lhs rhs H -- Update acR modify fun ccs => { ccs with acR := ccs.acR.insert lhs (rhs, H) } insertRBHSOccs lhs rhs let ccs ← get trace[Debug.Meta.Tactic.cc.ac] group <| "new rw: " ++ group (ccs.ppACApps lhs ++ ofFormat (Format.line ++ "-->" ++ .line) ++ ccs.ppACApps rhs) /-- Given AC variables `e₁` and `e₂` which are in the same equivalence class, add the proof of `e₁ = e₂` to the AC module. -/ def addACEq (e₁ e₂ : Expr) : CCM Unit := do dbgTraceACEq "cc eq:" e₁ e₂ modifyACTodo fun acTodo => acTodo.push (e₁, e₂, .eqProof e₁ e₂) processAC dbgTraceACState /-- If the root expression of `e` is AC variable, add equality to AC module. If not, register the AC variable to the root entry. -/ def setACVar (e : Expr) : CCM Unit := do let eRoot ← getRoot e let some rootEntry ← getEntry eRoot | failure if let some acVar := rootEntry.acVar then addACEq acVar e else let newRootEntry := { rootEntry with acVar := some e } modify fun ccs => { ccs with entries := ccs.entries.insert eRoot newRootEntry } /-- If `e` isn't an AC variable, set `e` as an new AC variable. -/ def internalizeACVar (e : Expr) : CCM Bool := do let ccs ← get if ccs.acEntries.contains e then return false modify fun _ => { ccs with acEntries := ccs.acEntries.insert e { idx := ccs.acEntries.size } } setACVar e return true /-- If `e` is of the form `op e₁ e₂` where `op` is an associative and commutative binary operator, return the canonical form of `op`. -/ def isAC (e : Expr) : CCM (Option Expr) := do let .app (.app op _) _ := e | return none let ccs ← get if let some cop := ccs.canOps[op]? then let some b := ccs.opInfo[cop]? | throwError "opInfo should contain all canonical operators in canOps" return bif b then some cop else none for (cop, b) in ccs.opInfo do if ← pureIsDefEq op cop then modify fun _ => { ccs with canOps := ccs.canOps.insert op cop } return bif b then some cop else none let b ← try let aop ← mkAppM ``Std.Associative #[op] let some _ ← synthInstance? aop | failure let cop ← mkAppM ``Std.Commutative #[op] let some _ ← synthInstance? cop | failure pure true catch _ => pure false modify fun _ => { ccs with canOps := ccs.canOps.insert op op opInfo := ccs.opInfo.insert op b } return bif b then some op else none /-- Given `e := op₁ (op₂ a₁ a₂) (op₃ a₃ a₄)` where `opₙ`s are canonicalized to `op`, internalize `aₙ`s as AC variables and return `(op (op a₁ a₂) (op a₃ a₄), args ++ #[a₁, a₂, a₃, a₄])`. -/ partial def convertAC (op e : Expr) (args : Array Expr := #[]) : CCM (Array Expr × Expr) := do if let some currOp ← isAC e then if op == currOp then let (args, arg₁) ← convertAC op e.appFn!.appArg! args let (args, arg₂) ← convertAC op e.appArg! args return (args, mkApp2 op arg₁ arg₂) let _ ← internalizeACVar e return (args.push e, e) /-- Internalize `e` so that the AC module can deal with the given expression. If the expression does not contain an AC operator, or the parent expression is already processed by `internalizeAC`, this operation does nothing. -/ def internalizeAC (e : Expr) (parent? : Option Expr) : CCM Unit := do let some op ← isAC e | return let parentOp? ← parent?.casesOn (pure none) isAC if parentOp?.any (· == op) then return unless (← internalizeACVar e) do return let (args, norme) ← convertAC op e let rep := ACApps.mkApps op args let some true := (← get).opInfo[op]? | failure let some repe := rep.toExpr | failure let pr ← mkACProof norme repe let ccs ← get trace[Debug.Meta.Tactic.cc.ac] group <| let d := paren (ccs.ppACApps e ++ ofFormat (" :=" ++ Format.line) ++ ofExpr e) "new term: " ++ d ++ ofFormat (Format.line ++ "===>" ++ .line) ++ ccs.ppACApps rep modifyACTodo fun todo => todo.push (e, rep, pr) processAC dbgTraceACState mutual /-- The specialized `internalizeCore` for applications or literals. -/ partial def internalizeAppLit (e : Expr) : CCM Unit := do if ← isInterpretedValue e then mkEntry e true if (← get).values then return -- we treat values as atomic symbols else mkEntry e false if (← get).values && isValue e then return -- we treat values as atomic symbols -- At this point we should have handled a literal; otherwise we fail. unless e.isApp do return if let some (_, lhs, rhs) ← e.relSidesIfSymm? then internalizeCore lhs (some e) internalizeCore rhs (some e) addOccurrence e lhs true addOccurrence e rhs true addSymmCongruenceTable e else if (← mkCCCongrTheorem e).isSome then let fn := e.getAppFn let apps := e.getAppApps guard (apps.size > 0) guard (apps.back! == e) let mut pinfo : List ParamInfo := [] let state ← get if state.ignoreInstances then pinfo := (← getFunInfoNArgs fn apps.size).paramInfo.toList if state.hoFns.isSome && fn.isConst && !(state.hoFns.iget.contains fn.constName) then for h : i in [:apps.size] do let arg := apps[i].appArg! addOccurrence e arg false if pinfo.head?.any ParamInfo.isInstImplicit then -- We do not recurse on instances when `(← get).config.ignoreInstances` is `true`. mkEntry arg false propagateInstImplicit arg else internalizeCore arg (some e) unless pinfo.isEmpty do pinfo := pinfo.tail internalizeCore fn (some e) addOccurrence e fn false setFO e addCongruenceTable e else -- Expensive case where we store a quadratic number of occurrences, -- as described in the paper "Congruence Closure in Intensional Type Theory" for h : i in [:apps.size] do let curr := apps[i] let .app currFn currArg := curr | unreachable! if i < apps.size - 1 then mkEntry curr false for h : j in [i:apps.size] do addOccurrence apps[j] currArg false addOccurrence apps[j] currFn false if pinfo.head?.any ParamInfo.isInstImplicit then -- We do not recurse on instances when `(← get).config.ignoreInstances` is `true`. mkEntry currArg false mkEntry currFn false propagateInstImplicit currArg else internalizeCore currArg (some e) mkEntry currFn false unless pinfo.isEmpty do pinfo := pinfo.tail addCongruenceTable curr applySimpleEqvs e /-- Internalize `e` so that the congruence closure can deal with the given expression. Don't forget to process the tasks in the `todo` field later. -/ partial def internalizeCore (e : Expr) (parent? : Option Expr) : CCM Unit := do guard !e.hasLooseBVars /- We allow metavariables after partitions have been frozen. -/ if e.hasExprMVar && !(← get).frozePartitions then return /- Check whether `e` has already been internalized. -/ if (← getEntry e).isNone then match e with | .bvar _ => unreachable! | .sort _ => pure () | .const _ _ | .mvar _ => mkEntry e false | .lam _ _ _ _ | .letE _ _ _ _ _ => mkEntry e false | .fvar f => mkEntry e false if let some v ← f.getValue? then pushReflEq e v | .mdata _ e' => mkEntry e false internalizeCore e' e addOccurrence e e' false pushReflEq e e' | .forallE _ t b _ => if e.isArrow then if ← isProp t <&&> isProp b then internalizeCore t e internalizeCore b e addOccurrence e t false addOccurrence e b false propagateImpUp e if ← isProp e then mkEntry e false | .app _ _ | .lit _ => internalizeAppLit e | .proj sn i pe => mkEntry e false let some fn := (getStructureFields (← getEnv) sn)[i]? | failure let e' ← pe.mkDirectProjection fn internalizeAppLit e' pushReflEq e e' /- Remark: if should invoke `internalizeAC` even if the test `(← getEntry e).isNone` above failed. Reason, the first time `e` was visited, it may have been visited with a different parent. -/ if (← get).ac then internalizeAC e parent? /-- Propagate equality from `a` and `b` to `a ↔ b`. -/ partial def propagateIffUp (e : Expr) : CCM Unit := do let some (a, b) := e.iff? | failure if ← isEqTrue a then -- `a = True → (Iff a b) = b` pushEq e b (mkApp3 (.const ``iff_eq_of_eq_true_left []) a b (← getEqTrueProof a)) else if ← isEqTrue b then -- `b = True → (Iff a b) = a` pushEq e a (mkApp3 (.const ``iff_eq_of_eq_true_right []) a b (← getEqTrueProof b)) else if ← isEqv a b then -- `a = b → (Iff a b) = True` pushEq e (.const ``True []) (mkApp3 (.const ``iff_eq_true_of_eq []) a b (← getPropEqProof a b)) /-- Propagate equality from `a` and `b` to `a ∧ b`. -/ partial def propagateAndUp (e : Expr) : CCM Unit := do let some (a, b) := e.and? | failure if ← isEqTrue a then -- `a = True → (And a b) = b` pushEq e b (mkApp3 (.const ``and_eq_of_eq_true_left []) a b (← getEqTrueProof a)) else if ← isEqTrue b then -- `b = True → (And a b) = a` pushEq e a (mkApp3 (.const ``and_eq_of_eq_true_right []) a b (← getEqTrueProof b)) else if ← isEqFalse a then -- `a = False → (And a b) = False` pushEq e (.const ``False []) (mkApp3 (.const ``and_eq_of_eq_false_left []) a b (← getEqFalseProof a)) else if ← isEqFalse b then -- `b = False → (And a b) = False` pushEq e (.const ``False []) (mkApp3 (.const ``and_eq_of_eq_false_right []) a b (← getEqFalseProof b)) else if ← isEqv a b then -- `a = b → (And a b) = a` pushEq e a (mkApp3 (.const ``and_eq_of_eq []) a b (← getPropEqProof a b)) -- We may also add `a = Not b -> (And a b) = False` /-- Propagate equality from `a` and `b` to `a ∨ b`. -/ partial def propagateOrUp (e : Expr) : CCM Unit := do let some (a, b) := e.app2? ``Or | failure if ← isEqTrue a then -- `a = True → (Or a b) = True` pushEq e (.const ``True []) (mkApp3 (.const ``or_eq_of_eq_true_left []) a b (← getEqTrueProof a)) else if ← isEqTrue b then -- `b = True → (Or a b) = True` pushEq e (.const ``True []) (mkApp3 (.const ``or_eq_of_eq_true_right []) a b (← getEqTrueProof b)) else if ← isEqFalse a then -- `a = False → (Or a b) = b` pushEq e b (mkApp3 (.const ``or_eq_of_eq_false_left []) a b (← getEqFalseProof a)) else if ← isEqFalse b then -- `b = False → (Or a b) = a` pushEq e a (mkApp3 (.const ``or_eq_of_eq_false_right []) a b (← getEqFalseProof b)) else if ← isEqv a b then -- `a = b → (Or a b) = a` pushEq e a (mkApp3 (.const ``or_eq_of_eq []) a b (← getPropEqProof a b)) -- We may also add `a = Not b -> (Or a b) = True` /-- Propagate equality from `a` to `¬a`. -/ partial def propagateNotUp (e : Expr) : CCM Unit := do let some a := e.not? | failure if ← isEqTrue a then -- `a = True → Not a = False` pushEq e (.const ``False []) (mkApp2 (.const ``not_eq_of_eq_true []) a (← getEqTrueProof a)) else if ← isEqFalse a then -- `a = False → Not a = True` pushEq e (.const ``True []) (mkApp2 (.const ``not_eq_of_eq_false []) a (← getEqFalseProof a)) else if ← isEqv a e then let falsePr := mkApp2 (.const ``false_of_a_eq_not_a []) a (← getPropEqProof a e) let H := Expr.app (.const ``true_eq_false_of_false []) falsePr pushEq (.const ``True []) (.const ``False []) H /-- Propagate equality from `a` and `b` to `a → b`. -/ partial def propagateImpUp (e : Expr) : CCM Unit := do guard e.isArrow let .forallE _ a b _ := e | unreachable! if ← isEqTrue a then -- `a = True → (a → b) = b` pushEq e b (mkApp3 (.const ``imp_eq_of_eq_true_left []) a b (← getEqTrueProof a)) else if ← isEqFalse a then -- `a = False → (a → b) = True` pushEq e (.const ``True []) (mkApp3 (.const ``imp_eq_of_eq_false_left []) a b (← getEqFalseProof a)) else if ← isEqTrue b then -- `b = True → (a → b) = True` pushEq e (.const ``True []) (mkApp3 (.const ``imp_eq_of_eq_true_right []) a b (← getEqTrueProof b)) else if ← isEqFalse b then let isNot : Expr → Bool × Expr | .app (.const ``Not []) a => (true, a) | .forallE _ a (.const ``False []) _ => (true, a) | e => (false, e) if let (true, arg) := isNot a then if (← get).em then -- `b = False → (Not a → b) = a` pushEq e arg (mkApp3 (.const ``not_imp_eq_of_eq_false_right []) arg b (← getEqFalseProof b)) else -- `b = False → (a → b) = Not a` let notA := mkApp (.const ``Not []) a internalizeCore notA none pushEq e notA (mkApp3 (.const ``imp_eq_of_eq_false_right []) a b (← getEqFalseProof b)) else if ← isEqv a b then pushEq e (.const ``True []) (mkApp3 (.const ``imp_eq_true_of_eq []) a b (← getPropEqProof a b)) /-- Propagate equality from `p`, `a` and `b` to `if p then a else b`. -/ partial def propagateIteUp (e : Expr) : CCM Unit := do let .app (.app (.app (.app (.app (.const ``ite [lvl]) A) c) d) a) b := e | failure if ← isEqTrue c then -- `c = True → (ite c a b) = a` pushEq e a (mkApp6 (.const ``if_eq_of_eq_true [lvl]) c d A a b (← getEqTrueProof c)) else if ← isEqFalse c then -- `c = False → (ite c a b) = b` pushEq e b (mkApp6 (.const ``if_eq_of_eq_false [lvl]) c d A a b (← getEqFalseProof c)) else if ← isEqv a b then -- `a = b → (ite c a b) = a` pushEq e a (mkApp6 (.const ``if_eq_of_eq [lvl]) c d A a b (← getPropEqProof a b)) /-- Propagate equality from `a` and `b` to *disprove* `a = b`. -/ partial def propagateEqUp (e : Expr) : CCM Unit := do -- Remark: the positive case is implemented at `checkEqTrue` for any reflexive relation. let some (_, a, b) := e.eq? | failure let ra ← getRoot a let rb ← getRoot b if ra != rb then let mut raNeRb : Option Expr := none /- We disprove inequality for interpreted values here. The possible types of interpreted values are in `{String, Char, Int, Nat}`. 1- `String` `ra` & `rb` are string literals, so if `ra != rb`, `ra.int?.isNone` is `true` and we can prove `$ra ≠ $rb`. 2- `Char` `ra` & `rb` are the form of `Char.ofNat (nat_lit n)`, so if `ra != rb`, `ra.int?.isNone` is `true` and we can prove `$ra ≠ $rb` (assuming that `n` is not pathological value, i.e. `n.isValidChar`). 3- `Int`, `Nat` `ra` & `rb` are the form of `@OfNat.ofNat ℤ (nat_lit n) i` or `@Neg.neg ℤ i' (@OfNat.ofNat ℤ (nat_lit n) i)`, so even if `ra != rb`, `$ra ≠ $rb` can be false when `i` or `i'` in `ra` & `rb` are not alpha-equivalent but def-eq. If `ra.int? != rb.int?`, we can prove `$ra ≠ $rb` (assuming that `i` & `i'` are not pathological instances). -/ if ← isInterpretedValue ra <&&> isInterpretedValue rb <&&> pure (ra.int?.isNone || ra.int? != rb.int?) then raNeRb := some (Expr.app (.proj ``Iff 0 (← mkAppOptM ``bne_iff_ne #[none, none, none, ra, rb])) (← mkEqRefl (.const ``true []))) else if let some c₁ ← isConstructorApp? ra then if let some c₂ ← isConstructorApp? rb then if c₁.name != c₂.name then raNeRb ← withLocalDeclD `h (← mkEq ra rb) fun h => do mkLambdaFVars #[h] (← mkNoConfusion (.const ``False []) h) if let some raNeRb' := raNeRb then if let some aNeRb ← mkNeOfEqOfNe a ra raNeRb' then if let some aNeB ← mkNeOfNeOfEq aNeRb rb b then pushEq e (.const ``False []) (← mkEqFalse aNeB) /-- Propagate equality from subexpressions of `e` to `e`. -/ partial def propagateUp (e : Expr) : CCM Unit := do if (← get).inconsistent then return if e.isAppOfArity ``Iff 2 then propagateIffUp e else if e.isAppOfArity ``And 2 then propagateAndUp e else if e.isAppOfArity ``Or 2 then propagateOrUp e else if e.isAppOfArity ``Not 1 then propagateNotUp e else if e.isArrow then propagateImpUp e else if e.isIte then propagateIteUp e else if e.isEq then propagateEqUp e /-- This method is invoked during internalization and eagerly apply basic equivalences for term `e` Examples: - If `e := cast H e'`, then it merges the equivalence classes of `cast H e'` and `e'` In principle, we could mark theorems such as `cast_eq` as simplification rules, but this created problems with the builtin support for cast-introduction in the ematching module in Lean 3. TODO: check if this is now possible in Lean 4. Eagerly merging the equivalence classes is also more efficient. -/ partial def applySimpleEqvs (e : Expr) : CCM Unit := do if let .app (.app (.app (.app (.const ``cast [l₁]) A) B) H) a := e then /- ``` cast H a ≍ a theorem cast_heq.{l₁} : ∀ {A B : Sort l₁} (H : A = B) (a : A), @cast.{l₁} A B H a ≍ a ``` -/ let proof := mkApp4 (.const ``cast_heq [l₁]) A B H a pushHEq e a proof if let .app (.app (.app (.app (.app (.app (.const ``Eq.rec [l₁, l₂]) A) a) P) p) a') H := e then /- ``` t ▸ p ≍ p theorem eqRec_heq_self.{l₁, l₂} : ∀ {A : Sort l₁} {a : A} {P : (a' : A) → a = a' → Sort l₂} (p : P a rfl) {a' : A} (H : a = a'), HEq (@Eq.rec.{l₁ l₂} A a P p a' H) p ``` -/ let proof := mkApp6 (.const ``eqRec_heq_self [l₁, l₂]) A a P p a' H pushHEq e p proof if let .app (.app (.app (.const ``Ne [l₁]) α) a) b := e then -- `(a ≠ b) = (Not (a = b))` let newE := Expr.app (.const ``Not []) (mkApp3 (.const ``Eq [l₁]) α a b) internalizeCore newE none pushReflEq e newE if let some r ← e.reduceProjStruct? then pushReflEq e r let fn := e.getAppFn if fn.isLambda then let reducedE := e.headBeta if let some phandler := (← get).phandler then phandler.newAuxCCTerm reducedE internalizeCore reducedE none pushReflEq e reducedE let mut revArgs : Array Expr := #[] let mut it := e while it.isApp do revArgs := revArgs.push it.appArg! let fn := it.appFn! let rootFn ← getRoot fn let en ← getEntry rootFn if en.any Entry.hasLambdas then let lambdas ← getEqcLambdas rootFn let newLambdaApps ← propagateBeta fn revArgs lambdas for newApp in newLambdaApps do internalizeCore newApp none it := fn propagateUp e /-- If `e` is a subsingleton element, push the equality proof between `e` and its canonical form to the todo list or register `e` as the canonical form of itself. -/ partial def processSubsingletonElem (e : Expr) : CCM Unit := do let type ← inferType e let ss ← synthInstance? (← mkAppM ``FastSubsingleton #[type]) if ss.isNone then return -- type is not a subsingleton let type ← normalize type -- Make sure type has been internalized internalizeCore type none -- Try to find representative if let some it := (← get).subsingletonReprs[type]? then pushSubsingletonEq e it else modify fun ccs => { ccs with subsingletonReprs := ccs.subsingletonReprs.insert type e } let typeRoot ← getRoot type if typeRoot == type then return if let some it2 := (← get).subsingletonReprs[typeRoot]? then pushSubsingletonEq e it2 else modify fun ccs => { ccs with subsingletonReprs := ccs.subsingletonReprs.insert typeRoot e } /-- Add an new entry for `e` to the congruence closure. -/ partial def mkEntry (e : Expr) (interpreted : Bool) : CCM Unit := do if (← getEntry e).isSome then return let constructor ← isConstructorApp e modify fun ccs => { ccs with toCCState := ccs.toCCState.mkEntryCore e interpreted constructor } processSubsingletonElem e end /-- Can we propagate equality from subexpressions of `e` to `e`? -/ def mayPropagate (e : Expr) : Bool := e.isAppOfArity ``Iff 2 || e.isAppOfArity ``And 2 || e.isAppOfArity ``Or 2 || e.isAppOfArity ``Not 1 || e.isArrow || e.isIte /-- Remove parents of `e` from the congruence table and the symm congruence table, and append parents to propagate equality, to `parentsToPropagate`. Returns the new value of `parentsToPropagate`. -/ def removeParents (e : Expr) (parentsToPropagate : Array Expr := #[]) : CCM (Array Expr) := do let some ps := (← get).parents[e]? | return parentsToPropagate let mut parentsToPropagate := parentsToPropagate for pocc in ps do let p := pocc.expr trace[Debug.Meta.Tactic.cc] "remove parent: {p}" if mayPropagate p then parentsToPropagate := parentsToPropagate.push p if p.isApp then if pocc.symmTable then let some (rel, lhs, rhs) ← p.relSidesIfSymm? | failure let k' ← mkSymmCongruencesKey lhs rhs if let some lst := (← get).symmCongruences[k']? then let k := (p, rel) let newLst ← lst.filterM fun k₂ => (!·) <$> compareSymm k k₂ if !newLst.isEmpty then modify fun ccs => { ccs with symmCongruences := ccs.symmCongruences.insert k' newLst } else modify fun ccs => { ccs with symmCongruences := ccs.symmCongruences.erase k' } else let k' ← mkCongruencesKey p if let some es := (← get).congruences[k']? then let newEs := es.erase p if !newEs.isEmpty then modify fun ccs => { ccs with congruences := ccs.congruences.insert k' newEs } else modify fun ccs => { ccs with congruences := ccs.congruences.erase k' } return parentsToPropagate /-- The fields `target` and `proof` in `e`'s entry are encoding a transitivity proof Let `e.rootTarget` and `e.rootProof` denote these fields. ```lean e = e.rootTarget := e.rootProof _ = e.rootTarget.rootTarget := e.rootTarget.rootProof ... _ = e.root := ... ``` The transitivity proof eventually reaches the root of the equivalence class. This method "inverts" the proof. That is, the `target` goes from `e.root` to e after we execute it. -/ partial def invertTrans (e : Expr) (newFlipped : Bool := false) (newTarget : Option Expr := none) (newProof : Option EntryExpr := none) : CCM Unit := do let some n ← getEntry e | failure if let some t := n.target then invertTrans t (!n.flipped) (some e) n.proof let newN : Entry := { n with flipped := newFlipped target := newTarget proof := newProof } modify fun ccs => { ccs with entries := ccs.entries.insert e newN } /-- Traverse the `root`'s equivalence class, and for each function application, collect the function's equivalence class root. -/ def collectFnRoots (root : Expr) (fnRoots : Array Expr := #[]) : CCM (Array Expr) := do guard ((← getRoot root) == root) let mut fnRoots : Array Expr := fnRoots let mut visited : ExprSet := ∅ let mut it := root repeat let fnRoot ← getRoot (it.getAppFn) if !visited.contains fnRoot then visited := visited.insert fnRoot fnRoots := fnRoots.push fnRoot let some itN ← getEntry it | failure it := itN.next until it == root return fnRoots /-- Reinsert parents of `e` to the congruence table and the symm congruence table. Together with `removeParents`, this allows modifying parents of an expression. -/ def reinsertParents (e : Expr) : CCM Unit := do let some ps := (← get).parents[e]? | return () for p in ps do trace[Debug.Meta.Tactic.cc] "reinsert parent: {p.expr}" if p.expr.isApp then if p.symmTable then addSymmCongruenceTable p.expr else addCongruenceTable p.expr /-- Check for integrity of the `CCStructure`. -/ def checkInvariant : CCM Unit := do guard (← get).checkInvariant /-- For each `fnRoot` in `fnRoots` traverse its parents, and look for a parent prefix that is in the same equivalence class of the given lambdas. remark All expressions in lambdas are in the same equivalence class -/ def propagateBetaToEqc (fnRoots lambdas : Array Expr) (newLambdaApps : Array Expr := #[]) : CCM (Array Expr) := do if lambdas.isEmpty then return newLambdaApps let mut newLambdaApps := newLambdaApps let lambdaRoot ← getRoot lambdas.back! guard (← lambdas.allM fun l => pure l.isLambda <&&> (· == lambdaRoot) <$> getRoot l) for fnRoot in fnRoots do if let some ps := (← get).parents[fnRoot]? then for { expr := p,.. } in ps do let mut revArgs : Array Expr := #[] let mut it₂ := p while it₂.isApp do let fn := it₂.appFn! revArgs := revArgs.push it₂.appArg! if (← getRoot fn) == lambdaRoot then -- found it newLambdaApps ← propagateBeta fn revArgs lambdas newLambdaApps break it₂ := it₂.appFn! return newLambdaApps /-- Given `c` a constructor application, if `p` is a projection application (not `.proj _ _ _`, but `.app (.const projName _) _`) such that major premise is equal to `c`, then propagate new equality. Example: if `p` is of the form `b.fst`, `c` is of the form `(x, y)`, and `b = c`, we add the equality `(x, y).fst = x` -/ def propagateProjectionConstructor (p c : Expr) : CCM Unit := do guard (← isConstructorApp c) p.withApp fun pFn pArgs => do let some pFnN := pFn.constName? | return let some info ← getProjectionFnInfo? pFnN | return let mkidx := info.numParams if h : mkidx < pArgs.size then unless ← isEqv (pArgs[mkidx]'h) c do return unless ← pureIsDefEq (← inferType (pArgs[mkidx]'h)) (← inferType c) do return /- Create new projection application using c (e.g., `(x, y).fst`), and internalize it. The internalizer will add the new equality. -/ let pArgs := pArgs.set mkidx c let newP := mkAppN pFn pArgs internalizeCore newP none else return /-- Given a new equality `e₁ = e₂`, where `e₁` and `e₂` are constructor applications. Implement the following implications: ```lean c a₁ ... aₙ = c b₁ ... bₙ => a₁ = b₁, ..., aₙ = bₙ c₁ ... = c₂ ... => False ``` where `c`, `c₁` and `c₂` are constructors -/ partial def propagateConstructorEq (e₁ e₂ : Expr) : CCM Unit := do let env ← getEnv let some c₁ ← isConstructorApp? e₁ | failure let some c₂ ← isConstructorApp? e₂ | failure unless ← pureIsDefEq (← inferType e₁) (← inferType e₂) do -- The implications above only hold if the types are equal. -- TODO(Leo): if the types are different, we may still propagate by searching the equivalence -- classes of `e₁` and `e₂` for other constructors that may have compatible types. return let some h ← getEqProof e₁ e₂ | failure if c₁.name == c₂.name then if 0 < c₁.numFields then let name := mkInjectiveTheoremNameFor c₁.name if env.contains name then let rec /-- Given an injective theorem `val : type`, whose `type` is the form of `a₁ = a₂ ∧ b₁ ≍ b₂ ∧ ..`, destruct `val` and push equality proofs to the todo list. -/ go (type val : Expr) : CCM Unit := do let push (type val : Expr) : CCM Unit := match type.eq? with | some (_, lhs, rhs) => pushEq lhs rhs val | none => match type.heq? with | some (_, _, lhs, rhs) => pushHEq lhs rhs val | none => failure match type.and? with | some (l, r) => push l (.proj ``And 0 val) go r (.proj ``And 1 val) | none => push type val let val ← mkAppM name #[h] let type ← inferType val go type val else let falsePr ← mkNoConfusion (.const ``False []) h let H := Expr.app (.const ``true_eq_false_of_false []) falsePr pushEq (.const ``True []) (.const ``False []) H /-- Derive contradiction if we can get equality between different values. -/ def propagateValueInconsistency (e₁ e₂ : Expr) : CCM Unit := do guard (← isInterpretedValue e₁) guard (← isInterpretedValue e₂) let some eqProof ← getEqProof e₁ e₂ | failure let trueEqFalse ← mkEq (.const ``True []) (.const ``False []) let neProof := Expr.app (.proj ``Iff 0 (← mkAppOptM ``bne_iff_ne #[none, none, none, e₁, e₂])) (← mkEqRefl (.const ``true [])) let H ← mkAbsurd trueEqFalse eqProof neProof pushEq (.const ``True []) (.const ``False []) H /-- Propagate equality from `a ∧ b = True` to `a = True` and `b = True`. -/ def propagateAndDown (e : Expr) : CCM Unit := do if ← isEqTrue e then let some (a, b) := e.and? | failure let h ← getEqTrueProof e pushEq a (.const ``True []) (mkApp3 (.const ``eq_true_of_and_eq_true_left []) a b h) pushEq b (.const ``True []) (mkApp3 (.const ``eq_true_of_and_eq_true_right []) a b h) /-- Propagate equality from `a ∨ b = False` to `a = False` and `b = False`. -/ def propagateOrDown (e : Expr) : CCM Unit := do if ← isEqFalse e then let some (a, b) := e.app2? ``Or | failure let h ← getEqFalseProof e pushEq a (.const ``False []) (mkApp3 (.const ``eq_false_of_or_eq_false_left []) a b h) pushEq b (.const ``False []) (mkApp3 (.const ``eq_false_of_or_eq_false_right []) a b h) /-- Propagate equality from `¬a` to `a`. -/ def propagateNotDown (e : Expr) : CCM Unit := do if ← isEqTrue e then let some a := e.not? | failure pushEq a (.const ``False []) (mkApp2 (.const ``eq_false_of_not_eq_true []) a (← getEqTrueProof e)) else if ← (·.em) <$> get <&&> isEqFalse e then let some a := e.not? | failure pushEq a (.const ``True []) (mkApp2 (.const ``eq_true_of_not_eq_false []) a (← getEqFalseProof e)) /-- Propagate equality from `(a = b) = True` to `a = b`. -/ def propagateEqDown (e : Expr) : CCM Unit := do if ← isEqTrue e then let some (a, b) := e.eqOrIff? | failure pushEq a b (← mkAppM ``of_eq_true #[← getEqTrueProof e]) /-- Propagate equality from `¬∃ x, p x` to `∀ x, ¬p x`. -/ def propagateExistsDown (e : Expr) : CCM Unit := do if ← isEqFalse e then let hNotE ← mkAppM ``of_eq_false #[← getEqFalseProof e] let (all, hAll) ← e.forallNot_of_notExists hNotE internalizeCore all none pushEq all (.const ``True []) (← mkEqTrue hAll) /-- Propagate equality from `e` to subexpressions of `e`. -/ def propagateDown (e : Expr) : CCM Unit := do if e.isAppOfArity ``And 2 then propagateAndDown e else if e.isAppOfArity ``Or 2 then propagateOrDown e else if e.isAppOfArity ``Not 1 then propagateNotDown e else if e.isEq || e.isAppOfArity ``Iff 2 then propagateEqDown e else if e.isAppOfArity ``Exists 2 then propagateExistsDown e /-- Performs one step in the process when the new equation is added. Here, `H` contains the proof that `e₁ = e₂` (if `heqProof` is false) or `e₁ ≍ e₂` (if `heqProof` is true). -/ def addEqvStep (e₁ e₂ : Expr) (H : EntryExpr) (heqProof : Bool) : CCM Unit := do let some n₁ ← getEntry e₁ | return -- `e₁` have not been internalized let some n₂ ← getEntry e₂ | return -- `e₂` have not been internalized if n₁.root == n₂.root then return -- they are already in the same equivalence class. let some r₁ ← getEntry n₁.root | failure let some r₂ ← getEntry n₂.root | failure -- We want `r₂` to be the root of the combined class. /- We swap `(e₁,n₁,r₁)` with `(e₂,n₂,r₂)` when 1- `r₁.interpreted && !r₂.interpreted`. Reason: to decide when to propagate we check whether the root of the equivalence class is `True`/`False`. So, this condition is to make sure if `True`/`False` is in an equivalence class, then one of them is the root. If both are, it doesn't matter, since the state is inconsistent anyway. 2- `r₁.constructor && !r₂.interpreted && !r₂.constructor` Reason: we want constructors to be the representative of their equivalence classes. 3- `r₁.size > r₂.size && !r₂.interpreted && !r₂.constructor` Reason: performance. -/ if (r₁.interpreted && !r₂.interpreted) || (r₁.constructor && !r₂.interpreted && !r₂.constructor) || (decide (r₁.size > r₂.size) && !r₂.interpreted && !r₂.constructor) then go e₂ e₁ n₂ n₁ r₂ r₁ true H heqProof else go e₁ e₂ n₁ n₂ r₁ r₂ false H heqProof where /-- The auxiliary definition for `addEqvStep` to flip the input. -/ go (e₁ e₂: Expr) (n₁ n₂ r₁ r₂ : Entry) (flipped : Bool) (H : EntryExpr) (heqProof : Bool) : CCM Unit := do -- Interpreted values are already in the correct equivalence class, -- so merging two different classes means we found an inconsistency. let mut valueInconsistency := false if r₁.interpreted && r₂.interpreted then if n₁.root.isConstOf ``True || n₂.root.isConstOf ``True then modify fun ccs => { ccs with inconsistent := true } else if n₁.root.int?.isSome && n₂.root.int?.isSome then valueInconsistency := n₁.root.int? != n₂.root.int? else valueInconsistency := true let e₁Root := n₁.root let e₂Root := n₂.root trace[Debug.Meta.Tactic.cc] "merging\n{e₁} ==> {e₁Root}\nwith\n{e₂Root} <== {e₂}" /- Following target/proof we have `e₁ → ... → r₁` `e₂ → ... → r₂` We want `r₁ → ... → e₁ → e₂ → ... → r₂` -/ invertTrans e₁ let newN₁ : Entry := { n₁ with target := e₂ proof := H flipped } modify fun ccs => { ccs with entries := ccs.entries.insert e₁ newN₁ } -- The hash code for the parents is going to change let parentsToPropagate ← removeParents e₁Root let lambdas₁ ← getEqcLambdas e₁Root let lambdas₂ ← getEqcLambdas e₂Root let fnRoots₂ ← if !lambdas₁.isEmpty then collectFnRoots e₂Root else pure #[] let fnRoots₁ ← if !lambdas₂.isEmpty then collectFnRoots e₁Root else pure #[] -- force all `root` fields in `e₁` equivalence class to point to `e₂Root` let propagate := e₂Root.isConstOf ``True || e₂Root.isConstOf ``False let mut toPropagate : Array Expr := #[] let mut it := e₁ repeat let some itN ← getEntry it | failure if propagate then toPropagate := toPropagate.push it let newItN : Entry := { itN with root := e₂Root } modify fun ccs => { ccs with entries := ccs.entries.insert it newItN } it := newItN.next until it == e₁ reinsertParents e₁Root -- update next of `e₁Root` and `e₂Root`, ac representative, and size of `e₂Root` let some r₁ ← getEntry e₁Root | failure let some r₂ ← getEntry e₂Root | failure guard (r₁.root == e₂Root) let acVar?₁ := r₁.acVar let acVar?₂ := r₂.acVar let newR₁ : Entry := { r₁ with next := r₂.next } let newR₂ : Entry := { r₂ with next := r₁.next size := r₂.size + r₁.size hasLambdas := r₂.hasLambdas || r₁.hasLambdas heqProofs := r₂.heqProofs || heqProof acVar := acVar?₂ <|> acVar?₁ } modify fun ccs => { ccs with entries := ccs.entries.insert e₁Root newR₁ |>.insert e₂Root newR₂ } checkInvariant let lambdaAppsToInternalize ← propagateBetaToEqc fnRoots₂ lambdas₁ let lambdaAppsToInternalize ← propagateBetaToEqc fnRoots₁ lambdas₂ lambdaAppsToInternalize -- copy `e₁Root` parents to `e₂Root` let constructorEq := r₁.constructor && r₂.constructor if let some ps₁ := (← get).parents[e₁Root]? then let mut ps₂ : ParentOccSet := ∅ if let some it' := (← get).parents[e₂Root]? then ps₂ := it' for p in ps₁ do if ← pure p.expr.isApp <||> isCgRoot p.expr then if !constructorEq && r₂.constructor then propagateProjectionConstructor p.expr e₂Root ps₂ := ps₂.insert p modify fun ccs => { ccs with parents := ccs.parents.erase e₁Root |>.insert e₂Root ps₂ } if !(← get).inconsistent then if let some acVar₁ := acVar?₁ then if let some acVar₂ := acVar?₂ then addACEq acVar₁ acVar₂ if !(← get).inconsistent && constructorEq then propagateConstructorEq e₁Root e₂Root if !(← get).inconsistent && valueInconsistency then propagateValueInconsistency e₁Root e₂Root if !(← get).inconsistent then updateMT e₂Root checkNewSubsingletonEq e₁Root e₂Root if !(← get).inconsistent then for p in parentsToPropagate do propagateUp p if !(← get).inconsistent && !toPropagate.isEmpty then for e in toPropagate do propagateDown e if let some phandler := (← get).phandler then phandler.propagated toPropagate if !(← get).inconsistent then for e in lambdaAppsToInternalize do internalizeCore e none let ccs ← get trace[Meta.Tactic.cc.merge] "{e₁Root} = {e₂Root}" trace[Debug.Meta.Tactic.cc] "merged: {e₁Root} = {e₂Root}\n{ccs.ppEqcs}" trace[Debug.Meta.Tactic.cc.parentOccs] ccs.ppParentOccs /-- Process the tasks in the `todo` field. -/ def processTodo : CCM Unit := do repeat let todo ← getTodo let some (lhs, rhs, H, heqProof) := todo.back? | return if (← get).inconsistent then modifyTodo fun _ => #[] return modifyTodo Array.pop addEqvStep lhs rhs H heqProof /-- Internalize `e` so that the congruence closure can deal with the given expression. -/ def internalize (e : Expr) : CCM Unit := do internalizeCore e none processTodo /-- Add `H : lhs = rhs` or `H : lhs ≍ rhs` to the congruence closure. Don't forget to internalize `lhs` and `rhs` beforehand. -/ def addEqvCore (lhs rhs H : Expr) (heqProof : Bool) : CCM Unit := do pushTodo lhs rhs H heqProof processTodo /-- Add `proof : type` to the congruence closure. -/ def add (type : Expr) (proof : Expr) : CCM Unit := do if (← get).inconsistent then return modifyTodo fun _ => #[] let (isNeg, p) := match type with | .app (.const ``Not []) a => (true, a) | .forallE _ a (.const ``False []) _ => (true, a) | .app (.app (.app (.const ``Ne [u]) α) lhs) rhs => (true, .app (.app (.app (.const ``Eq [u]) α) lhs) rhs) | e => (false, e) match p with | .app (.app (.app (.const ``Eq _) _) lhs) rhs => if isNeg then internalizeCore p none addEqvCore p (.const ``False []) (← mkEqFalse proof) false else internalizeCore lhs none internalizeCore rhs none addEqvCore lhs rhs proof false | .app (.app (.app (.app (.const ``HEq _) _) lhs) _) rhs => if isNeg then internalizeCore p none addEqvCore p (.const ``False []) (← mkEqFalse proof) false else internalizeCore lhs none internalizeCore rhs none addEqvCore lhs rhs proof true | .app (.app (.const ``Iff _) lhs) rhs => if isNeg then let neqProof ← mkAppM ``neq_of_not_iff #[proof] internalizeCore p none addEqvCore p (.const ``False []) (← mkEqFalse neqProof) false else internalizeCore lhs none internalizeCore rhs none addEqvCore lhs rhs (mkApp3 (.const ``propext []) lhs rhs proof) false | _ => if ← pure isNeg <||> isProp p then internalizeCore p none if isNeg then addEqvCore p (.const ``False []) (← mkEqFalse proof) false else addEqvCore p (.const ``True []) (← mkEqTrue proof) false end CCM end Mathlib.Tactic.CC
.lake/packages/mathlib/Mathlib/Tactic/CC/Datatypes.lean
import Batteries.Classes.Order import Mathlib.Lean.Meta.Basic import Mathlib.Lean.Meta.CongrTheorems import Mathlib.Data.Ordering.Basic /-! # Datatypes for `cc` Some of the data structures here are used in multiple parts of the tactic. We split them into their own file. ## TODO This file is ported from C++ code, so many declarations lack documents. -/ universe u open Lean Meta Elab Tactic namespace Mathlib.Tactic.CC /-- Return true if `e` represents a constant value (numeral, character, or string). -/ def isValue (e : Expr) : Bool := e.int?.isSome || e.isCharLit || e.isStringLit /-- Return true if `e` represents a value (nat/int numeral, character, or string). In addition to the conditions in `Mathlib.Tactic.CC.isValue`, this also checks that kernel computation can compare the values for equality. -/ def isInterpretedValue (e : Expr) : MetaM Bool := do if e.isCharLit || e.isStringLit then return true else if e.int?.isSome then let type ← inferType e pureIsDefEq type (.const ``Nat []) <||> pureIsDefEq type (.const ``Int []) else return false /-- Given a reflexive relation `R`, and a proof `H : a = b`, build a proof for `R a b` -/ def liftFromEq (R : Name) (H : Expr) : MetaM Expr := do if R == ``Eq then return H let HType ← whnf (← inferType H) -- `HType : @Eq A a _` let some (A, a, _) := HType.eq? | throwError "failed to build liftFromEq equality proof expected: {H}" -- `motive : (x : _) → a = x → Prop := fun x h => R a x` let motive ← withLocalDeclD `x A fun x => do let hType ← mkEq a x withLocalDeclD `h hType fun h => mkRel R a x >>= mkLambdaFVars #[x, h] -- `minor : R a a := by rfl` let minor ← do let mt ← mkRel R a a let m ← mkFreshExprSyntheticOpaqueMVar mt m.mvarId!.applyRfl instantiateMVars m mkEqRec motive minor H /-- Ordering on `Expr`. -/ scoped instance : Ord Expr where compare a b := bif Expr.lt a b then .lt else bif Expr.eqv b a then .eq else .gt /-- Red-black maps whose keys are `Expr`s. TODO: the choice between `TreeMap` and `HashMap` is not obvious: once the `cc` tactic is used a lot in Mathlib, we should profile and see if `HashMap` could be more optimal. -/ abbrev ExprMap (α : Type u) := Std.TreeMap Expr α compare /-- Red-black sets of `Expr`s. TODO: the choice between `TreeSet` and `HashSet` is not obvious: once the `cc` tactic is used a lot in Mathlib, we should profile and see if `HashSet` could be more optimal. -/ abbrev ExprSet := Std.TreeSet Expr compare /-- `CongrTheorem`s equipped with additional infos used by congruence closure modules. -/ structure CCCongrTheorem extends CongrTheorem where /-- If `heqResult` is true, then lemma is based on heterogeneous equality and the conclusion is a heterogeneous equality. -/ heqResult : Bool := false /-- If `hcongrTheorem` is true, then lemma was created using `mkHCongrWithArity`. -/ hcongrTheorem : Bool := false /-- Automatically generated congruence lemma based on heterogeneous equality. This returns an annotated version of the result from `Lean.Meta.mkHCongrWithArity`. -/ def mkCCHCongrWithArity (fn : Expr) (nargs : Nat) : MetaM (Option CCCongrTheorem) := do let eqCongr ← try mkHCongrWithArity fn nargs catch _ => return none return some { eqCongr with heqResult := true hcongrTheorem := true } /-- Keys used to find corresponding `CCCongrTheorem`s. -/ structure CCCongrTheoremKey where /-- The function of the given `CCCongrTheorem`. -/ fn : Expr /-- The number of arguments of `fn`. -/ nargs : Nat deriving BEq, Hashable /-- Caches used to find corresponding `CCCongrTheorem`s. -/ abbrev CCCongrTheoremCache := Std.HashMap CCCongrTheoremKey (Option CCCongrTheorem) /-- Configs used in congruence closure modules. -/ structure CCConfig where /-- If `true`, congruence closure will treat implicit instance arguments as constants. This means that setting `ignoreInstances := false` will fail to unify two definitionally equal instances of the same class. -/ ignoreInstances : Bool := true /-- If `true`, congruence closure modulo Associativity and Commutativity. -/ ac : Bool := true /-- If `hoFns` is `some fns`, then full (and more expensive) support for higher-order functions is *only* considered for the functions in fns and local functions. The performance overhead is described in the paper "Congruence Closure in Intensional Type Theory". If `hoFns` is `none`, then full support is provided for *all* constants. -/ hoFns : Option (List Name) := none /-- If `true`, then use excluded middle -/ em : Bool := true /-- If `true`, we treat values as atomic symbols -/ values : Bool := false deriving Inhabited /-- An `ACApps` represents either just an `Expr` or applications of an associative and commutative binary operator. -/ inductive ACApps where /-- An `ACApps` of just an `Expr`. -/ | ofExpr (e : Expr) : ACApps /-- An `ACApps` of applications of a binary operator. `args` are assumed to be sorted. See also `ACApps.mkApps` if `args` are not yet sorted. -/ | apps (op : Expr) (args : Array Expr) : ACApps deriving Inhabited, BEq instance : Coe Expr ACApps := ⟨ACApps.ofExpr⟩ attribute [coe] ACApps.ofExpr /-- Ordering on `ACApps` sorts `.ofExpr` before `.apps`, and sorts `.apps` by function symbol, then by shortlex order. -/ scoped instance : Ord ACApps where compare | .ofExpr a, .ofExpr b => compare a b | .ofExpr _, .apps _ _ => .lt | .apps _ _, .ofExpr _ => .gt | .apps op₁ args₁, .apps op₂ args₂ => compare op₁ op₂ |>.then <| compare args₁.size args₂.size |>.dthen fun hs => Id.run do have hs := eq_of_beq <| Std.LawfulBEqCmp.compare_eq_iff_beq.mp hs for hi : i in [:args₁.size] do have hi := hi.right let o := compare args₁[i] (args₂[i]'(hs ▸ hi.1)) if o != .eq then return o return .eq /-- Return true iff `e₁` is a "subset" of `e₂`. Example: The result is `true` for `e₁ := a*a*a*b*d` and `e₂ := a*a*a*a*b*b*c*d*d`. The result is also `true` for `e₁ := a` and `e₂ := a*a*a*b*c`. -/ def ACApps.isSubset : (e₁ e₂ : ACApps) → Bool | .ofExpr a, .ofExpr b => a == b | .ofExpr a, .apps _ args => args.contains a | .apps _ _, .ofExpr _ => false | .apps op₁ args₁, .apps op₂ args₂ => if op₁ == op₂ then if args₁.size ≤ args₂.size then Id.run do let mut i₁ := 0 let mut i₂ := 0 while h : i₁ < args₁.size ∧ i₂ < args₂.size do if args₁[i₁] == args₂[i₂] then i₁ := i₁ + 1 i₂ := i₂ + 1 else if Expr.lt args₂[i₂] args₁[i₁] then i₂ := i₂ + 1 else return false return i₁ == args₁.size else false else false /-- Appends elements of the set difference `e₁ \ e₂` to `r`. Example: given `e₁ := a*a*a*a*b*b*c*d*d*d` and `e₂ := a*a*a*b*b*d`, the result is `#[a, c, d, d]` Precondition: `e₂.isSubset e₁` -/ def ACApps.diff (e₁ e₂ : ACApps) (r : Array Expr := #[]) : Array Expr := match e₁ with | .apps op₁ args₁ => Id.run do let mut r := r match e₂ with | .apps op₂ args₂ => if op₁ == op₂ then let mut i₂ := 0 for h : i₁ in [:args₁.size] do if i₂ == args₂.size then r := r.push args₁[i₁] else if args₁[i₁] == args₂[i₂]! then i₂ := i₂ + 1 else r := r.push args₁[i₁] | .ofExpr e₂ => let mut found := false for h : i in [:args₁.size] do if !found && args₁[i] == e₂ then found := true else r := r.push args₁[i] return r | .ofExpr e => if e₂ == e then r else r.push e /-- Appends arguments of `e` to `r`. -/ def ACApps.append (op : Expr) (e : ACApps) (r : Array Expr := #[]) : Array Expr := match e with | .apps op' args => if op' == op then r ++ args else r | .ofExpr e => r.push e /-- Appends elements in the intersection of `e₁` and `e₂` to `r`. -/ def ACApps.intersection (e₁ e₂ : ACApps) (r : Array Expr := #[]) : Array Expr := match e₁, e₂ with | .apps _ args₁, .apps _ args₂ => Id.run do let mut r := r let mut i₁ := 0 let mut i₂ := 0 while h : i₁ < args₁.size ∧ i₂ < args₂.size do if args₁[i₁] == args₂[i₂] then r := r.push args₁[i₁] i₁ := i₁ + 1 i₂ := i₂ + 1 else if Expr.lt args₂[i₂] args₁[i₁] then i₂ := i₂ + 1 else i₁ := i₁ + 1 return r | _, _ => r /-- Sorts `args` and applies them to `ACApps.apps`. -/ def ACApps.mkApps (op : Expr) (args : Array Expr) : ACApps := .apps op (args.qsort Expr.lt) /-- Flattens given two `ACApps`. -/ def ACApps.mkFlatApps (op : Expr) (e₁ e₂ : ACApps) : ACApps := let newArgs := ACApps.append op e₁ let newArgs := ACApps.append op e₂ newArgs -- TODO: this does a full sort but `newArgs` consists of two sorted subarrays, -- so if we want to optimize this, some form of merge sort might be faster. ACApps.mkApps op newArgs /-- Converts an `ACApps` to an `Expr`. This returns `none` when the empty applications are given. -/ def ACApps.toExpr : ACApps → Option Expr | .apps _ ⟨[]⟩ => none | .apps op ⟨arg₀ :: args⟩ => some <| args.foldl (fun e arg => mkApp2 op e arg) arg₀ | .ofExpr e => some e /-- Red-black maps whose keys are `ACApps`es. TODO: the choice between `TreeMap` and `HashMap` is not obvious: once the `cc` tactic is used a lot in Mathlib, we should profile and see if `HashMap` could be more optimal. -/ abbrev ACAppsMap (α : Type u) := Std.TreeMap ACApps α compare /-- Red-black sets of `ACApps`es. TODO: the choice between `TreeSet` and `HashSet` is not obvious: once the `cc` tactic is used a lot in Mathlib, we should profile and see if `HashSet` could be more optimal. -/ abbrev ACAppsSet := Std.TreeSet ACApps compare /-- For proof terms generated by AC congruence closure modules, we want a placeholder as an equality proof between given two terms which will be generated by non-AC congruence closure modules later. `DelayedExpr` represents it using `eqProof`. -/ inductive DelayedExpr where /-- A `DelayedExpr` of just an `Expr`. -/ | ofExpr (e : Expr) : DelayedExpr /-- A placeholder as an equality proof between given two terms which will be generated by non-AC congruence closure modules later. -/ | eqProof (lhs rhs : Expr) : DelayedExpr /-- Will be applied to `congr_arg`. -/ | congrArg (f : Expr) (h : DelayedExpr) : DelayedExpr /-- Will be applied to `congr_fun`. -/ | congrFun (h : DelayedExpr) (a : ACApps) : DelayedExpr /-- Will be applied to `Eq.symm`. -/ | eqSymm (h : DelayedExpr) : DelayedExpr /-- Will be applied to `Eq.symm`. -/ | eqSymmOpt (a₁ a₂ : ACApps) (h : DelayedExpr) : DelayedExpr /-- Will be applied to `Eq.trans`. -/ | eqTrans (h₁ h₂ : DelayedExpr) : DelayedExpr /-- Will be applied to `Eq.trans`. -/ | eqTransOpt (a₁ a₂ a₃ : ACApps) (h₁ h₂ : DelayedExpr) : DelayedExpr /-- Will be applied to `heq_of_eq`. -/ | heqOfEq (h : DelayedExpr) : DelayedExpr /-- Will be applied to `HEq.symm`. -/ | heqSymm (h : DelayedExpr) : DelayedExpr deriving Inhabited instance : Coe Expr DelayedExpr := ⟨DelayedExpr.ofExpr⟩ attribute [coe] DelayedExpr.ofExpr /-- This is used as a proof term in `Entry`s instead of `Expr`. -/ inductive EntryExpr /-- An `EntryExpr` of just an `Expr`. -/ | ofExpr (e : Expr) : EntryExpr /-- dummy congruence proof, it is just a placeholder. -/ | congr : EntryExpr /-- dummy eq_true proof, it is just a placeholder -/ | eqTrue : EntryExpr /-- dummy refl proof, it is just a placeholder. -/ | refl : EntryExpr /-- An `EntryExpr` of a `DelayedExpr`. -/ | ofDExpr (e : DelayedExpr) : EntryExpr deriving Inhabited instance : ToMessageData EntryExpr where toMessageData | .ofExpr e => toMessageData e | .congr => m!"[congruence proof]" | .eqTrue => m!"[eq_true proof]" | .refl => m!"[refl proof]" | .ofDExpr _ => m!"[delayed expression]" instance : Coe Expr EntryExpr := ⟨EntryExpr.ofExpr⟩ attribute [coe] EntryExpr.ofExpr /-- Equivalence class data associated with an expression `e`. -/ structure Entry where /-- next element in the equivalence class. -/ next : Expr /-- root (aka canonical) representative of the equivalence class. -/ root : Expr /-- root of the congruence class, it is meaningless if `e` is not an application. -/ cgRoot : Expr /-- When `e` was added to this equivalence class because of an equality `(H : e = tgt)`, then we store `tgt` at `target`, and `H` at `proof`. Both fields are none if `e == root` -/ target : Option Expr := none /-- When `e` was added to this equivalence class because of an equality `(H : e = tgt)`, then we store `tgt` at `target`, and `H` at `proof`. Both fields are none if `e == root` -/ proof : Option EntryExpr := none /-- Variable in the AC theory. -/ acVar : Option Expr := none /-- proof has been flipped -/ flipped : Bool /-- `true` if the node should be viewed as an abstract value -/ interpreted : Bool /-- `true` if head symbol is a constructor -/ constructor : Bool /-- `true` if equivalence class contains lambda expressions -/ hasLambdas : Bool /-- `heqProofs == true` iff some proofs in the equivalence class are based on heterogeneous equality. We represent equality and heterogeneous equality in a single equivalence class. -/ heqProofs : Bool /-- If `fo == true`, then the expression associated with this entry is an application, and we are using first-order approximation to encode it. That is, we ignore its partial applications. -/ fo : Bool /-- number of elements in the equivalence class, it is meaningless if `e != root` -/ size : Nat /-- The field `mt` is used to implement the mod-time optimization introduce by the Simplify theorem prover. The basic idea is to introduce a counter gmt that records the number of heuristic instantiation that have occurred in the current branch. It is incremented after each round of heuristic instantiation. The field `mt` records the last time any proper descendant of this entry was involved in a merge. -/ mt : Nat deriving Inhabited /-- Stores equivalence class data associated with an expression `e`. -/ abbrev Entries := ExprMap Entry /-- Equivalence class data associated with an expression `e` used by AC congruence closure modules. -/ structure ACEntry where /-- Natural number associated to an expression. -/ idx : Nat /-- AC variables that occur on the left-hand side of an equality which `e` occurs as the left-hand side of in `CCState.acR`. -/ RLHSOccs : ACAppsSet := ∅ /-- AC variables that occur on the **left**-hand side of an equality which `e` occurs as the right-hand side of in `CCState.acR`. Don't confuse. -/ RRHSOccs : ACAppsSet := ∅ deriving Inhabited /-- Returns the occurrences of this entry in either the LHS or RHS. -/ def ACEntry.ROccs (ent : ACEntry) : (inLHS : Bool) → ACAppsSet | true => ent.RLHSOccs | false => ent.RRHSOccs /-- Used to record when an expression processed by `cc` occurs in another expression. -/ structure ParentOcc where expr : Expr /-- If `symmTable` is true, then we should use the `symmCongruences`, otherwise `congruences`. Remark: this information is redundant, it can be inferred from `expr`. We use store it for performance reasons. -/ symmTable : Bool /-- Red-black sets of `ParentOcc`s. -/ abbrev ParentOccSet := Std.TreeSet ParentOcc (Ordering.byKey ParentOcc.expr compare) /-- Used to map an expression `e` to another expression that contains `e`. When `e` is normalized, its parents should also change. -/ abbrev Parents := ExprMap ParentOccSet inductive CongruencesKey /-- `fn` is First-Order: we do not consider all partial applications. -/ | fo (fn : Expr) (args : Array Expr) : CongruencesKey /-- `fn` is Higher-Order. -/ | ho (fn : Expr) (arg : Expr) : CongruencesKey deriving BEq, Hashable /-- Maps each expression (via `mkCongruenceKey`) to expressions it might be congruent to. -/ abbrev Congruences := Std.HashMap CongruencesKey (List Expr) structure SymmCongruencesKey where (h₁ h₂ : Expr) deriving BEq, Hashable /-- The symmetric variant of `Congruences`. The `Name` identifies which relation the congruence is considered for. Note that this only works for two-argument relations: `ModEq n` and `ModEq m` are considered the same. -/ abbrev SymmCongruences := Std.HashMap SymmCongruencesKey (List (Expr × Name)) /-- Stores the root representatives of subsingletons, this uses `FastSingleton` instead of `Subsingleton`. -/ abbrev SubsingletonReprs := ExprMap Expr /-- Stores the root representatives of `.instImplicit` arguments. -/ abbrev InstImplicitReprs := ExprMap (List Expr) abbrev TodoEntry := Expr × Expr × EntryExpr × Bool abbrev ACTodoEntry := ACApps × ACApps × DelayedExpr /-- Congruence closure state. This may be considered to be a set of expressions and an equivalence class over this set. The equivalence class is generated by the equational rules that are added to the `CCState` and congruence, that is, if `a = b` then `f(a) = f(b)` and so on. -/ structure CCState extends CCConfig where /-- Maps known expressions to their equivalence class data. -/ entries : Entries := ∅ /-- Maps an expression `e` to the expressions `e` occurs in. -/ parents : Parents := ∅ /-- Maps each expression to a set of expressions it might be congruent to. -/ congruences : Congruences := ∅ /-- Maps each expression to a set of expressions it might be congruent to, via the symmetrical relation. -/ symmCongruences : SymmCongruences := ∅ subsingletonReprs : SubsingletonReprs := ∅ /-- Records which instances of the same class are defeq. -/ instImplicitReprs : InstImplicitReprs := ∅ /-- The congruence closure module has a mode where the root of each equivalence class is marked as an interpreted/abstract value. Moreover, in this mode proof production is disabled. This capability is useful for heuristic instantiation. -/ frozePartitions : Bool := false /-- Mapping from operators occurring in terms and their canonical representation in this module -/ canOps : ExprMap Expr := ∅ /-- Whether the canonical operator is supported by AC. -/ opInfo : ExprMap Bool := ∅ /-- Extra `Entry` information used by the AC part of the tactic. -/ acEntries : ExprMap ACEntry := ∅ /-- Records equality between `ACApps`. -/ acR : ACAppsMap (ACApps × DelayedExpr) := ∅ /-- Returns true if the `CCState` is inconsistent. For example if it had both `a = b` and `a ≠ b` in it. -/ inconsistent : Bool := false /-- "Global Modification Time". gmt is a number stored on the `CCState`, it is compared with the modification time of a cc_entry in e-matching. See `CCState.mt`. -/ gmt : Nat := 0 deriving Inhabited attribute [inherit_doc SubsingletonReprs] CCState.subsingletonReprs /-- Update the `CCState` by constructing and inserting a new `Entry`. -/ def CCState.mkEntryCore (ccs : CCState) (e : Expr) (interpreted : Bool) (constructor : Bool) : CCState := assert! ccs.entries[e]? |>.isNone let n : Entry := { next := e root := e cgRoot := e size := 1 flipped := false interpreted constructor hasLambdas := e.isLambda heqProofs := false mt := ccs.gmt fo := false } { ccs with entries := ccs.entries.insert e n } namespace CCState /-- Get the root representative of the given expression. -/ def root (ccs : CCState) (e : Expr) : Expr := match ccs.entries[e]? with | some n => n.root | none => e /-- Get the next element in the equivalence class. Note that if the given `Expr` `e` is not in the graph then it will just return `e`. -/ def next (ccs : CCState) (e : Expr) : Expr := match ccs.entries[e]? with | some n => n.next | none => e /-- Check if `e` is the root of the congruence class. -/ def isCgRoot (ccs : CCState) (e : Expr) : Bool := match ccs.entries[e]? with | some n => e == n.cgRoot | none => true /-- "Modification Time". The field `mt` is used to implement the mod-time optimization introduced by the Simplify theorem prover. The basic idea is to introduce a counter `gmt` that records the number of heuristic instantiation that have occurred in the current branch. It is incremented after each round of heuristic instantiation. The field `mt` records the last time any proper descendant of this entry was involved in a merge. -/ def mt (ccs : CCState) (e : Expr) : Nat := match ccs.entries[e]? with | some n => n.mt | none => ccs.gmt /-- Is the expression in an equivalence class with only one element (namely, itself)? -/ def inSingletonEqc (ccs : CCState) (e : Expr) : Bool := match ccs.entries[e]? with | some it => it.next == e | none => true /-- Append to `roots` all the roots of equivalence classes in `ccs`. If `nonsingletonOnly` is true, we skip all the singleton equivalence classes. -/ def getRoots (ccs : CCState) (roots : Array Expr) (nonsingletonOnly : Bool) : Array Expr := Id.run do let mut roots := roots for (k, n) in ccs.entries do if k == n.root && (!nonsingletonOnly || !ccs.inSingletonEqc k) then roots := roots.push k return roots /-- Check for integrity of the `CCState`. -/ def checkEqc (ccs : CCState) (e : Expr) : Bool := toBool <| Id.run <| OptionT.run do let root := ccs.root e let mut size : Nat := 0 let mut it := e repeat let some itN := ccs.entries[it]? | failure guard (itN.root == root) let mut it₂ := it -- following `target` fields should lead to root repeat let it₂N := ccs.entries[it₂]? match it₂N.bind Entry.target with | some it₃ => it₂ := it₃ | none => break guard (it₂ == root) it := itN.next size := size + 1 until it == e guard (ccs.entries[root]? |>.any (·.size == size)) /-- Check for integrity of the `CCState`. -/ def checkInvariant (ccs : CCState) : Bool := ccs.entries.all fun k n => k != n.root || checkEqc ccs k def getNumROccs (ccs : CCState) (e : Expr) (inLHS : Bool) : Nat := match ccs.acEntries[e]? with | some ent => (ent.ROccs inLHS).size | none => 0 /-- Search for the AC-variable (`Entry.acVar`) with the least occurrences in the state. -/ def getVarWithLeastOccs (ccs : CCState) (e : ACApps) (inLHS : Bool) : Option Expr := match e with | .apps _ args => Id.run do let mut r := args[0]? let mut numOccs := r.casesOn 0 fun r' => ccs.getNumROccs r' inLHS for hi : i in [1:args.size] do if args[i] != (args[i - 1]'(Nat.lt_of_le_of_lt (i.sub_le 1) hi.2.1)) then let currOccs := ccs.getNumROccs args[i] inLHS if currOccs < numOccs then r := args[i] numOccs := currOccs return r | .ofExpr e => e /-- Search for the AC-variable (`Entry.acVar`) with the fewest occurrences in the LHS. -/ def getVarWithLeastLHSOccs (ccs : CCState) (e : ACApps) : Option Expr := ccs.getVarWithLeastOccs e true /-- Search for the AC-variable (`Entry.acVar`) with the fewest occurrences in the RHS. -/ def getVarWithLeastRHSOccs (ccs : CCState) (e : ACApps) : Option Expr := ccs.getVarWithLeastOccs e false open MessageData /-- Pretty print the entry associated with the given expression. -/ def ppEqc (ccs : CCState) (e : Expr) : MessageData := Id.run do let mut lr : List MessageData := [] let mut it := e repeat let some itN := ccs.entries[it]? | break let mdIt : MessageData := if it.isForall || it.isLambda || it.isLet then paren (ofExpr it) else ofExpr it lr := mdIt :: lr it := itN.next until it == e let l := lr.reverse return bracket "{" (group <| joinSep l (ofFormat ("," ++ .line))) "}" /-- Pretty print the entire cc graph. If the `nonSingleton` argument is set to `true` then singleton equivalence classes will be omitted. -/ def ppEqcs (ccs : CCState) (nonSingleton : Bool := true) : MessageData := let roots := ccs.getRoots #[] nonSingleton let a := roots.map (fun root => ccs.ppEqc root) let l := a.toList bracket "{" (group <| joinSep l (ofFormat ("," ++ .line))) "}" def ppParentOccsAux (ccs : CCState) (e : Expr) : MessageData := match ccs.parents[e]? with | some poccs => let r := ofExpr e ++ ofFormat (.line ++ ":=" ++ .line) let ps := poccs.toList.map fun o => ofExpr o.expr group (r ++ bracket "{" (group <| joinSep ps (ofFormat ("," ++ .line))) "}") | none => ofFormat .nil def ppParentOccs (ccs : CCState) : MessageData := let r := ccs.parents.toList.map fun (k, _) => ccs.ppParentOccsAux k bracket "{" (group <| joinSep r (ofFormat ("," ++ .line))) "}" def ppACDecl (ccs : CCState) (e : Expr) : MessageData := match ccs.acEntries[e]? with | some it => group (ofFormat (s!"x_{it.idx}" ++ .line ++ ":=" ++ .line) ++ ofExpr e) | none => nil def ppACDecls (ccs : CCState) : MessageData := let r := ccs.acEntries.toList.map fun (k, _) => ccs.ppACDecl k bracket "{" (joinSep r (ofFormat ("," ++ .line))) "}" def ppACExpr (ccs : CCState) (e : Expr) : MessageData := if let some it := ccs.acEntries[e]? then s!"x_{it.idx}" else ofExpr e partial def ppACApps (ccs : CCState) : ACApps → MessageData | .apps op args => let r := ofExpr op :: args.toList.map fun arg => ccs.ppACExpr arg sbracket (joinSep r (ofFormat .line)) | .ofExpr e => ccs.ppACExpr e def ppACR (ccs : CCState) : MessageData := let r := ccs.acR.toList.map fun (k, p, _) => group <| ccs.ppACApps k ++ ofFormat (Format.line ++ "--> ") ++ nest 4 (Format.line ++ ccs.ppACApps p) bracket "{" (joinSep r (ofFormat ("," ++ .line))) "}" def ppAC (ccs : CCState) : MessageData := sbracket (ccs.ppACDecls ++ ofFormat ("," ++ .line) ++ ccs.ppACR) end CCState /-- The congruence closure module (optionally) uses a normalizer. The idea is to use it (if available) to normalize auxiliary expressions produced by internal propagation rules (e.g., subsingleton propagator). -/ structure CCNormalizer where normalize : Expr → MetaM Expr attribute [inherit_doc CCNormalizer] CCNormalizer.normalize structure CCPropagationHandler where propagated : Array Expr → MetaM Unit /-- Congruence closure module invokes the following method when a new auxiliary term is created during propagation. -/ newAuxCCTerm : Expr → MetaM Unit /-- `CCStructure` extends `CCState` (which records a set of facts derived by congruence closure) by recording which steps still need to be taken to solve the goal. -/ structure CCStructure extends CCState where /-- Equalities that have been discovered but not processed. -/ todo : Array TodoEntry := #[] /-- AC-equalities that have been discovered but not processed. -/ acTodo : Array ACTodoEntry := #[] normalizer : Option CCNormalizer := none phandler : Option CCPropagationHandler := none cache : CCCongrTheoremCache := ∅ deriving Inhabited initialize registerTraceClass `Meta.Tactic.cc.merge registerTraceClass `Meta.Tactic.cc.failure registerTraceClass `Debug.Meta.Tactic.cc registerTraceClass `Debug.Meta.Tactic.cc.ac registerTraceClass `Debug.Meta.Tactic.cc.parentOccs end Mathlib.Tactic.CC
.lake/packages/mathlib/Mathlib/Tactic/Ring/NamePolyVars.lean
import Mathlib.Algebra.MvPolynomial.Basic /-! The command `name_poly_vars` names variables in `MvPolynomial (Fin n) R` for the appropriate value of `n`. The notation introduced by this command is local. Usage: ```lean variable (R : Type) [CommRing R] name_poly_vars X, Y, Z over R #check Y -- Y : MvPolynomial (Fin 3) R ``` -/ open Lean Elab Command namespace Mathlib.Tactic /-- The command `name_poly_vars` names variables in `MvPolynomial (Fin n) R` for the appropriate value of `n`. The notation introduced by this command is local. Usage: ```lean variable (R : Type) [CommRing R] name_poly_vars X, Y, Z over R #check Y -- Y : MvPolynomial (Fin 3) R ``` -/ syntax (name := namePolyVarsOver) "name_poly_vars " ident,+ " over " term : command @[command_elab namePolyVarsOver, inherit_doc namePolyVarsOver] def elabNameVariablesOver : CommandElab | `(command|name_poly_vars $vars:ident,* over $R:term) => do let vars := vars.getElems let size := vars.size let sizeStx : TSyntax `term := quote size for h : idx in [:size] do let var := vars[idx] let var := quote s!"{var.getId}" let idx : TSyntax `term ← `(($(quote idx) : Fin $sizeStx)) let cmd ← `(command|local notation3 $var:str => MvPolynomial.X (R := $R) (σ := Fin $sizeStx) $idx) elabCommand cmd | _ => throwUnsupportedSyntax end Mathlib.Tactic
.lake/packages/mathlib/Mathlib/Tactic/Ring/Basic.lean
import Mathlib.Tactic.NormNum.Inv import Mathlib.Tactic.NormNum.Pow import Mathlib.Util.AtomM /-! # `ring` tactic A tactic for solving equations in commutative (semi)rings, where the exponents can also contain variables. Based on <http://www.cs.ru.nl/~freek/courses/tt-2014/read/10.1.1.61.3041.pdf> . More precisely, expressions of the following form are supported: - constants (non-negative integers) - variables - coefficients (any rational number, embedded into the (semi)ring) - addition of expressions - multiplication of expressions (`a * b`) - scalar multiplication of expressions (`n • a`; the multiplier must have type `ℕ`) - exponentiation of expressions (the exponent must have type `ℕ`) - subtraction and negation of expressions (if the base is a full ring) The extension to exponents means that something like `2 * 2^n * b = b * 2^(n+1)` can be proved, even though it is not strictly speaking an equation in the language of commutative rings. ## Implementation notes The basic approach to prove equalities is to normalise both sides and check for equality. The normalisation is guided by building a value in the type `ExSum` at the meta level, together with a proof (at the base level) that the original value is equal to the normalised version. The outline of the file: - Define a mutual inductive family of types `ExSum`, `ExProd`, `ExBase`, which can represent expressions with `+`, `*`, `^` and rational numerals. The mutual induction ensures that associativity and distributivity are applied, by restricting which kinds of subexpressions appear as arguments to the various operators. - Represent addition, multiplication and exponentiation in the `ExSum` type, thus allowing us to map expressions to `ExSum` (the `eval` function drives this). We apply associativity and distributivity of the operators here (helped by `Ex*` types) and commutativity as well (by sorting the subterms; unfortunately not helped by anything). Any expression not of the above formats is treated as an atom (the same as a variable). There are some details we glossed over which make the plan more complicated: - The order on atoms is not initially obvious. We construct a list containing them in order of initial appearance in the expression, then use the index into the list as a key to order on. - For `pow`, the exponent must be a natural number, while the base can be any semiring `α`. We swap out operations for the base ring `α` with those for the exponent ring `ℕ` as soon as we deal with exponents. ## Caveats and future work The normalized form of an expression is the one that is useful for the tactic, but not as nice to read. To remedy this, the user-facing normalization calls `ringNFCore`. Subtraction cancels out identical terms, but division does not. That is: `a - a = 0 := by ring` solves the goal, but `a / a := 1 by ring` doesn't. Note that `0 / 0` is generally defined to be `0`, so division cancelling out is not true in general. Multiplication of powers can be simplified a little bit further: `2 ^ n * 2 ^ n = 4 ^ n := by ring` could be implemented in a similar way that `2 * a + 2 * a = 4 * a := by ring` already works. This feature wasn't needed yet, so it's not implemented yet. ## Tags ring, semiring, exponent, power -/ assert_not_exists IsOrderedMonoid namespace Mathlib.Tactic namespace Ring open Mathlib.Meta Qq NormNum Lean.Meta AtomM attribute [local instance] monadLiftOptionMetaM open Lean (MetaM Expr mkRawNatLit) /-- A shortcut instance for `CommSemiring ℕ` used by ring. -/ def instCommSemiringNat : CommSemiring ℕ := inferInstance /-- A shortcut instance for `CommSemiring ℤ` used by ring. -/ def instCommSemiringInt : CommSemiring ℤ := inferInstance /-- A typed expression of type `CommSemiring ℕ` used when we are working on ring subexpressions of type `ℕ`. -/ def sℕ : Q(CommSemiring ℕ) := q(instCommSemiringNat) /-- A typed expression of type `CommSemiring ℤ` used when we are working on ring subexpressions of type `ℤ`. -/ def sℤ : Q(CommSemiring ℤ) := q(instCommSemiringInt) mutual /-- The base `e` of a normalized exponent expression. -/ inductive ExBase : ∀ {u : Lean.Level} {α : Q(Type u)}, Q(CommSemiring $α) → (e : Q($α)) → Type /-- An atomic expression `e` with id `id`. Atomic expressions are those which `ring` cannot parse any further. For instance, `a + (a % b)` has `a` and `(a % b)` as atoms. The `ring1` tactic does not normalize the subexpressions in atoms, but `ring_nf` does. Atoms in fact represent equivalence classes of expressions, modulo definitional equality. The field `index : ℕ` should be a unique number for each class, while `value : expr` contains a representative of this class. The function `resolve_atom` determines the appropriate atom for a given expression. -/ | atom {sα} {e} (id : ℕ) : ExBase sα e /-- A sum of monomials. -/ | sum {sα} {e} (_ : ExSum sα e) : ExBase sα e /-- A monomial, which is a product of powers of `ExBase` expressions, terminated by a (nonzero) constant coefficient. -/ inductive ExProd : ∀ {u : Lean.Level} {α : Q(Type u)}, Q(CommSemiring $α) → (e : Q($α)) → Type /-- A coefficient `value`, which must not be `0`. `e` is a raw rat cast. If `value` is not an integer, then `hyp` should be a proof of `(value.den : α) ≠ 0`. -/ | const {sα} {e} (value : ℚ) (hyp : Option Expr := none) : ExProd sα e /-- A product `x ^ e * b` is a monomial if `b` is a monomial. Here `x` is an `ExBase` and `e` is an `ExProd` representing a monomial expression in `ℕ` (it is a monomial instead of a polynomial because we eagerly normalize `x ^ (a + b) = x ^ a * x ^ b`.) -/ | mul {u : Lean.Level} {α : Q(Type u)} {sα} {x : Q($α)} {e : Q(ℕ)} {b : Q($α)} : ExBase sα x → ExProd sℕ e → ExProd sα b → ExProd sα q($x ^ $e * $b) /-- A polynomial expression, which is a sum of monomials. -/ inductive ExSum : ∀ {u : Lean.Level} {α : Q(Type u)}, Q(CommSemiring $α) → (e : Q($α)) → Type /-- Zero is a polynomial. `e` is the expression `0`. -/ | zero {u : Lean.Level} {α : Q(Type u)} {sα : Q(CommSemiring $α)} : ExSum sα q(0 : $α) /-- A sum `a + b` is a polynomial if `a` is a monomial and `b` is another polynomial. -/ | add {u : Lean.Level} {α : Q(Type u)} {sα : Q(CommSemiring $α)} {a b : Q($α)} : ExProd sα a → ExSum sα b → ExSum sα q($a + $b) end mutual -- partial only to speed up compilation /-- Equality test for expressions. This is not a `BEq` instance because it is heterogeneous. -/ partial def ExBase.eq {u : Lean.Level} {α : Q(Type u)} {sα : Q(CommSemiring $α)} {a b : Q($α)} : ExBase sα a → ExBase sα b → Bool | .atom i, .atom j => i == j | .sum a, .sum b => a.eq b | _, _ => false @[inherit_doc ExBase.eq] partial def ExProd.eq {u : Lean.Level} {α : Q(Type u)} {sα : Q(CommSemiring $α)} {a b : Q($α)} : ExProd sα a → ExProd sα b → Bool | .const i _, .const j _ => i == j | .mul a₁ a₂ a₃, .mul b₁ b₂ b₃ => a₁.eq b₁ && a₂.eq b₂ && a₃.eq b₃ | _, _ => false @[inherit_doc ExBase.eq] partial def ExSum.eq {u : Lean.Level} {α : Q(Type u)} {sα : Q(CommSemiring $α)} {a b : Q($α)} : ExSum sα a → ExSum sα b → Bool | .zero, .zero => true | .add a₁ a₂, .add b₁ b₂ => a₁.eq b₁ && a₂.eq b₂ | _, _ => false end mutual -- partial only to speed up compilation /-- A total order on normalized expressions. This is not an `Ord` instance because it is heterogeneous. -/ partial def ExBase.cmp {u : Lean.Level} {α : Q(Type u)} {sα : Q(CommSemiring $α)} {a b : Q($α)} : ExBase sα a → ExBase sα b → Ordering | .atom i, .atom j => compare i j | .sum a, .sum b => a.cmp b | .atom .., .sum .. => .lt | .sum .., .atom .. => .gt @[inherit_doc ExBase.cmp] partial def ExProd.cmp {u : Lean.Level} {α : Q(Type u)} {sα : Q(CommSemiring $α)} {a b : Q($α)} : ExProd sα a → ExProd sα b → Ordering | .const i _, .const j _ => compare i j | .mul a₁ a₂ a₃, .mul b₁ b₂ b₃ => (a₁.cmp b₁).then (a₂.cmp b₂) |>.then (a₃.cmp b₃) | .const _ _, .mul .. => .lt | .mul .., .const _ _ => .gt @[inherit_doc ExBase.cmp] partial def ExSum.cmp {u : Lean.Level} {α : Q(Type u)} {sα : Q(CommSemiring $α)} {a b : Q($α)} : ExSum sα a → ExSum sα b → Ordering | .zero, .zero => .eq | .add a₁ a₂, .add b₁ b₂ => (a₁.cmp b₁).then (a₂.cmp b₂) | .zero, .add .. => .lt | .add .., .zero => .gt end variable {u : Lean.Level} {α : Q(Type u)} {sα : Q(CommSemiring $α)} instance : Inhabited (Σ e, (ExBase sα) e) := ⟨default, .atom 0⟩ instance : Inhabited (Σ e, (ExSum sα) e) := ⟨_, .zero⟩ instance : Inhabited (Σ e, (ExProd sα) e) := ⟨default, .const 0 none⟩ mutual /-- Converts `ExBase sα` to `ExBase sβ`, assuming `sα` and `sβ` are defeq. -/ partial def ExBase.cast {v : Lean.Level} {β : Q(Type v)} {sβ : Q(CommSemiring $β)} {a : Q($α)} : ExBase sα a → Σ a, ExBase sβ a | .atom i => ⟨a, .atom i⟩ | .sum a => let ⟨_, vb⟩ := a.cast; ⟨_, .sum vb⟩ /-- Converts `ExProd sα` to `ExProd sβ`, assuming `sα` and `sβ` are defeq. -/ partial def ExProd.cast {v : Lean.Level} {β : Q(Type v)} {sβ : Q(CommSemiring $β)} {a : Q($α)} : ExProd sα a → Σ a, ExProd sβ a | .const i h => ⟨a, .const i h⟩ | .mul a₁ a₂ a₃ => ⟨_, .mul a₁.cast.2 a₂ a₃.cast.2⟩ /-- Converts `ExSum sα` to `ExSum sβ`, assuming `sα` and `sβ` are defeq. -/ partial def ExSum.cast {v : Lean.Level} {β : Q(Type v)} {sβ : Q(CommSemiring $β)} {a : Q($α)} : ExSum sα a → Σ a, ExSum sβ a | .zero => ⟨_, .zero⟩ | .add a₁ a₂ => ⟨_, .add a₁.cast.2 a₂.cast.2⟩ end /-- The result of evaluating an (unnormalized) expression `e` into the type family `E` (one of `ExSum`, `ExProd`, `ExBase`) is a (normalized) element `e'` and a representation `E e'` for it, and a proof of `e = e'`. -/ structure Result {α : Q(Type u)} (E : Q($α) → Type) (e : Q($α)) where /-- The normalized result. -/ expr : Q($α) /-- The data associated to the normalization. -/ val : E expr /-- A proof that the original expression is equal to the normalized result. -/ proof : Q($e = $expr) instance {α : Q(Type u)} {E : Q($α) → Type} {e : Q($α)} [Inhabited (Σ e, E e)] : Inhabited (Result E e) := let ⟨e', v⟩ : Σ e, E e := default; ⟨e', v, default⟩ variable (sα) variable {R : Type*} [CommSemiring R] /-- Constructs the expression corresponding to `.const n`. (The `.const` constructor does not check that the expression is correct.) -/ def ExProd.mkNat (n : ℕ) : (e : Q($α)) × ExProd sα e := let lit : Q(ℕ) := mkRawNatLit n ⟨q(($lit).rawCast : $α), .const n none⟩ /-- Constructs the expression corresponding to `.const (-n)`. (The `.const` constructor does not check that the expression is correct.) -/ def ExProd.mkNegNat (_ : Q(Ring $α)) (n : ℕ) : (e : Q($α)) × ExProd sα e := let lit : Q(ℕ) := mkRawNatLit n ⟨q((Int.negOfNat $lit).rawCast : $α), .const (-n) none⟩ /-- Constructs the expression corresponding to `.const q h` for `q = n / d` and `h` a proof that `(d : α) ≠ 0`. (The `.const` constructor does not check that the expression is correct.) -/ def ExProd.mkNNRat (_ : Q(DivisionSemiring $α)) (q : ℚ) (n : Q(ℕ)) (d : Q(ℕ)) (h : Expr) : (e : Q($α)) × ExProd sα e := ⟨q(NNRat.rawCast $n $d : $α), .const q h⟩ /-- Constructs the expression corresponding to `.const q h` for `q = -(n / d)` and `h` a proof that `(d : α) ≠ 0`. (The `.const` constructor does not check that the expression is correct.) -/ def ExProd.mkNegNNRat (_ : Q(DivisionRing $α)) (q : ℚ) (n : Q(ℕ)) (d : Q(ℕ)) (h : Expr) : (e : Q($α)) × ExProd sα e := ⟨q(Rat.rawCast (.negOfNat $n) $d : $α), .const q h⟩ section /-- Embed an exponent (an `ExBase, ExProd` pair) as an `ExProd` by multiplying by 1. -/ def ExBase.toProd {α : Q(Type u)} {sα : Q(CommSemiring $α)} {a : Q($α)} {b : Q(ℕ)} (va : ExBase sα a) (vb : ExProd sℕ b) : ExProd sα q($a ^ $b * (nat_lit 1).rawCast) := .mul va vb (.const 1 none) /-- Embed `ExProd` in `ExSum` by adding 0. -/ def ExProd.toSum {sα : Q(CommSemiring $α)} {e : Q($α)} (v : ExProd sα e) : ExSum sα q($e + 0) := .add v .zero /-- Get the leading coefficient of an `ExProd`. -/ def ExProd.coeff {sα : Q(CommSemiring $α)} {e : Q($α)} : ExProd sα e → ℚ | .const q _ => q | .mul _ _ v => v.coeff end /-- Two monomials are said to "overlap" if they differ by a constant factor, in which case the constants just add. When this happens, the constant may be either zero (if the monomials cancel) or nonzero (if they add up); the zero case is handled specially. -/ inductive Overlap (e : Q($α)) where /-- The expression `e` (the sum of monomials) is equal to `0`. -/ | zero (_ : Q(IsNat $e (nat_lit 0))) /-- The expression `e` (the sum of monomials) is equal to another monomial (with nonzero leading coefficient). -/ | nonzero (_ : Result (ExProd sα) e) variable {a a' a₁ a₂ a₃ b b' b₁ b₂ b₃ c c₁ c₂ : R} /-! ### Addition -/ theorem add_overlap_pf (x : R) (e) (pq_pf : a + b = c) : x ^ e * a + x ^ e * b = x ^ e * c := by subst_vars; simp [mul_add] theorem add_overlap_pf_zero (x : R) (e) : IsNat (a + b) (nat_lit 0) → IsNat (x ^ e * a + x ^ e * b) (nat_lit 0) | ⟨h⟩ => ⟨by simp [h, ← mul_add]⟩ -- TODO: decide if this is a good idea globally in -- https://leanprover.zulipchat.com/#narrow/stream/270676-lean4/topic/.60MonadLift.20Option.20.28OptionT.20m.29.60/near/469097834 private local instance {m} [Pure m] : MonadLift Option (OptionT m) where monadLift f := .mk <| pure f /-- Given monomials `va, vb`, attempts to add them together to get another monomial. If the monomials are not compatible, returns `none`. For example, `xy + 2xy = 3xy` is a `.nonzero` overlap, while `xy + xz` returns `none` and `xy + -xy = 0` is a `.zero` overlap. -/ def evalAddOverlap {a b : Q($α)} (va : ExProd sα a) (vb : ExProd sα b) : OptionT MetaM (Overlap sα q($a + $b)) := do Lean.Core.checkSystem decl_name%.toString match va, vb with | .const za ha, .const zb hb => do let ra := Result.ofRawRat za a ha; let rb := Result.ofRawRat zb b hb let res ← ra.add rb match res with | .isNat _ (.lit (.natVal 0)) p => pure <| .zero p | rc => let ⟨zc, hc⟩ ← rc.toRatNZ let ⟨c, pc⟩ := rc.toRawEq pure <| .nonzero ⟨c, .const zc hc, pc⟩ | .mul (x := a₁) (e := a₂) va₁ va₂ va₃, .mul vb₁ vb₂ vb₃ => do guard (va₁.eq vb₁ && va₂.eq vb₂) match ← evalAddOverlap va₃ vb₃ with | .zero p => pure <| .zero (q(add_overlap_pf_zero $a₁ $a₂ $p) : Expr) | .nonzero ⟨_, vc, p⟩ => pure <| .nonzero ⟨_, .mul va₁ va₂ vc, (q(add_overlap_pf $a₁ $a₂ $p) : Expr)⟩ | _, _ => OptionT.fail theorem add_pf_zero_add (b : R) : 0 + b = b := by simp theorem add_pf_add_zero (a : R) : a + 0 = a := by simp theorem add_pf_add_overlap (_ : a₁ + b₁ = c₁) (_ : a₂ + b₂ = c₂) : (a₁ + a₂ : R) + (b₁ + b₂) = c₁ + c₂ := by subst_vars; simp [add_assoc, add_left_comm] theorem add_pf_add_overlap_zero (h : IsNat (a₁ + b₁) (nat_lit 0)) (h₄ : a₂ + b₂ = c) : (a₁ + a₂ : R) + (b₁ + b₂) = c := by subst_vars; rw [add_add_add_comm, h.1, Nat.cast_zero, add_pf_zero_add] theorem add_pf_add_lt (a₁ : R) (_ : a₂ + b = c) : (a₁ + a₂) + b = a₁ + c := by simp [*, add_assoc] theorem add_pf_add_gt (b₁ : R) (_ : a + b₂ = c) : a + (b₁ + b₂) = b₁ + c := by subst_vars; simp [add_left_comm] /-- Adds two polynomials `va, vb` together to get a normalized result polynomial. * `0 + b = b` * `a + 0 = a` * `a * x + a * y = a * (x + y)` (for `x`, `y` coefficients; uses `evalAddOverlap`) * `(a₁ + a₂) + (b₁ + b₂) = a₁ + (a₂ + (b₁ + b₂))` (if `a₁.lt b₁`) * `(a₁ + a₂) + (b₁ + b₂) = b₁ + ((a₁ + a₂) + b₂)` (if not `a₁.lt b₁`) -/ partial def evalAdd {a b : Q($α)} (va : ExSum sα a) (vb : ExSum sα b) : MetaM <| Result (ExSum sα) q($a + $b) := do Lean.Core.checkSystem decl_name%.toString match va, vb with | .zero, vb => return ⟨b, vb, q(add_pf_zero_add $b)⟩ | va, .zero => return ⟨a, va, q(add_pf_add_zero $a)⟩ | .add (a := a₁) (b := _a₂) va₁ va₂, .add (a := b₁) (b := _b₂) vb₁ vb₂ => match ← (evalAddOverlap sα va₁ vb₁).run with | some (.nonzero ⟨_, vc₁, pc₁⟩) => let ⟨_, vc₂, pc₂⟩ ← evalAdd va₂ vb₂ return ⟨_, .add vc₁ vc₂, q(add_pf_add_overlap $pc₁ $pc₂)⟩ | some (.zero pc₁) => let ⟨c₂, vc₂, pc₂⟩ ← evalAdd va₂ vb₂ return ⟨c₂, vc₂, q(add_pf_add_overlap_zero $pc₁ $pc₂)⟩ | none => if let .lt := va₁.cmp vb₁ then let ⟨_c, vc, (pc : Q($_a₂ + ($b₁ + $_b₂) = $_c))⟩ ← evalAdd va₂ vb return ⟨_, .add va₁ vc, q(add_pf_add_lt $a₁ $pc)⟩ else let ⟨_c, vc, (pc : Q($a₁ + $_a₂ + $_b₂ = $_c))⟩ ← evalAdd va vb₂ return ⟨_, .add vb₁ vc, q(add_pf_add_gt $b₁ $pc)⟩ /-! ### Multiplication -/ theorem one_mul (a : R) : (nat_lit 1).rawCast * a = a := by simp [Nat.rawCast] theorem mul_one (a : R) : a * (nat_lit 1).rawCast = a := by simp [Nat.rawCast] theorem mul_pf_left (a₁ : R) (a₂) (_ : a₃ * b = c) : (a₁ ^ a₂ * a₃ : R) * b = a₁ ^ a₂ * c := by subst_vars; rw [mul_assoc] theorem mul_pf_right (b₁ : R) (b₂) (_ : a * b₃ = c) : a * (b₁ ^ b₂ * b₃) = b₁ ^ b₂ * c := by subst_vars; rw [mul_left_comm] theorem mul_pp_pf_overlap {ea eb e : ℕ} (x : R) (_ : ea + eb = e) (_ : a₂ * b₂ = c) : (x ^ ea * a₂ : R) * (x ^ eb * b₂) = x ^ e * c := by subst_vars; simp [pow_add, mul_mul_mul_comm] /-- Multiplies two monomials `va, vb` together to get a normalized result monomial. * `x * y = (x * y)` (for `x`, `y` coefficients) * `x * (b₁ * b₂) = b₁ * (b₂ * x)` (for `x` coefficient) * `(a₁ * a₂) * y = a₁ * (a₂ * y)` (for `y` coefficient) * `(x ^ ea * a₂) * (x ^ eb * b₂) = x ^ (ea + eb) * (a₂ * b₂)` (if `ea` and `eb` are identical except coefficient) * `(a₁ * a₂) * (b₁ * b₂) = a₁ * (a₂ * (b₁ * b₂))` (if `a₁.lt b₁`) * `(a₁ * a₂) * (b₁ * b₂) = b₁ * ((a₁ * a₂) * b₂)` (if not `a₁.lt b₁`) -/ partial def evalMulProd {a b : Q($α)} (va : ExProd sα a) (vb : ExProd sα b) : MetaM <| Result (ExProd sα) q($a * $b) := do Lean.Core.checkSystem decl_name%.toString match va, vb with | .const za ha, .const zb hb => if za = 1 then return ⟨b, .const zb hb, (q(one_mul $b) : Expr)⟩ else if zb = 1 then return ⟨a, .const za ha, (q(mul_one $a) : Expr)⟩ else let ra := Result.ofRawRat za a ha; let rb := Result.ofRawRat zb b hb let rc ← ra.mul rb let ⟨zc, hc⟩ := rc.toRatNZ.get! let ⟨c, pc⟩ := rc.toRawEq return ⟨c, .const zc hc, pc⟩ | .mul (x := a₁) (e := a₂) va₁ va₂ va₃, .const _ _ => let ⟨_, vc, pc⟩ ← evalMulProd va₃ vb return ⟨_, .mul va₁ va₂ vc, (q(mul_pf_left $a₁ $a₂ $pc) : Expr)⟩ | .const _ _, .mul (x := b₁) (e := b₂) vb₁ vb₂ vb₃ => let ⟨_, vc, pc⟩ ← evalMulProd va vb₃ return ⟨_, .mul vb₁ vb₂ vc, (q(mul_pf_right $b₁ $b₂ $pc) : Expr)⟩ | .mul (x := xa) (e := ea) vxa vea va₂, .mul (x := xb) (e := eb) vxb veb vb₂ => do if vxa.eq vxb then if let some (.nonzero ⟨_, ve, pe⟩) ← (evalAddOverlap sℕ vea veb).run then let ⟨_, vc, pc⟩ ← evalMulProd va₂ vb₂ return ⟨_, .mul vxa ve vc, (q(mul_pp_pf_overlap $xa $pe $pc) : Expr)⟩ if let .lt := (vxa.cmp vxb).then (vea.cmp veb) then let ⟨_, vc, pc⟩ ← evalMulProd va₂ vb return ⟨_, .mul vxa vea vc, (q(mul_pf_left $xa $ea $pc) : Expr)⟩ else let ⟨_, vc, pc⟩ ← evalMulProd va vb₂ return ⟨_, .mul vxb veb vc, (q(mul_pf_right $xb $eb $pc) : Expr)⟩ theorem mul_zero (a : R) : a * 0 = 0 := by simp theorem mul_add {d : R} (_ : (a : R) * b₁ = c₁) (_ : a * b₂ = c₂) (_ : c₁ + 0 + c₂ = d) : a * (b₁ + b₂) = d := by subst_vars; simp [_root_.mul_add] /-- Multiplies a monomial `va` to a polynomial `vb` to get a normalized result polynomial. * `a * 0 = 0` * `a * (b₁ + b₂) = (a * b₁) + (a * b₂)` -/ def evalMul₁ {a b : Q($α)} (va : ExProd sα a) (vb : ExSum sα b) : MetaM <| Result (ExSum sα) q($a * $b) := do match vb with | .zero => return ⟨_, .zero, q(mul_zero $a)⟩ | .add vb₁ vb₂ => let ⟨_, vc₁, pc₁⟩ ← evalMulProd sα va vb₁ let ⟨_, vc₂, pc₂⟩ ← evalMul₁ va vb₂ let ⟨_, vd, pd⟩ ← evalAdd sα vc₁.toSum vc₂ return ⟨_, vd, q(mul_add $pc₁ $pc₂ $pd)⟩ theorem zero_mul (b : R) : 0 * b = 0 := by simp theorem add_mul {d : R} (_ : (a₁ : R) * b = c₁) (_ : a₂ * b = c₂) (_ : c₁ + c₂ = d) : (a₁ + a₂) * b = d := by subst_vars; simp [_root_.add_mul] /-- Multiplies two polynomials `va, vb` together to get a normalized result polynomial. * `0 * b = 0` * `(a₁ + a₂) * b = (a₁ * b) + (a₂ * b)` -/ def evalMul {a b : Q($α)} (va : ExSum sα a) (vb : ExSum sα b) : MetaM <| Result (ExSum sα) q($a * $b) := do match va with | .zero => return ⟨_, .zero, q(zero_mul $b)⟩ | .add va₁ va₂ => let ⟨_, vc₁, pc₁⟩ ← evalMul₁ sα va₁ vb let ⟨_, vc₂, pc₂⟩ ← evalMul va₂ vb let ⟨_, vd, pd⟩ ← evalAdd sα vc₁ vc₂ return ⟨_, vd, q(add_mul $pc₁ $pc₂ $pd)⟩ /-! ### Scalar multiplication by `ℕ` -/ theorem natCast_nat (n) : ((Nat.rawCast n : ℕ) : R) = Nat.rawCast n := by simp theorem natCast_mul {a₁ a₃ : ℕ} (a₂) (_ : ((a₁ : ℕ) : R) = b₁) (_ : ((a₃ : ℕ) : R) = b₃) : ((a₁ ^ a₂ * a₃ : ℕ) : R) = b₁ ^ a₂ * b₃ := by subst_vars; simp theorem natCast_zero : ((0 : ℕ) : R) = 0 := Nat.cast_zero theorem natCast_add {a₁ a₂ : ℕ} (_ : ((a₁ : ℕ) : R) = b₁) (_ : ((a₂ : ℕ) : R) = b₂) : ((a₁ + a₂ : ℕ) : R) = b₁ + b₂ := by subst_vars; simp mutual /-- Applies `Nat.cast` to a nat polynomial to produce a polynomial in `α`. * An atom `e` causes `↑e` to be allocated as a new atom. * A sum delegates to `ExSum.evalNatCast`. -/ partial def ExBase.evalNatCast {a : Q(ℕ)} (va : ExBase sℕ a) : AtomM (Result (ExBase sα) q($a)) := match va with | .atom _ => do let (i, ⟨b', _⟩) ← addAtomQ q($a) pure ⟨b', ExBase.atom i, q(Eq.refl $b')⟩ | .sum va => do let ⟨_, vc, p⟩ ← va.evalNatCast pure ⟨_, .sum vc, p⟩ /-- Applies `Nat.cast` to a nat monomial to produce a monomial in `α`. * `↑c = c` if `c` is a numeric literal * `↑(a ^ n * b) = ↑a ^ n * ↑b` -/ partial def ExProd.evalNatCast {a : Q(ℕ)} (va : ExProd sℕ a) : AtomM (Result (ExProd sα) q($a)) := match va with | .const c hc => have n : Q(ℕ) := a.appArg! pure ⟨q(Nat.rawCast $n), .const c hc, (q(natCast_nat (R := $α) $n) : Expr)⟩ | .mul (e := a₂) va₁ va₂ va₃ => do let ⟨_, vb₁, pb₁⟩ ← va₁.evalNatCast let ⟨_, vb₃, pb₃⟩ ← va₃.evalNatCast pure ⟨_, .mul vb₁ va₂ vb₃, q(natCast_mul $a₂ $pb₁ $pb₃)⟩ /-- Applies `Nat.cast` to a nat polynomial to produce a polynomial in `α`. * `↑0 = 0` * `↑(a + b) = ↑a + ↑b` -/ partial def ExSum.evalNatCast {a : Q(ℕ)} (va : ExSum sℕ a) : AtomM (Result (ExSum sα) q($a)) := match va with | .zero => pure ⟨_, .zero, q(natCast_zero (R := $α))⟩ | .add va₁ va₂ => do let ⟨_, vb₁, pb₁⟩ ← va₁.evalNatCast let ⟨_, vb₂, pb₂⟩ ← va₂.evalNatCast pure ⟨_, .add vb₁ vb₂, q(natCast_add $pb₁ $pb₂)⟩ end theorem smul_nat {a b c : ℕ} (_ : (a * b : ℕ) = c) : a • b = c := by subst_vars; simp theorem smul_eq_cast {a : ℕ} (_ : ((a : ℕ) : R) = a') (_ : a' * b = c) : a • b = c := by subst_vars; simp /-- Constructs the scalar multiplication `n • a`, where both `n : ℕ` and `a : α` are normalized polynomial expressions. * `a • b = a * b` if `α = ℕ` * `a • b = ↑a * b` otherwise -/ def evalNSMul {a : Q(ℕ)} {b : Q($α)} (va : ExSum sℕ a) (vb : ExSum sα b) : AtomM (Result (ExSum sα) q($a • $b)) := do if ← isDefEq sα sℕ then let ⟨_, va'⟩ := va.cast have _b : Q(ℕ) := b let ⟨(_c : Q(ℕ)), vc, (pc : Q($a * $_b = $_c))⟩ ← evalMul sα va' vb pure ⟨_, vc, (q(smul_nat $pc) : Expr)⟩ else let ⟨_, va', pa'⟩ ← va.evalNatCast sα let ⟨_, vc, pc⟩ ← evalMul sα va' vb pure ⟨_, vc, (q(smul_eq_cast $pa' $pc) : Expr)⟩ /-! ### Scalar multiplication by `ℤ` -/ theorem natCast_int {R} [Ring R] (n) : ((Nat.rawCast n : ℤ) : R) = Nat.rawCast n := by simp theorem intCast_negOfNat_Int {R} [Ring R] (n) : ((Int.rawCast (Int.negOfNat n) : ℤ) : R) = Int.rawCast (Int.negOfNat n) := by simp theorem intCast_mul {R} [Ring R] {b₁ b₃ : R} {a₁ a₃ : ℤ} (a₂) (_ : ((a₁ : ℤ) : R) = b₁) (_ : ((a₃ : ℤ) : R) = b₃) : ((a₁ ^ a₂ * a₃ : ℤ) : R) = b₁ ^ a₂ * b₃ := by subst_vars; simp theorem intCast_zero {R} [Ring R] : ((0 : ℤ) : R) = 0 := Int.cast_zero theorem intCast_add {R} [Ring R] {b₁ b₂ : R} {a₁ a₂ : ℤ} (_ : ((a₁ : ℤ) : R) = b₁) (_ : ((a₂ : ℤ) : R) = b₂) : ((a₁ + a₂ : ℤ) : R) = b₁ + b₂ := by subst_vars; simp mutual /-- Applies `Int.cast` to an int polynomial to produce a polynomial in `α`. * An atom `e` causes `↑e` to be allocated as a new atom. * A sum delegates to `ExSum.evalIntCast`. -/ partial def ExBase.evalIntCast {a : Q(ℤ)} (rα : Q(Ring $α)) (va : ExBase sℤ a) : AtomM (Result (ExBase sα) q($a)) := match va with | .atom _ => do let (i, ⟨b', _⟩) ← addAtomQ q($a) pure ⟨b', ExBase.atom i, q(Eq.refl $b')⟩ | .sum va => do let ⟨_, vc, p⟩ ← va.evalIntCast rα pure ⟨_, .sum vc, p⟩ /-- Applies `Int.cast` to an int monomial to produce a monomial in `α`. * `↑c = c` if `c` is a numeric literal * `↑(a ^ n * b) = ↑a ^ n * ↑b` -/ partial def ExProd.evalIntCast {a : Q(ℤ)} (rα : Q(Ring $α)) (va : ExProd sℤ a) : AtomM (Result (ExProd sα) q($a)) := match va with | .const c hc => do match a with | ~q(Nat.rawCast $m) => pure ⟨q(Nat.rawCast $m), .const c hc, q(natCast_int (R := $α) $m)⟩ | ~q(Int.rawCast (Int.negOfNat $m)) => pure ⟨q(Int.rawCast (Int.negOfNat $m)), .const c hc, q(intCast_negOfNat_Int (R := $α) $m)⟩ | .mul (e := a₂) va₁ va₂ va₃ => do let ⟨_, vb₁, pb₁⟩ ← va₁.evalIntCast rα let ⟨_, vb₃, pb₃⟩ ← va₃.evalIntCast rα -- Qq is probably unhappy about `Ring` and `CommSemiring` at the same time. let pf ← mkAppM ``intCast_mul #[a₂, pb₁, pb₃] pure ⟨_, .mul vb₁ va₂ vb₃, pf⟩ /-- Applies `Int.cast` to an int polynomial to produce a polynomial in `α`. * `↑0 = 0` * `↑(a + b) = ↑a + ↑b` -/ partial def ExSum.evalIntCast {a : Q(ℤ)} (rα : Q(Ring $α)) (va : ExSum sℤ a) : AtomM (Result (ExSum sα) q($a)) := match va with | .zero => do -- Qq is probably unhappy about `Ring` and `CommSemiring` at the same time. let pf ← mkAppOptM ``intCast_zero #[α, none] pure ⟨_, .zero, pf⟩ | .add va₁ va₂ => do let ⟨_, vb₁, pb₁⟩ ← va₁.evalIntCast rα let ⟨_, vb₂, pb₂⟩ ← va₂.evalIntCast rα -- Qq is probably unhappy about `Ring` and `CommSemiring` at the same time. let pf ← mkAppM ``intCast_add #[pb₁, pb₂] pure ⟨_, .add vb₁ vb₂, pf⟩ end theorem smul_int {a b c : ℤ} (_ : (a * b : ℤ) = c) : a • b = c := by subst_vars; simp theorem smul_eq_intCast {R} [Ring R] {a' b c : R} {a : ℤ} (_ : ((a : ℤ) : R) = a') (_ : a' * b = c) : a • b = c := by subst_vars; simp /-- Constructs the scalar multiplication `n • a`, where both `n : ℤ` and `a : α` are normalized polynomial expressions. * `a • b = a * b` if `α = ℤ` * `a • b = a' * b` otherwise, where `a'` is `↑a` with the coercion pushed as deep as possible. -/ def evalZSMul {a : Q(ℤ)} {b : Q($α)} (rα : Q(Ring $α)) (va : ExSum sℤ a) (vb : ExSum sα b) : AtomM (Result (ExSum sα) q($a • $b)) := do if ← isDefEq sα sℤ then let ⟨_, va'⟩ := va.cast have _b : Q(ℤ) := b let ⟨(_c : Q(ℤ)), vc, (pc : Q($a * $_b = $_c))⟩ ← evalMul sα va' vb pure ⟨_, vc, (q(smul_int $pc) : Expr)⟩ else let ⟨_, va', pa'⟩ ← va.evalIntCast sα rα let ⟨_, vc, pc⟩ ← evalMul sα va' vb -- Qq is probably unhappy about `Ring` and `CommSemiring` at the same time. let pf ← mkAppM ``smul_eq_intCast #[pa', pc] pure ⟨_, vc, pf⟩ /-! ### Negation -/ theorem neg_one_mul {R} [Ring R] {a b : R} (_ : (Int.negOfNat (nat_lit 1)).rawCast * a = b) : -a = b := by subst_vars; simp [Int.negOfNat] theorem neg_mul {R} [Ring R] (a₁ : R) (a₂) {a₃ b : R} (_ : -a₃ = b) : -(a₁ ^ a₂ * a₃) = a₁ ^ a₂ * b := by subst_vars; simp /-- Negates a monomial `va` to get another monomial. * `-c = (-c)` (for `c` coefficient) * `-(a₁ * a₂) = a₁ * -a₂` -/ def evalNegProd {a : Q($α)} (rα : Q(Ring $α)) (va : ExProd sα a) : MetaM <| Result (ExProd sα) q(-$a) := do Lean.Core.checkSystem decl_name%.toString match va with | .const za ha => let ⟨m1, _⟩ := ExProd.mkNegNat sα rα 1 let rm := Result.isNegNat rα q(nat_lit 1) q(IsInt.of_raw $α (.negOfNat (nat_lit 1))) let ra := Result.ofRawRat za a ha let rb ← rm.mul ra let ⟨zb, hb⟩ := rb.toRatNZ.get! let ⟨b, pb⟩ := rb.toRawEq -- Qq is probably unhappy about `Ring` and `CommSemiring` at the same time. have pb : Q(((Int.negOfNat (nat_lit 1)).rawCast : $α) * $a = $b) := pb return ⟨b, .const zb hb, q(neg_one_mul (R := $α) $pb)⟩ | .mul (x := a₁) (e := a₂) va₁ va₂ va₃ => let ⟨_, vb, pb⟩ ← evalNegProd rα va₃ return ⟨_, .mul va₁ va₂ vb, (q(neg_mul $a₁ $a₂ $pb) : Expr)⟩ theorem neg_zero {R} [Ring R] : -(0 : R) = 0 := by simp theorem neg_add {R} [Ring R] {a₁ a₂ b₁ b₂ : R} (_ : -a₁ = b₁) (_ : -a₂ = b₂) : -(a₁ + a₂) = b₁ + b₂ := by subst_vars; simp [add_comm] /-- Negates a polynomial `va` to get another polynomial. * `-0 = 0` (for `c` coefficient) * `-(a₁ + a₂) = -a₁ + -a₂` -/ def evalNeg {a : Q($α)} (rα : Q(Ring $α)) (va : ExSum sα a) : MetaM <| Result (ExSum sα) q(-$a) := do match va with | .zero => return ⟨_, .zero, (q(neg_zero (R := $α)) : Expr)⟩ | .add va₁ va₂ => let ⟨_, vb₁, pb₁⟩ ← evalNegProd sα rα va₁ let ⟨_, vb₂, pb₂⟩ ← evalNeg rα va₂ return ⟨_, .add vb₁ vb₂, (q(neg_add $pb₁ $pb₂) : Expr)⟩ /-! ### Subtraction -/ theorem sub_pf {R} [Ring R] {a b c d : R} (_ : -b = c) (_ : a + c = d) : a - b = d := by subst_vars; simp [sub_eq_add_neg] /-- Subtracts two polynomials `va, vb` to get a normalized result polynomial. * `a - b = a + -b` -/ def evalSub {α : Q(Type u)} (sα : Q(CommSemiring $α)) {a b : Q($α)} (rα : Q(Ring $α)) (va : ExSum sα a) (vb : ExSum sα b) : MetaM <| Result (ExSum sα) q($a - $b) := do let ⟨_c, vc, pc⟩ ← evalNeg sα rα vb let ⟨d, vd, (pd : Q($a + $_c = $d))⟩ ← evalAdd sα va vc return ⟨d, vd, (q(sub_pf $pc $pd) : Expr)⟩ /-! ### Exponentiation -/ theorem pow_prod_atom (a : R) (b) : a ^ b = (a + 0) ^ b * (nat_lit 1).rawCast := by simp /-- The fallback case for exponentiating polynomials is to use `ExBase.toProd` to just build an exponent expression. (This has a slightly different normalization than `evalPowAtom` because the input types are different.) * `x ^ e = (x + 0) ^ e * 1` -/ def evalPowProdAtom {a : Q($α)} {b : Q(ℕ)} (va : ExProd sα a) (vb : ExProd sℕ b) : Result (ExProd sα) q($a ^ $b) := ⟨_, (ExBase.sum va.toSum).toProd vb, q(pow_prod_atom $a $b)⟩ theorem pow_atom (a : R) (b) : a ^ b = a ^ b * (nat_lit 1).rawCast + 0 := by simp /-- The fallback case for exponentiating polynomials is to use `ExBase.toProd` to just build an exponent expression. * `x ^ e = x ^ e * 1 + 0` -/ def evalPowAtom {a : Q($α)} {b : Q(ℕ)} (va : ExBase sα a) (vb : ExProd sℕ b) : Result (ExSum sα) q($a ^ $b) := ⟨_, (va.toProd vb).toSum, q(pow_atom $a $b)⟩ theorem const_pos (n : ℕ) (h : Nat.ble 1 n = true) : 0 < (n.rawCast : ℕ) := Nat.le_of_ble_eq_true h theorem mul_exp_pos {a₁ a₂ : ℕ} (n) (h₁ : 0 < a₁) (h₂ : 0 < a₂) : 0 < a₁ ^ n * a₂ := Nat.mul_pos (Nat.pow_pos h₁) h₂ theorem add_pos_left {a₁ : ℕ} (a₂) (h : 0 < a₁) : 0 < a₁ + a₂ := Nat.lt_of_lt_of_le h (Nat.le_add_right ..) theorem add_pos_right {a₂ : ℕ} (a₁) (h : 0 < a₂) : 0 < a₁ + a₂ := Nat.lt_of_lt_of_le h (Nat.le_add_left ..) mutual /-- Attempts to prove that a polynomial expression in `ℕ` is positive. * Atoms are not (necessarily) positive * Sums defer to `ExSum.evalPos` -/ partial def ExBase.evalPos {a : Q(ℕ)} (va : ExBase sℕ a) : Option Q(0 < $a) := match va with | .atom _ => none | .sum va => va.evalPos /-- Attempts to prove that a monomial expression in `ℕ` is positive. * `0 < c` (where `c` is a numeral) is true by the normalization invariant (`c` is not zero) * `0 < x ^ e * b` if `0 < x` and `0 < b` -/ partial def ExProd.evalPos {a : Q(ℕ)} (va : ExProd sℕ a) : Option Q(0 < $a) := match va with | .const _ _ => -- it must be positive because it is a nonzero nat literal have lit : Q(ℕ) := a.appArg! haveI : $a =Q Nat.rawCast $lit := ⟨⟩ haveI p : Nat.ble 1 $lit =Q true := ⟨⟩ some q(const_pos $lit $p) | .mul (e := ea₁) vxa₁ _ va₂ => do let pa₁ ← vxa₁.evalPos let pa₂ ← va₂.evalPos some q(mul_exp_pos $ea₁ $pa₁ $pa₂) /-- Attempts to prove that a polynomial expression in `ℕ` is positive. * `0 < 0` fails * `0 < a + b` if `0 < a` or `0 < b` -/ partial def ExSum.evalPos {a : Q(ℕ)} (va : ExSum sℕ a) : Option Q(0 < $a) := match va with | .zero => none | .add (a := a₁) (b := a₂) va₁ va₂ => do match va₁.evalPos with | some p => some q(add_pos_left $a₂ $p) | none => let p ← va₂.evalPos; some q(add_pos_right $a₁ $p) end theorem pow_one (a : R) : a ^ nat_lit 1 = a := by simp theorem pow_bit0 {k : ℕ} (_ : (a : R) ^ k = b) (_ : b * b = c) : a ^ (Nat.mul (nat_lit 2) k) = c := by subst_vars; simp [Nat.succ_mul, pow_add] theorem pow_bit1 {k : ℕ} {d : R} (_ : (a : R) ^ k = b) (_ : b * b = c) (_ : c * a = d) : a ^ (Nat.add (Nat.mul (nat_lit 2) k) (nat_lit 1)) = d := by subst_vars; simp [Nat.succ_mul, pow_add] /-- The main case of exponentiation of ring expressions is when `va` is a polynomial and `n` is a nonzero literal expression, like `(x + y)^5`. In this case we work out the polynomial completely into a sum of monomials. * `x ^ 1 = x` * `x ^ (2*n) = x ^ n * x ^ n` * `x ^ (2*n+1) = x ^ n * x ^ n * x` -/ partial def evalPowNat {a : Q($α)} (va : ExSum sα a) (n : Q(ℕ)) : MetaM <| Result (ExSum sα) q($a ^ $n) := do let nn := n.natLit! if nn = 1 then return ⟨_, va, (q(pow_one $a) : Expr)⟩ else let nm := nn >>> 1 have m : Q(ℕ) := mkRawNatLit nm if nn &&& 1 = 0 then let ⟨_, vb, pb⟩ ← evalPowNat va m let ⟨_, vc, pc⟩ ← evalMul sα vb vb return ⟨_, vc, (q(pow_bit0 $pb $pc) : Expr)⟩ else let ⟨_, vb, pb⟩ ← evalPowNat va m let ⟨_, vc, pc⟩ ← evalMul sα vb vb let ⟨_, vd, pd⟩ ← evalMul sα vc va return ⟨_, vd, (q(pow_bit1 $pb $pc $pd) : Expr)⟩ theorem one_pow (b : ℕ) : ((nat_lit 1).rawCast : R) ^ b = (nat_lit 1).rawCast := by simp theorem mul_pow {ea₁ b c₁ : ℕ} {xa₁ : R} (_ : ea₁ * b = c₁) (_ : a₂ ^ b = c₂) : (xa₁ ^ ea₁ * a₂ : R) ^ b = xa₁ ^ c₁ * c₂ := by subst_vars; simp [_root_.mul_pow, pow_mul] -- needed to lift from `OptionT CoreM` to `OptionT MetaM` private local instance {m m'} [Monad m] [Monad m'] [MonadLiftT m m'] : MonadLiftT (OptionT m) (OptionT m') where monadLift x := OptionT.mk x.run /-- There are several special cases when exponentiating monomials: * `1 ^ n = 1` * `x ^ y = (x ^ y)` when `x` and `y` are constants * `(a * b) ^ e = a ^ e * b ^ e` In all other cases we use `evalPowProdAtom`. -/ def evalPowProd {a : Q($α)} {b : Q(ℕ)} (va : ExProd sα a) (vb : ExProd sℕ b) : MetaM <| Result (ExProd sα) q($a ^ $b) := do Lean.Core.checkSystem decl_name%.toString let res : OptionT MetaM (Result (ExProd sα) q($a ^ $b)) := do match va, vb with | .const 1, _ => return ⟨_, va, (q(one_pow (R := $α) $b) : Expr)⟩ | .const za ha, .const zb hb => assert! 0 ≤ zb let ra := Result.ofRawRat za a ha have lit : Q(ℕ) := b.appArg! let rb := (q(IsNat.of_raw ℕ $lit) : Expr) let rc ← NormNum.evalPow.core q($a ^ $b) q(HPow.hPow) q($a) q($b) lit rb q(CommSemiring.toSemiring) ra let ⟨zc, hc⟩ ← rc.toRatNZ let ⟨c, pc⟩ := rc.toRawEq return ⟨c, .const zc hc, pc⟩ | .mul vxa₁ vea₁ va₂, vb => let ⟨_, vc₁, pc₁⟩ ← evalMulProd sℕ vea₁ vb let ⟨_, vc₂, pc₂⟩ ← evalPowProd va₂ vb return ⟨_, .mul vxa₁ vc₁ vc₂, q(mul_pow $pc₁ $pc₂)⟩ | _, _ => OptionT.fail return (← res.run).getD (evalPowProdAtom sα va vb) /-- The result of `extractCoeff` is a numeral and a proof that the original expression factors by this numeral. -/ structure ExtractCoeff (e : Q(ℕ)) where /-- A raw natural number literal. -/ k : Q(ℕ) /-- The result of extracting the coefficient is a monic monomial. -/ e' : Q(ℕ) /-- `e'` is a monomial. -/ ve' : ExProd sℕ e' /-- The proof that `e` splits into the coefficient `k` and the monic monomial `e'`. -/ p : Q($e = $e' * $k) theorem coeff_one (k : ℕ) : k.rawCast = (nat_lit 1).rawCast * k := by simp theorem coeff_mul {a₃ c₂ k : ℕ} (a₁ a₂ : ℕ) (_ : a₃ = c₂ * k) : a₁ ^ a₂ * a₃ = (a₁ ^ a₂ * c₂) * k := by subst_vars; rw [mul_assoc] /-- Given a monomial expression `va`, splits off the leading coefficient `k` and the remainder `e'`, stored in the `ExtractCoeff` structure. * `c = 1 * c` (if `c` is a constant) * `a * b = (a * b') * k` if `b = b' * k` -/ def extractCoeff {a : Q(ℕ)} (va : ExProd sℕ a) : ExtractCoeff a := match va with | .const _ _ => have k : Q(ℕ) := a.appArg! ⟨k, q((nat_lit 1).rawCast), .const 1, (q(coeff_one $k) : Expr)⟩ | .mul (x := a₁) (e := a₂) va₁ va₂ va₃ => let ⟨k, _, vc, pc⟩ := extractCoeff va₃ ⟨k, _, .mul va₁ va₂ vc, q(coeff_mul $a₁ $a₂ $pc)⟩ theorem pow_one_cast (a : R) : a ^ (nat_lit 1).rawCast = a := by simp theorem zero_pow {b : ℕ} (_ : 0 < b) : (0 : R) ^ b = 0 := match b with | b+1 => by simp [pow_succ] theorem single_pow {b : ℕ} (_ : (a : R) ^ b = c) : (a + 0) ^ b = c + 0 := by simp [*] theorem pow_nat {b c k : ℕ} {d e : R} (_ : b = c * k) (_ : a ^ c = d) (_ : d ^ k = e) : (a : R) ^ b = e := by subst_vars; simp [pow_mul] /-- Exponentiates a polynomial `va` by a monomial `vb`, including several special cases. * `a ^ 1 = a` * `0 ^ e = 0` if `0 < e` * `(a + 0) ^ b = a ^ b` computed using `evalPowProd` * `a ^ b = (a ^ b') ^ k` if `b = b' * k` and `k > 1` Otherwise `a ^ b` is just encoded as `a ^ b * 1 + 0` using `evalPowAtom`. -/ partial def evalPow₁ {a : Q($α)} {b : Q(ℕ)} (va : ExSum sα a) (vb : ExProd sℕ b) : MetaM <| Result (ExSum sα) q($a ^ $b) := do match va, vb with | va, .const 1 => haveI : $b =Q Nat.rawCast (nat_lit 1) := ⟨⟩ return ⟨_, va, q(pow_one_cast $a)⟩ | .zero, vb => match vb.evalPos with | some p => return ⟨_, .zero, q(zero_pow (R := $α) $p)⟩ | none => return evalPowAtom sα (.sum .zero) vb | ExSum.add va .zero, vb => -- TODO: using `.add` here takes a while to compile? let ⟨_, vc, pc⟩ ← evalPowProd sα va vb return ⟨_, vc.toSum, q(single_pow $pc)⟩ | va, vb => if vb.coeff > 1 then let ⟨k, _, vc, pc⟩ := extractCoeff vb let ⟨_, vd, pd⟩ ← evalPow₁ va vc let ⟨_, ve, pe⟩ ← evalPowNat sα vd k return ⟨_, ve, q(pow_nat $pc $pd $pe)⟩ else return evalPowAtom sα (.sum va) vb theorem pow_zero (a : R) : a ^ 0 = (nat_lit 1).rawCast + 0 := by simp theorem pow_add {b₁ b₂ : ℕ} {d : R} (_ : a ^ b₁ = c₁) (_ : a ^ b₂ = c₂) (_ : c₁ * c₂ = d) : (a : R) ^ (b₁ + b₂) = d := by subst_vars; simp [_root_.pow_add] /-- Exponentiates two polynomials `va, vb`. * `a ^ 0 = 1` * `a ^ (b₁ + b₂) = a ^ b₁ * a ^ b₂` -/ def evalPow {a : Q($α)} {b : Q(ℕ)} (va : ExSum sα a) (vb : ExSum sℕ b) : MetaM <| Result (ExSum sα) q($a ^ $b) := do match vb with | .zero => return ⟨_, (ExProd.mkNat sα 1).2.toSum, q(pow_zero $a)⟩ | .add vb₁ vb₂ => let ⟨_, vc₁, pc₁⟩ ← evalPow₁ sα va vb₁ let ⟨_, vc₂, pc₂⟩ ← evalPow va vb₂ let ⟨_, vd, pd⟩ ← evalMul sα vc₁ vc₂ return ⟨_, vd, q(pow_add $pc₁ $pc₂ $pd)⟩ /-- This cache contains data required by the `ring` tactic during execution. -/ structure Cache {α : Q(Type u)} (sα : Q(CommSemiring $α)) where /-- A ring instance on `α`, if available. -/ rα : Option Q(Ring $α) /-- A division semiring instance on `α`, if available. -/ dsα : Option Q(DivisionSemiring $α) /-- A characteristic zero ring instance on `α`, if available. -/ czα : Option Q(CharZero $α) /-- Create a new cache for `α` by doing the necessary instance searches. -/ def mkCache {α : Q(Type u)} (sα : Q(CommSemiring $α)) : MetaM (Cache sα) := return { rα := (← trySynthInstanceQ q(Ring $α)).toOption dsα := (← trySynthInstanceQ q(DivisionSemiring $α)).toOption czα := (← trySynthInstanceQ q(CharZero $α)).toOption } theorem cast_pos {n : ℕ} : IsNat (a : R) n → a = n.rawCast + 0 | ⟨e⟩ => by simp [e] theorem cast_zero : IsNat (a : R) (nat_lit 0) → a = 0 | ⟨e⟩ => by simp [e] theorem cast_neg {n : ℕ} {R} [Ring R] {a : R} : IsInt a (.negOfNat n) → a = (Int.negOfNat n).rawCast + 0 | ⟨e⟩ => by simp [e] theorem cast_nnrat {n : ℕ} {d : ℕ} {R} [DivisionSemiring R] {a : R} : IsNNRat a n d → a = NNRat.rawCast n d + 0 | ⟨_, e⟩ => by simp [e, div_eq_mul_inv] theorem cast_rat {n : ℤ} {d : ℕ} {R} [DivisionRing R] {a : R} : IsRat a n d → a = Rat.rawCast n d + 0 | ⟨_, e⟩ => by simp [e, div_eq_mul_inv] /-- Converts a proof by `norm_num` that `e` is a numeral, into a normalization as a monomial: * `e = 0` if `norm_num` returns `IsNat e 0` * `e = Nat.rawCast n + 0` if `norm_num` returns `IsNat e n` * `e = Int.rawCast n + 0` if `norm_num` returns `IsInt e n` * `e = NNRat.rawCast n d + 0` if `norm_num` returns `IsNNRat e n d` * `e = Rat.rawCast n d + 0` if `norm_num` returns `IsRat e n d` -/ def evalCast {α : Q(Type u)} (sα : Q(CommSemiring $α)) {e : Q($α)} : NormNum.Result e → Option (Result (ExSum sα) e) | .isNat _ (.lit (.natVal 0)) p => do assumeInstancesCommute pure ⟨_, .zero, q(cast_zero $p)⟩ | .isNat _ lit p => do assumeInstancesCommute pure ⟨_, (ExProd.mkNat sα lit.natLit!).2.toSum, (q(cast_pos $p) :)⟩ | .isNegNat rα lit p => pure ⟨_, (ExProd.mkNegNat _ rα lit.natLit!).2.toSum, (q(cast_neg $p) : Expr)⟩ | .isNNRat dsα q n d p => pure ⟨_, (ExProd.mkNNRat sα dsα q n d q(IsNNRat.den_nz $p)).2.toSum, (q(cast_nnrat $p) : Expr)⟩ | .isNegNNRat dα q n d p => pure ⟨_, (ExProd.mkNegNNRat sα dα q n d q(IsRat.den_nz $p)).2.toSum, (q(cast_rat $p) : Expr)⟩ | _ => none theorem toProd_pf (p : (a : R) = a') : a = a' ^ (nat_lit 1).rawCast * (nat_lit 1).rawCast := by simp [*] theorem atom_pf (a : R) : a = a ^ (nat_lit 1).rawCast * (nat_lit 1).rawCast + 0 := by simp theorem atom_pf' (p : (a : R) = a') : a = a' ^ (nat_lit 1).rawCast * (nat_lit 1).rawCast + 0 := by simp [*] /-- Evaluates an atom, an expression where `ring` can find no additional structure. * `a = a ^ 1 * 1 + 0` -/ def evalAtom (e : Q($α)) : AtomM (Result (ExSum sα) e) := do let r ← (← read).evalAtom e have e' : Q($α) := r.expr let (i, ⟨a', _⟩) ← addAtomQ e' let ve' := (ExBase.atom i (e := a')).toProd (ExProd.mkNat sℕ 1).2 |>.toSum pure ⟨_, ve', match r.proof? with | none => (q(atom_pf $e) : Expr) | some (p : Q($e = $a')) => (q(atom_pf' $p) : Expr)⟩ theorem inv_mul {R} [DivisionSemiring R] {a₁ a₂ a₃ b₁ b₃ c} (_ : (a₁⁻¹ : R) = b₁) (_ : (a₃⁻¹ : R) = b₃) (_ : b₃ * (b₁ ^ a₂ * (nat_lit 1).rawCast) = c) : (a₁ ^ a₂ * a₃ : R)⁻¹ = c := by subst_vars; simp nonrec theorem inv_zero {R} [DivisionSemiring R] : (0 : R)⁻¹ = 0 := inv_zero theorem inv_single {R} [DivisionSemiring R] {a b : R} (_ : (a : R)⁻¹ = b) : (a + 0)⁻¹ = b + 0 := by simp [*] theorem inv_add {a₁ a₂ : ℕ} (_ : ((a₁ : ℕ) : R) = b₁) (_ : ((a₂ : ℕ) : R) = b₂) : ((a₁ + a₂ : ℕ) : R) = b₁ + b₂ := by subst_vars; simp section variable (dsα : Q(DivisionSemiring $α)) /-- Applies `⁻¹` to a polynomial to get an atom. -/ def evalInvAtom (a : Q($α)) : AtomM (Result (ExBase sα) q($a⁻¹)) := do let (i, ⟨b', _⟩) ← addAtomQ q($a⁻¹) pure ⟨b', ExBase.atom i, q(Eq.refl $b')⟩ /-- Inverts a polynomial `va` to get a normalized result polynomial. * `c⁻¹ = (c⁻¹)` if `c` is a constant * `(a ^ b * c)⁻¹ = a⁻¹ ^ b * c⁻¹` -/ def ExProd.evalInv {a : Q($α)} (czα : Option Q(CharZero $α)) (va : ExProd sα a) : AtomM (Result (ExProd sα) q($a⁻¹)) := do Lean.Core.checkSystem decl_name%.toString match va with | .const c hc => let ra := Result.ofRawRat c a hc match ← (Lean.observing? <| ra.inv dsα czα :) with | some rc => let ⟨zc, hc⟩ := rc.toRatNZ.get! let ⟨c, pc⟩ := rc.toRawEq pure ⟨c, .const zc hc, pc⟩ | none => let ⟨_, vc, pc⟩ ← evalInvAtom sα dsα a pure ⟨_, vc.toProd (ExProd.mkNat sℕ 1).2, q(toProd_pf $pc)⟩ | .mul (x := a₁) (e := _a₂) _va₁ va₂ va₃ => do let ⟨_b₁, vb₁, pb₁⟩ ← evalInvAtom sα dsα a₁ let ⟨_b₃, vb₃, pb₃⟩ ← va₃.evalInv czα let ⟨c, vc, (pc : Q($_b₃ * ($_b₁ ^ $_a₂ * Nat.rawCast 1) = $c))⟩ ← evalMulProd sα vb₃ (vb₁.toProd va₂) pure ⟨c, vc, (q(inv_mul $pb₁ $pb₃ $pc) : Expr)⟩ /-- Inverts a polynomial `va` to get a normalized result polynomial. * `0⁻¹ = 0` * `a⁻¹ = (a⁻¹)` if `a` is a nontrivial sum -/ def ExSum.evalInv {a : Q($α)} (czα : Option Q(CharZero $α)) (va : ExSum sα a) : AtomM (Result (ExSum sα) q($a⁻¹)) := match va with | ExSum.zero => pure ⟨_, .zero, (q(inv_zero (R := $α)) : Expr)⟩ | ExSum.add va ExSum.zero => do let ⟨_, vb, pb⟩ ← va.evalInv sα dsα czα pure ⟨_, vb.toSum, (q(inv_single $pb) : Expr)⟩ | va => do let ⟨_, vb, pb⟩ ← evalInvAtom sα dsα a pure ⟨_, vb.toProd (ExProd.mkNat sℕ 1).2 |>.toSum, q(atom_pf' $pb)⟩ end theorem div_pf {R} [DivisionSemiring R] {a b c d : R} (_ : b⁻¹ = c) (_ : a * c = d) : a / b = d := by subst_vars; simp [div_eq_mul_inv] /-- Divides two polynomials `va, vb` to get a normalized result polynomial. * `a / b = a * b⁻¹` -/ def evalDiv {a b : Q($α)} (rα : Q(DivisionSemiring $α)) (czα : Option Q(CharZero $α)) (va : ExSum sα a) (vb : ExSum sα b) : AtomM (Result (ExSum sα) q($a / $b)) := do let ⟨_c, vc, pc⟩ ← vb.evalInv sα rα czα let ⟨d, vd, (pd : Q($a * $_c = $d))⟩ ← evalMul sα va vc pure ⟨d, vd, q(div_pf $pc $pd)⟩ theorem add_congr (_ : a = a') (_ : b = b') (_ : a' + b' = c) : (a + b : R) = c := by subst_vars; rfl theorem mul_congr (_ : a = a') (_ : b = b') (_ : a' * b' = c) : (a * b : R) = c := by subst_vars; rfl theorem nsmul_congr {a a' : ℕ} (_ : (a : ℕ) = a') (_ : b = b') (_ : a' • b' = c) : (a • (b : R)) = c := by subst_vars; rfl theorem zsmul_congr {R} [Ring R] {b b' c : R} {a a' : ℤ} (_ : (a : ℤ) = a') (_ : b = b') (_ : a' • b' = c) : (a • (b : R)) = c := by subst_vars; rfl theorem pow_congr {b b' : ℕ} (_ : a = a') (_ : b = b') (_ : a' ^ b' = c) : (a ^ b : R) = c := by subst_vars; rfl theorem neg_congr {R} [Ring R] {a a' b : R} (_ : a = a') (_ : -a' = b) : (-a : R) = b := by subst_vars; rfl theorem sub_congr {R} [Ring R] {a a' b b' c : R} (_ : a = a') (_ : b = b') (_ : a' - b' = c) : (a - b : R) = c := by subst_vars; rfl theorem inv_congr {R} [DivisionSemiring R] {a a' b : R} (_ : a = a') (_ : a'⁻¹ = b) : (a⁻¹ : R) = b := by subst_vars; rfl theorem div_congr {R} [DivisionSemiring R] {a a' b b' c : R} (_ : a = a') (_ : b = b') (_ : a' / b' = c) : (a / b : R) = c := by subst_vars; rfl /-- A precomputed `Cache` for `ℕ`. -/ def Cache.nat : Cache sℕ := { rα := none, dsα := none, czα := some q(inferInstance) } /-- A precomputed `Cache` for `ℤ`. -/ def Cache.int : Cache sℤ := { rα := some q(inferInstance), dsα := none, czα := some q(inferInstance) } /-- Checks whether `e` would be processed by `eval` as a ring expression, or otherwise if it is an atom or something simplifiable via `norm_num`. We use this in `ring_nf` to avoid rewriting atoms unnecessarily. Returns: * `none` if `eval` would process `e` as an algebraic ring expression * `some none` if `eval` would treat `e` as an atom. * `some (some r)` if `eval` would not process `e` as an algebraic ring expression, but `NormNum.derive` can nevertheless simplify `e`, with result `r`. -/ -- Note this is not the same as whether the result of `eval` is an atom. (e.g. consider `x + 0`.) def isAtomOrDerivable {u} {α : Q(Type u)} (sα : Q(CommSemiring $α)) (c : Cache sα) (e : Q($α)) : AtomM (Option (Option (Result (ExSum sα) e))) := do let els := try pure <| some (evalCast sα (← derive e)) catch _ => pure (some none) let .const n _ := (← withReducible <| whnf e).getAppFn | els match n, c.rα, c.dsα with | ``HAdd.hAdd, _, _ | ``Add.add, _, _ | ``HMul.hMul, _, _ | ``Mul.mul, _, _ | ``HSMul.hSMul, _, _ | ``HPow.hPow, _, _ | ``Pow.pow, _, _ | ``Neg.neg, some _, _ | ``HSub.hSub, some _, _ | ``Sub.sub, some _, _ | ``Inv.inv, _, some _ | ``HDiv.hDiv, _, some _ | ``Div.div, _, some _ => pure none | _, _, _ => els /-- Evaluates expression `e` of type `α` into a normalized representation as a polynomial. This is the main driver of `ring`, which calls out to `evalAdd`, `evalMul` etc. -/ partial def eval {u : Lean.Level} {α : Q(Type u)} (sα : Q(CommSemiring $α)) (c : Cache sα) (e : Q($α)) : AtomM (Result (ExSum sα) e) := Lean.withIncRecDepth do let els := do try evalCast sα (← derive e) catch _ => evalAtom sα e let .const n _ := (← withReducible <| whnf e).getAppFn | els match n, c.rα, c.dsα with | ``HAdd.hAdd, _, _ | ``Add.add, _, _ => match e with | ~q($a + $b) => let ⟨_, va, pa⟩ ← eval sα c a let ⟨_, vb, pb⟩ ← eval sα c b let ⟨c, vc, p⟩ ← evalAdd sα va vb pure ⟨c, vc, q(add_congr $pa $pb $p)⟩ | _ => els | ``HMul.hMul, _, _ | ``Mul.mul, _, _ => match e with | ~q($a * $b) => let ⟨_, va, pa⟩ ← eval sα c a let ⟨_, vb, pb⟩ ← eval sα c b let ⟨c, vc, p⟩ ← evalMul sα va vb pure ⟨c, vc, q(mul_congr $pa $pb $p)⟩ | _ => els | ``HSMul.hSMul, rα, _ => match e, rα with | ~q(($a : ℕ) • ($b : «$α»)), _ => let ⟨_, va, pa⟩ ← eval sℕ .nat a let ⟨_, vb, pb⟩ ← eval sα c b let ⟨c, vc, p⟩ ← evalNSMul sα va vb pure ⟨c, vc, q(nsmul_congr $pa $pb $p)⟩ | ~q(@HSMul.hSMul ℤ _ _ $i $a $b), some rα => let b : Q($α) := b let ⟨_, va, pa⟩ ← eval sℤ .int a let ⟨_, vb, pb⟩ ← eval sα c b let ⟨c, vc, p⟩ ← evalZSMul sα rα va vb -- Qq is probably unhappy about `Ring` and `CommSemiring` at the same time. let pf ← mkAppM ``zsmul_congr #[pa, pb, p] pure ⟨c, vc, pf⟩ | _, _ => els | ``HPow.hPow, _, _ | ``Pow.pow, _, _ => match e with | ~q($a ^ $b) => let ⟨_, va, pa⟩ ← eval sα c a let ⟨_, vb, pb⟩ ← eval sℕ .nat b let ⟨c, vc, p⟩ ← evalPow sα va vb pure ⟨c, vc, q(pow_congr $pa $pb $p)⟩ | _ => els | ``Neg.neg, some rα, _ => match e with | ~q(-$a) => let ⟨_, va, pa⟩ ← eval sα c a let ⟨b, vb, p⟩ ← evalNeg sα rα va pure ⟨b, vb, q(neg_congr $pa $p)⟩ | _ => els | ``HSub.hSub, some rα, _ | ``Sub.sub, some rα, _ => match e with | ~q($a - $b) => do let ⟨_, va, pa⟩ ← eval sα c a let ⟨_, vb, pb⟩ ← eval sα c b let ⟨c, vc, p⟩ ← evalSub sα rα va vb pure ⟨c, vc, q(sub_congr $pa $pb $p)⟩ | _ => els | ``Inv.inv, _, some dsα => match e with | ~q($a⁻¹) => let ⟨_, va, pa⟩ ← eval sα c a let ⟨b, vb, p⟩ ← va.evalInv sα dsα c.czα pure ⟨b, vb, q(inv_congr $pa $p)⟩ | _ => els | ``HDiv.hDiv, _, some dsα | ``Div.div, _, some dsα => match e with | ~q($a / $b) => do let ⟨_, va, pa⟩ ← eval sα c a let ⟨_, vb, pb⟩ ← eval sα c b let ⟨c, vc, p⟩ ← evalDiv sα dsα c.czα va vb pure ⟨c, vc, q(div_congr $pa $pb $p)⟩ | _ => els | _, _, _ => els universe u /-- `CSLift α β` is a typeclass used by `ring` for lifting operations from `α` (which is not a commutative semiring) into a commutative semiring `β` by using an injective map `lift : α → β`. -/ class CSLift (α : Type u) (β : outParam (Type u)) where /-- `lift` is the "canonical injection" from `α` to `β` -/ lift : α → β /-- `lift` is an injective function -/ inj : Function.Injective lift /-- `CSLiftVal a b` means that `b = lift a`. This is used by `ring` to construct an expression `b` from the input expression `a`, and then run the usual ring algorithm on `b`. -/ class CSLiftVal {α} {β : outParam (Type u)} [CSLift α β] (a : α) (b : outParam β) : Prop where /-- The output value `b` is equal to the lift of `a`. This can be supplied by the default instance which sets `b := lift a`, but `ring` will treat this as an atom so it is more useful when there are other instances which distribute addition or multiplication. -/ eq : b = CSLift.lift a instance (priority := low) {α β} [CSLift α β] (a : α) : CSLiftVal a (CSLift.lift a) := ⟨rfl⟩ theorem of_lift {α β} [inst : CSLift α β] {a b : α} {a' b' : β} [h1 : CSLiftVal a a'] [h2 : CSLiftVal b b'] (h : a' = b') : a = b := inst.2 <| by rwa [← h1.1, ← h2.1] open Lean Parser.Tactic Elab Command Elab.Tactic theorem of_eq {α} {a b c : α} (_ : (a : α) = c) (_ : b = c) : a = b := by subst_vars; rfl /-- This is a routine which is used to clean up the unsolved subgoal of a failed `ring1` application. It is overridden in `Mathlib/Tactic/Ring/RingNF.lean` to apply the `ring_nf` simp set to the goal. -/ initialize ringCleanupRef : IO.Ref (Expr → MetaM Expr) ← IO.mkRef pure /-- Frontend of `ring1`: attempt to close a goal `g`, assuming it is an equation of semirings. -/ def proveEq (g : MVarId) : AtomM Unit := do let some (α, e₁, e₂) := (← whnfR <|← instantiateMVars <|← g.getType).eq? | throwError "ring failed: not an equality" let .sort u ← whnf (← inferType α) | unreachable! let v ← try u.dec catch _ => throwError "not a type{indentExpr α}" have α : Q(Type v) := α let sα ← try Except.ok <$> synthInstanceQ q(CommSemiring $α) catch e => pure (.error e) have e₁ : Q($α) := e₁; have e₂ : Q($α) := e₂ let eq ← match sα with | .ok sα => ringCore sα e₁ e₂ | .error e => let β ← mkFreshExprMVarQ q(Type v) let e₁' ← mkFreshExprMVarQ q($β) let e₂' ← mkFreshExprMVarQ q($β) let (sβ, (pf : Q($e₁' = $e₂' → $e₁ = $e₂))) ← try let _l ← synthInstanceQ q(CSLift $α $β) let sβ ← synthInstanceQ q(CommSemiring $β) let _ ← synthInstanceQ q(CSLiftVal $e₁ $e₁') let _ ← synthInstanceQ q(CSLiftVal $e₂ $e₂') pure (sβ, q(of_lift (a := $e₁) (b := $e₂))) catch _ => throw e pure q($pf $(← ringCore sβ e₁' e₂')) g.assign eq where /-- The core of `proveEq` takes expressions `e₁ e₂ : α` where `α` is a `CommSemiring`, and returns a proof that they are equal (or fails). -/ ringCore {v : Level} {α : Q(Type v)} (sα : Q(CommSemiring $α)) (e₁ e₂ : Q($α)) : AtomM Q($e₁ = $e₂) := do let c ← mkCache sα profileitM Exception "ring" (← getOptions) do let ⟨a, va, pa⟩ ← eval sα c e₁ let ⟨b, vb, pb⟩ ← eval sα c e₂ unless va.eq vb do let g ← mkFreshExprMVar (← (← ringCleanupRef.get) q($a = $b)) throwError "ring failed, ring expressions not equal\n{g.mvarId!}" let pb : Q($e₂ = $a) := pb return q(of_eq $pa $pb) /-- Tactic for solving equations of *commutative* (semi)rings, allowing variables in the exponent. * This version of `ring` fails if the target is not an equality. * The variant `ring1!` will use a more aggressive reducibility setting to determine equality of atoms. -/ elab (name := ring1) "ring1" tk:"!"? : tactic => liftMetaMAtMain fun g ↦ do AtomM.run (if tk.isSome then .default else .reducible) (proveEq g) @[inherit_doc ring1] macro "ring1!" : tactic => `(tactic| ring1 !) end Ring end Mathlib.Tactic
.lake/packages/mathlib/Mathlib/Tactic/Ring/Compare.lean
import Mathlib.Tactic.Ring.Basic import Mathlib.Tactic.NormNum.Ineq /-! # Automation for proving inequalities in commutative (semi)rings This file provides automation for proving certain kinds of inequalities in commutative semirings: goals of the form `A ≤ B` and `A < B` for which the ring-normal forms of `A` and `B` differ by a nonnegative (resp. positive) constant. For example, `⊢ x + 3 + y < y + x + 4` is in scope because the normal forms of the LHS and RHS are, respectively, `3 + (x + y)` and `4 + (x + y)`, which differ by an additive constant. ## Main declarations * `Mathlib.Tactic.Ring.proveLE`: prove goals of the form `A ≤ B` (subject to the scope constraints described) * `Mathlib.Tactic.Ring.proveLT`: prove goals of the form `A < B` (subject to the scope constraints described) ## Implementation notes The automation is provided in the `MetaM` monad; that is, these functions are not user-facing. It would not be hard to provide user-facing versions (see the test file), but the scope of this automation is rather specialized and might be confusing to users. However, this automation serves as the discharger for the `linear_combination` tactic on inequality goals, so it is available to the user indirectly as the "degenerate" case of that tactic -- that is, by calling `linear_combination` without arguments. -/ namespace Mathlib.Tactic.Ring open Lean Qq Meta /-! Rather than having the metaprograms `Mathlib.Tactic.Ring.evalLE.lean` and `Mathlib.Tactic.Ring.evalLT.lean` perform all type class inference at the point of use, we record in advance, as `abbrev`s, a few type class deductions which will certainly be necessary. They add no new information (they can already be proved by `inferInstance`). This helps in speeding up the metaprograms in this file substantially -- about a 50% reduction in heartbeat count in representative test cases -- since otherwise a substantial fraction of their runtime is devoted to type class inference. -/ section Typeclass /-- `CommSemiring` implies `AddMonoidWithOne`. -/ abbrev amwo_of_cs (α : Type*) [CommSemiring α] : AddMonoidWithOne α := inferInstance /-- `PartialOrder` implies `LE`. -/ abbrev le_of_po (α : Type*) [PartialOrder α] : LE α := inferInstance /-- `PartialOrder` implies `LT`. -/ abbrev lt_of_po (α : Type*) [PartialOrder α] : LT α := inferInstance end Typeclass /-! The lemmas like `add_le_add_right` in the root namespace are stated under minimal type classes, typically just `[AddRightMono α]` or similar. Here we restate these lemmas under stronger type class assumptions (`[OrderedCommSemiring α]` or similar), which helps in speeding up the metaprograms in this file (`Mathlib.Tactic.Ring.proveLT.lean` and `Mathlib.Tactic.Ring.proveLE.lean`) substantially -- about a 50% reduction in heartbeat count in representative test cases -- since otherwise a substantial fraction of their runtime is devoted to type class inference. These metaprograms at least require `CommSemiring`, `LE`/`LT`, and all `CovariantClass`/`ContravariantClass` permutations for addition, and in their main use case (in `linear_combination`) the `Preorder` type class is also required, so it is rather little loss of generality simply to require `OrderedCommSemiring`/`StrictOrderedCommSemiring`. -/ section Lemma theorem add_le_add_right {α : Type*} [CommSemiring α] [PartialOrder α] [IsOrderedRing α] {b c : α} (bc : b ≤ c) (a : α) : b + a ≤ c + a := _root_.add_le_add_right bc a theorem add_le_of_nonpos_left {α : Type*} [CommSemiring α] [PartialOrder α] [IsOrderedRing α] (a : α) {b : α} (h : b ≤ 0) : b + a ≤ a := _root_.add_le_of_nonpos_left h theorem le_add_of_nonneg_left {α : Type*} [CommSemiring α] [PartialOrder α] [IsOrderedRing α] (a : α) {b : α} (h : 0 ≤ b) : a ≤ b + a := _root_.le_add_of_nonneg_left h theorem add_lt_add_right {α : Type*} [CommSemiring α] [PartialOrder α] [IsStrictOrderedRing α] {b c : α} (bc : b < c) (a : α) : b + a < c + a := _root_.add_lt_add_right bc a theorem add_lt_of_neg_left {α : Type*} [CommSemiring α] [PartialOrder α] [IsStrictOrderedRing α] (a : α) {b : α} (h : b < 0) : b + a < a := _root_.add_lt_of_neg_left a h theorem lt_add_of_pos_left {α : Type*} [CommSemiring α] [PartialOrder α] [IsStrictOrderedRing α] (a : α) {b : α} (h : 0 < b) : a < b + a := _root_.lt_add_of_pos_left a h end Lemma /-- Inductive type carrying the two kinds of errors which can arise in the metaprograms `Mathlib.Tactic.Ring.evalLE.lean` and `Mathlib.Tactic.Ring.evalLT.lean`. -/ inductive ExceptType | tooSmall | notComparable export ExceptType (tooSmall notComparable) /-- In a commutative semiring, given `Ring.ExSum` objects `va`, `vb` which differ by a positive (additive) constant, construct a proof of `$a < $b`, where `a` (resp. `b`) is the expression in the semiring to which `va` (resp. `vb`) evaluates. -/ def evalLE {v : Level} {α : Q(Type v)} (ics : Q(CommSemiring $α)) (_ : Q(PartialOrder $α)) (_ : Q(IsOrderedRing $α)) {a b : Q($α)} (va : Ring.ExSum q($ics) a) (vb : Ring.ExSum q($ics) b) : MetaM (Except ExceptType Q($a ≤ $b)) := do let lα : Q(LE $α) := q(le_of_po $α) assumeInstancesCommute let ⟨_, pz⟩ ← NormNum.mkOfNat α q(amwo_of_cs $α) q(nat_lit 0) let rz : NormNum.Result q((0:$α)) := NormNum.Result.isNat q(amwo_of_cs $α) q(nat_lit 0) (q(NormNum.isNat_ofNat $α $pz):) match va, vb with /- `0 ≤ 0` -/ | .zero, .zero => pure <| .ok (q(le_refl (0:$α)):) /- For numerals `ca` and `cb`, `ca + x ≤ cb + x` if `ca ≤ cb` -/ | .add (b := a') (.const (e := xa) ca hypa) va', .add (.const (e := xb) cb hypb) vb' => do unless va'.eq vb' do return .error notComparable let rxa := NormNum.Result.ofRawRat ca xa hypa let rxb := NormNum.Result.ofRawRat cb xb hypb let NormNum.Result.isTrue pf ← NormNum.evalLE.core lα rxa rxb | return .error tooSmall pure <| .ok (q(add_le_add_right (a := $a') $pf):) /- For a numeral `ca ≤ 0`, `ca + x ≤ x` -/ | .add (.const (e := xa) ca hypa) va', _ => do unless va'.eq vb do return .error notComparable let rxa := NormNum.Result.ofRawRat ca xa hypa let NormNum.Result.isTrue pf ← NormNum.evalLE.core lα rxa rz | return .error tooSmall pure <| .ok (q(add_le_of_nonpos_left (a := $b) $pf):) /- For a numeral `0 ≤ cb`, `x ≤ cb + x` -/ | _, .add (.const (e := xb) cb hypb) vb' => do unless va.eq vb' do return .error notComparable let rxb := NormNum.Result.ofRawRat cb xb hypb let NormNum.Result.isTrue pf ← NormNum.evalLE.core lα rz rxb | return .error tooSmall pure <| .ok (q(le_add_of_nonneg_left (a := $a) $pf):) | _, _ => unless va.eq vb do return .error notComparable pure <| .ok (q(le_refl $a):) --[CommSemiring α] [PartialOrder α] [IsStrictOrderedRing α] /-- In a commutative semiring, given `Ring.ExSum` objects `va`, `vb` which differ by a positive (additive) constant, construct a proof of `$a < $b`, where `a` (resp. `b`) is the expression in the semiring to which `va` (resp. `vb`) evaluates. -/ def evalLT {v : Level} {α : Q(Type v)} (ics : Q(CommSemiring $α)) (_ : Q(PartialOrder $α)) (_ : Q(IsStrictOrderedRing $α)) {a b : Q($α)} (va : Ring.ExSum q($ics) a) (vb : Ring.ExSum q($ics) b) : MetaM (Except ExceptType Q($a < $b)) := do let lα : Q(LT $α) := q(lt_of_po $α) assumeInstancesCommute let ⟨_, pz⟩ ← NormNum.mkOfNat α q(amwo_of_cs $α) q(nat_lit 0) let rz : NormNum.Result q((0:$α)) := NormNum.Result.isNat q(amwo_of_cs $α) q(nat_lit 0) (q(NormNum.isNat_ofNat $α $pz):) match va, vb with /- `0 < 0` -/ | .zero, .zero => return .error tooSmall /- For numerals `ca` and `cb`, `ca + x < cb + x` if `ca < cb` -/ | .add (b := a') (.const (e := xa) ca hypa) va', .add (.const (e := xb) cb hypb) vb' => do unless va'.eq vb' do return .error notComparable let rxa := NormNum.Result.ofRawRat ca xa hypa let rxb := NormNum.Result.ofRawRat cb xb hypb let NormNum.Result.isTrue pf ← NormNum.evalLT.core lα rxa rxb | return .error tooSmall pure <| .ok (q(add_lt_add_right $pf $a'):) /- For a numeral `ca < 0`, `ca + x < x` -/ | .add (.const (e := xa) ca hypa) va', _ => do unless va'.eq vb do return .error notComparable let rxa := NormNum.Result.ofRawRat ca xa hypa let NormNum.Result.isTrue pf ← NormNum.evalLT.core lα rxa rz | return .error tooSmall have pf : Q($xa < 0) := pf pure <| .ok (q(add_lt_of_neg_left $b $pf):) /- For a numeral `0 < cb`, `x < cb + x` -/ | _, .add (.const (e := xb) cb hypb) vb' => do unless va.eq vb' do return .error notComparable let rxb := NormNum.Result.ofRawRat cb xb hypb let NormNum.Result.isTrue pf ← NormNum.evalLT.core lα rz rxb | return .error tooSmall pure <| .ok (q(lt_add_of_pos_left $a $pf):) | _, _ => return .error notComparable theorem le_congr {α : Type*} [LE α] {a b c d : α} (h1 : a = b) (h2 : b ≤ c) (h3 : d = c) : a ≤ d := by rwa [h1, h3] theorem lt_congr {α : Type*} [LT α] {a b c d : α} (h1 : a = b) (h2 : b < c) (h3 : d = c) : a < d := by rwa [h1, h3] attribute [local instance] monadLiftOptionMetaM in /-- Prove goals of the form `A ≤ B` in an ordered commutative semiring, if the ring-normal forms of `A` and `B` differ by a nonnegative (additive) constant. -/ def proveLE (g : MVarId) : MetaM Unit := do let some (α, e₁, e₂) := (← whnfR <|← instantiateMVars <|← g.getType).le? | throwError "ring failed: not of the form `A ≤ B`" let .sort u ← whnf (← inferType α) | unreachable! let v ← try u.dec catch _ => throwError "not a type{indentExpr α}" have α : Q(Type v) := α let ics ← synthInstanceQ q(CommSemiring $α) let ipo ← synthInstanceQ q(PartialOrder $α) let sα ← synthInstanceQ q(IsOrderedRing $α) assumeInstancesCommute have e₁ : Q($α) := e₁; have e₂ : Q($α) := e₂ let c ← mkCache q($ics) let (⟨a, va, pa⟩, ⟨b, vb, pb⟩) ← AtomM.run .instances do pure (← eval q($ics) c e₁, ← eval q($ics) c e₂) match ← evalLE ics ipo sα va vb with | .ok p => g.assign q(le_congr $pa $p $pb) | .error e => let g' ← mkFreshExprMVar (← (← ringCleanupRef.get) q($a ≤ $b)) match e with | notComparable => throwError "ring failed, ring expressions not equal up to an additive constant\n{g'.mvarId!}" | tooSmall => throwError "comparison failed, LHS is larger\n{g'.mvarId!}" attribute [local instance] monadLiftOptionMetaM in /-- Prove goals of the form `A < B` in an ordered commutative semiring, if the ring-normal forms of `A` and `B` differ by a positive (additive) constant. -/ def proveLT (g : MVarId) : MetaM Unit := do let some (α, e₁, e₂) := (← whnfR <|← instantiateMVars <|← g.getType).lt? | throwError "ring failed: not of the form `A < B`" let .sort u ← whnf (← inferType α) | unreachable! let v ← try u.dec catch _ => throwError "not a type{indentExpr α}" have α : Q(Type v) := α let ics ← synthInstanceQ q(CommSemiring $α) let ipo ← synthInstanceQ q(PartialOrder $α) let sα ← synthInstanceQ q(IsStrictOrderedRing $α) assumeInstancesCommute have e₁ : Q($α) := e₁; have e₂ : Q($α) := e₂ let c ← mkCache q($ics) let (⟨a, va, pa⟩, ⟨b, vb, pb⟩) ← AtomM.run .instances do pure (← eval q($ics) c e₁, ← eval q($ics) c e₂) match ← evalLT ics ipo sα va vb with | .ok p => g.assign q(lt_congr $pa $p $pb) | .error e => let g' ← mkFreshExprMVar (← (← ringCleanupRef.get) q($a < $b)) match e with | notComparable => throwError "ring failed, ring expressions not equal up to an additive constant\n{g'.mvarId!}" | tooSmall => throwError "comparison failed, LHS is at least as large\n{g'.mvarId!}" end Mathlib.Tactic.Ring
.lake/packages/mathlib/Mathlib/Tactic/Ring/PNat.lean
import Mathlib.Tactic.Ring.Basic import Mathlib.Data.PNat.Basic /-! # Additional instances for `ring` over `PNat` This adds some instances which enable `ring` to work on `PNat` even though it is not a commutative semiring, by lifting to `Nat`. -/ namespace Mathlib.Tactic.Ring instance : CSLift ℕ+ Nat where lift := PNat.val inj := PNat.coe_injective -- FIXME: this `no_index` seems to be in the wrong place, but -- #synth CSLiftVal (3 : ℕ+) _ doesn't work otherwise instance {n} : CSLiftVal (no_index (OfNat.ofNat (n + 1)) : ℕ+) (n + 1) := ⟨rfl⟩ instance {n h} : CSLiftVal (Nat.toPNat n h) n := ⟨rfl⟩ instance {n} : CSLiftVal (Nat.succPNat n) (n + 1) := ⟨rfl⟩ instance {n} : CSLiftVal (Nat.toPNat' n) (n.pred + 1) := ⟨rfl⟩ instance {n k} : CSLiftVal (PNat.divExact n k) (n.div k + 1) := ⟨rfl⟩ instance {n n' k k'} [h1 : CSLiftVal (n : ℕ+) n'] [h2 : CSLiftVal (k : ℕ+) k'] : CSLiftVal (n + k) (n' + k') := ⟨by simp [h1.1, h2.1, CSLift.lift]⟩ instance {n n' k k'} [h1 : CSLiftVal (n : ℕ+) n'] [h2 : CSLiftVal (k : ℕ+) k'] : CSLiftVal (n * k) (n' * k') := ⟨by simp [h1.1, h2.1, CSLift.lift]⟩ instance {n n' k} [h1 : CSLiftVal (n : ℕ+) n'] : CSLiftVal (n ^ k) (n' ^ k) := ⟨by simp [h1.1, CSLift.lift]⟩ end Ring end Mathlib.Tactic
.lake/packages/mathlib/Mathlib/Tactic/Ring/RingNF.lean
import Mathlib.Tactic.Ring.Basic import Mathlib.Tactic.TryThis import Mathlib.Tactic.Conv import Mathlib.Util.AtLocation import Mathlib.Util.AtomM.Recurse import Mathlib.Util.Qq /-! # `ring_nf` tactic A tactic which uses `ring` to rewrite expressions. This can be used non-terminally to normalize ring expressions in the goal such as `⊢ P (x + x + x)` ~> `⊢ P (x * 3)`, as well as being able to prove some equations that `ring` cannot because they involve ring reasoning inside a subterm, such as `sin (x + y) + sin (y + x) = 2 * sin (x + y)`. -/ namespace Mathlib.Tactic open Lean open Qq Meta namespace Ring variable {u : Level} {arg : Q(Type u)} {sα : Q(CommSemiring $arg)} {a : Q($arg)} /-- True if this represents an atomic expression. -/ def ExBase.isAtom : ExBase sα a → Bool | .atom _ => true | _ => false /-- True if this represents an atomic expression. -/ def ExProd.isAtom : ExProd sα a → Bool | .mul va₁ (.const 1 _) (.const 1 _) => va₁.isAtom | _ => false /-- True if this represents an atomic expression. -/ def ExSum.isAtom : ExSum sα a → Bool | .add va₁ va₂ => match va₂ with -- FIXME: this takes a while to compile as one match | .zero => va₁.isAtom | _ => false | _ => false end Ring namespace RingNF open Ring /-- The normalization style for `ring_nf`. -/ inductive RingMode where /-- Sum-of-products form, like `x + x * y * 2 + z ^ 2`. -/ | SOP /-- Raw form: the representation `ring` uses internally. -/ | raw deriving Inhabited, BEq, Repr /-- Configuration for `ring_nf`. -/ structure Config extends AtomM.Recurse.Config where /-- if true, then fail if no progress is made -/ failIfUnchanged := true /-- The normalization style. -/ mode := RingMode.SOP deriving Inhabited, BEq, Repr -- See https://github.com/leanprover/lean4/issues/10295 attribute [nolint unusedArguments] Mathlib.Tactic.RingNF.instReprConfig.repr /-- Function elaborating `RingNF.Config`. -/ declare_config_elab elabConfig Config /-- Evaluates an expression `e` into a normalized representation as a polynomial. This is a variant of `Mathlib.Tactic.Ring.eval`, the main driver of the `ring` tactic. It differs in * operating on `Expr` (input) and `Simp.Result` (output), rather than typed `Qq` versions of these; * throwing an error if the expression `e` is an atom for the `ring` tactic. -/ def evalExpr (e : Expr) : AtomM Simp.Result := do let e ← withReducible <| whnf e guard e.isApp -- all interesting ring expressions are applications let ⟨u, α, e⟩ ← inferTypeQ' e let sα ← synthInstanceQ q(CommSemiring $α) let c ← mkCache sα let ⟨a, _, pa⟩ ← match ← isAtomOrDerivable q($sα) c q($e) with | none => eval sα c e -- `none` indicates that `eval` will find something algebraic. | some none => failure -- No point rewriting atoms | some (some r) => pure r -- Nothing algebraic for `eval` to use, but `norm_num` simplifies. pure { expr := a, proof? := pa } variable {R : Type*} [CommSemiring R] {n d : ℕ} theorem add_assoc_rev (a b c : R) : a + (b + c) = a + b + c := (add_assoc ..).symm theorem mul_assoc_rev (a b c : R) : a * (b * c) = a * b * c := (mul_assoc ..).symm theorem mul_neg {R} [Ring R] (a b : R) : a * -b = -(a * b) := by simp theorem add_neg {R} [Ring R] (a b : R) : a + -b = a - b := (sub_eq_add_neg ..).symm theorem nat_rawCast_0 : (Nat.rawCast 0 : R) = 0 := by simp theorem nat_rawCast_1 : (Nat.rawCast 1 : R) = 1 := by simp theorem nat_rawCast_2 [Nat.AtLeastTwo n] : (Nat.rawCast n : R) = OfNat.ofNat n := rfl theorem int_rawCast_neg {R} [Ring R] : (Int.rawCast (.negOfNat n) : R) = -Nat.rawCast n := by simp theorem nnrat_rawCast {R} [DivisionSemiring R] : (NNRat.rawCast n d : R) = Nat.rawCast n / Nat.rawCast d := by simp theorem rat_rawCast_neg {R} [DivisionRing R] : (Rat.rawCast (.negOfNat n) d : R) = Int.rawCast (.negOfNat n) / Nat.rawCast d := by simp /-- A cleanup routine, which simplifies normalized polynomials to a more human-friendly format. -/ def cleanup (cfg : RingNF.Config) (r : Simp.Result) : MetaM Simp.Result := do match cfg.mode with | .raw => pure r | .SOP => do let thms : SimpTheorems := {} let thms ← [``add_zero, ``add_assoc_rev, ``_root_.mul_one, ``mul_assoc_rev, ``_root_.pow_one, ``mul_neg, ``add_neg].foldlM (·.addConst ·) thms let thms ← [``nat_rawCast_0, ``nat_rawCast_1, ``nat_rawCast_2, ``int_rawCast_neg, ``nnrat_rawCast, ``rat_rawCast_neg].foldlM (·.addConst · (post := false)) thms let ctx ← Simp.mkContext { zetaDelta := cfg.zetaDelta } (simpTheorems := #[thms]) (congrTheorems := ← getSimpCongrTheorems) pure <| ← r.mkEqTrans (← Simp.main r.expr ctx (methods := Lean.Meta.Simp.mkDefaultMethodsCore {})).1 /-- Overrides the default error message in `ring1` to use a prettified version of the goal. -/ initialize ringCleanupRef.set fun e => do return (← cleanup {} { expr := e }).expr open Elab.Tactic Parser.Tactic /-- Simplification tactic for expressions in the language of commutative (semi)rings, which rewrites all ring expressions into a normal form. * `ring_nf!` will use a more aggressive reducibility setting to identify atoms. * `ring_nf (config := cfg)` allows for additional configuration: * `red`: the reducibility setting (overridden by `!`) * `zetaDelta`: if true, local let variables can be unfolded (overridden by `!`) * `recursive`: if true, `ring_nf` will also recurse into atoms * `ring_nf` works as both a tactic and a conv tactic. In tactic mode, `ring_nf at h` can be used to rewrite in a hypothesis. This can be used non-terminally to normalize ring expressions in the goal such as `⊢ P (x + x + x)` ~> `⊢ P (x * 3)`, as well as being able to prove some equations that `ring` cannot because they involve ring reasoning inside a subterm, such as `sin (x + y) + sin (y + x) = 2 * sin (x + y)`. -/ elab (name := ringNF) "ring_nf" tk:"!"? cfg:optConfig loc:(location)? : tactic => do let mut cfg ← elabConfig cfg if tk.isSome then cfg := { cfg with red := .default, zetaDelta := true } let loc := (loc.map expandLocation).getD (.targets #[] true) let s ← IO.mkRef {} let m := AtomM.recurse s cfg.toConfig evalExpr (cleanup cfg) transformAtLocation (m ·) "ring_nf" loc cfg.failIfUnchanged false @[inherit_doc ringNF] macro "ring_nf!" cfg:optConfig loc:(location)? : tactic => `(tactic| ring_nf ! $cfg:optConfig $(loc)?) @[inherit_doc ringNF] syntax (name := ringNFConv) "ring_nf" "!"? optConfig : conv /-- Tactic for solving equations of *commutative* (semi)rings, allowing variables in the exponent. * This version of `ring1` uses `ring_nf` to simplify in atoms. * The variant `ring1_nf!` will use a more aggressive reducibility setting to determine equality of atoms. -/ elab (name := ring1NF) "ring1_nf" tk:"!"? cfg:optConfig : tactic => do let mut cfg ← elabConfig cfg if tk.isSome then cfg := { cfg with red := .default, zetaDelta := true } let s ← IO.mkRef {} liftMetaMAtMain fun g ↦ AtomM.RecurseM.run s cfg.toConfig evalExpr (cleanup cfg) <| proveEq g @[inherit_doc ring1NF] macro "ring1_nf!" cfg:optConfig : tactic => `(tactic| ring1_nf ! $cfg:optConfig) /-- Elaborator for the `ring_nf` tactic. -/ @[tactic ringNFConv] def elabRingNFConv : Tactic := fun stx ↦ match stx with | `(conv| ring_nf $[!%$tk]? $cfg:optConfig) => withMainContext do let mut cfg ← elabConfig cfg if tk.isSome then cfg := { cfg with red := .default, zetaDelta := true } let s ← IO.mkRef {} Conv.applySimpResult (← AtomM.recurse s cfg.toConfig evalExpr (cleanup cfg) (← instantiateMVars (← Conv.getLhs))) | _ => Elab.throwUnsupportedSyntax @[inherit_doc ringNF] macro "ring_nf!" cfg:optConfig : conv => `(conv| ring_nf ! $cfg:optConfig) /-- Tactic for evaluating expressions in *commutative* (semi)rings, allowing for variables in the exponent. If the goal is not appropriate for `ring` (e.g. not an equality) `ring_nf` will be suggested. * `ring!` will use a more aggressive reducibility setting to determine equality of atoms. * `ring1` fails if the target is not an equality. For example: ``` example (n : ℕ) (m : ℤ) : 2^(n+1) * m = 2 * 2^n * m := by ring example (a b : ℤ) (n : ℕ) : (a + b)^(n + 2) = (a^2 + b^2 + a * b + b * a) * (a + b)^n := by ring example (x y : ℕ) : x + id y = y + id x := by ring! example (x : ℕ) (h : x * 2 > 5): x + x > 5 := by ring; assumption -- suggests ring_nf ``` -/ macro (name := ring) "ring" : tactic => `(tactic| first | ring1 | try_this ring_nf "\n\nThe `ring` tactic failed to close the goal. Use `ring_nf` to obtain a normal form. \nNote that `ring` works primarily in *commutative* rings. \ If you have a noncommutative ring, abelian group or module, consider using \ `noncomm_ring`, `abel` or `module` instead.") @[inherit_doc ring] macro "ring!" : tactic => `(tactic| first | ring1! | try_this ring_nf! "\n\nThe `ring!` tactic failed to close the goal. Use `ring_nf!` to obtain a normal form. \nNote that `ring!` works primarily in *commutative* rings. \ If you have a noncommutative ring, abelian group or module, consider using \ `noncomm_ring`, `abel` or `module` instead.") /-- The tactic `ring` evaluates expressions in *commutative* (semi)rings. This is the conv tactic version, which rewrites a target which is a ring equality to `True`. See also the `ring` tactic. -/ macro (name := ringConv) "ring" : conv => `(conv| first | discharge => ring1 | try_this ring_nf "\n\nThe `ring` tactic failed to close the goal. Use `ring_nf` to obtain a normal form. \nNote that `ring` works primarily in *commutative* rings. \ If you have a noncommutative ring, abelian group or module, consider using \ `noncomm_ring`, `abel` or `module` instead.") @[inherit_doc ringConv] macro "ring!" : conv => `(conv| first | discharge => ring1! | try_this ring_nf! "\n\nThe `ring!` tactic failed to close the goal. Use `ring_nf!` to obtain a normal form. \nNote that `ring!` works primarily in *commutative* rings. \ If you have a noncommutative ring, abelian group or module, consider using \ `noncomm_ring`, `abel` or `module` instead.") end RingNF end Mathlib.Tactic /-! We register `ring` with the `hint` tactic. -/ register_hint 1000 ring
.lake/packages/mathlib/Mathlib/Tactic/Explode/Pretty.lean
import Lean.Meta.Basic import Mathlib.Tactic.Explode.Datatypes /-! # Explode command: pretty This file contains UI code to render the Fitch table. -/ open Lean namespace Mathlib.Explode /-- Given a list of `MessageData`s, make them of equal length. We need this in order to form columns in our Fitch table. ```lean padRight ["hi", "hello"] = ["hi ", "hello"] ``` -/ def padRight (mds : List MessageData) : MetaM (List MessageData) := do -- 1. Find the max length of the word in a list let mut maxLength := 0 for md in mds do maxLength := max maxLength (← md.toString).length -- 2. Pad all words in a list with " " let pad (md : MessageData) : MetaM MessageData := do let padWidth : Nat := maxLength - (← md.toString).length return md ++ "".pushn ' ' padWidth mds.mapM pad /-- Render a particular row of the Fitch table. -/ def rowToMessageData : List MessageData → List MessageData → List MessageData → List Entry → MetaM MessageData | line :: lines, dep :: deps, thm :: thms, en :: es => do let pipes := String.join (List.replicate en.depth "│ ") let pipes := match en.status with | Status.sintro => s!"├ " | Status.intro => s!"│ {pipes}┌ " | Status.cintro => s!"│ {pipes}├ " | Status.lam => s!"│ {pipes}" | Status.reg => s!"│ {pipes}" let row := m!"{line}│{dep}│ {thm} {pipes}{en.type}\n" return (← rowToMessageData lines deps thms es).compose row | _, _, _, _ => return MessageData.nil /-- Given all `Entries`, return the entire Fitch table. -/ def entriesToMessageData (entries : Entries) : MetaM MessageData := do -- ['1', '2', '3'] let paddedLines ← padRight <| entries.l.map fun entry => m!"{entry.line!}" -- [' ', '1,2', '1 '] let paddedDeps ← padRight <| entries.l.map fun entry => String.intercalate "," <| entry.deps.map (fun dep => (dep.map toString).getD "_") -- ['p ', 'hP ', '∀I '] let paddedThms ← padRight <| entries.l.map (·.thm) rowToMessageData paddedLines paddedDeps paddedThms entries.l end Explode end Mathlib
.lake/packages/mathlib/Mathlib/Tactic/Explode/Datatypes.lean
import Mathlib.Init import Lean.Util.Trace /-! # Explode command: datatypes This file contains datatypes used by the `#explode` command and their associated methods. -/ open Lean namespace Mathlib.Explode initialize registerTraceClass `explode /-- How to display pipes (`│`) for this entry in the Fitch table . -/ inductive Status where /-- `├` Start intro (top-level) -/ | sintro : Status /-- `Entry.depth` * `│` + `┌` Normal intro -/ | intro : Status /-- `Entry.depth` * `│` + `├` Continuation intro -/ | cintro : Status /-- `Entry.depth` * `│` -/ | lam : Status /-- `Entry.depth` * `│` -/ | reg : Status deriving Inhabited /-- The row in the Fitch table. -/ structure Entry where /-- A type of this expression as a `MessageData`. Make sure to use `addMessageContext`. -/ type : MessageData /-- The row number, starting from `0`. This is set by `Entries.add`. -/ line : Option Nat := none /-- How many `if`s (aka lambda-abstractions) this row is nested under. -/ depth : Nat /-- What `Status` this entry has - this only affects how `│`s are displayed. -/ status : Status /-- What to display in the "theorem applied" column. Make sure to use `addMessageContext` if needed. -/ thm : MessageData /-- Which other lines (aka rows) this row depends on. `none` means that the dependency has been filtered out of the table. -/ deps : List (Option Nat) /-- Whether or not to use this in future deps lists. Generally controlled by the `select` function passed to `explodeCore`. Exception: `∀I` may ignore this for introduced hypotheses. -/ useAsDep : Bool /-- Get the `line` for an `Entry` that has been added to the `Entries` structure. -/ def Entry.line! (entry : Entry) : Nat := entry.line.get! /-- Instead of simply keeping a list of entries (`List Entry`), we create a datatype `Entries` that allows us to compare expressions faster. -/ structure Entries : Type where /-- Allows us to compare `Expr`s fast. -/ s : ExprMap Entry /-- Simple list of `Expr`s. -/ l : List Entry deriving Inhabited /-- Find a row where `Entry.expr` == `e`. -/ def Entries.find? (es : Entries) (e : Expr) : Option Entry := es.s[e]? /-- Length of our entries. -/ def Entries.size (es : Entries) : Nat := es.s.size /-- Add the entry unless it already exists. Sets the `line` field to the next available value. -/ def Entries.add (entries : Entries) (expr : Expr) (entry : Entry) : Entry × Entries := if let some entry' := entries.find? expr then (entry', entries) else let entry := { entry with line := entries.size } (entry, ⟨entries.s.insert expr entry, entry :: entries.l⟩) /-- Add a pre-existing entry to the `ExprMap` for an additional expression. This is used by `let` bindings where `expr` is an fvar. -/ def Entries.addSynonym (entries : Entries) (expr : Expr) (entry : Entry) : Entries := ⟨entries.s.insert expr entry, entries.l⟩ end Explode end Mathlib
.lake/packages/mathlib/Mathlib/Tactic/Positivity/Core.lean
import Mathlib.Tactic.NormNum.Core import Mathlib.Tactic.HaveI import Mathlib.Algebra.Order.Invertible import Mathlib.Algebra.Order.Ring.Cast import Mathlib.Control.Basic import Mathlib.Data.Nat.Cast.Basic import Qq /-! ## `positivity` core functionality This file sets up the `positivity` tactic and the `@[positivity]` attribute, which allow for plugging in new positivity functionality around a positivity-based driver. The actual behavior is in `@[positivity]`-tagged definitions in `Tactic.Positivity.Basic` and elsewhere. -/ open Lean open Lean.Meta Qq Lean.Elab Term /-- Attribute for identifying `positivity` extensions. -/ syntax (name := positivity) "positivity " term,+ : attr lemma ne_of_ne_of_eq' {α : Sort*} {a c b : α} (hab : (a : α) ≠ c) (hbc : a = b) : b ≠ c := hbc ▸ hab namespace Mathlib.Meta.Positivity variable {u : Level} {α : Q(Type u)} (zα : Q(Zero $α)) (pα : Q(PartialOrder $α)) /-- The result of `positivity` running on an expression `e` of type `α`. -/ inductive Strictness (e : Q($α)) where | positive (pf : Q(0 < $e)) | nonnegative (pf : Q(0 ≤ $e)) | nonzero (pf : Q($e ≠ 0)) | none deriving Repr /-- Gives a generic description of the `positivity` result. -/ def Strictness.toString {e : Q($α)} : Strictness zα pα e → String | positive _ => "positive" | nonnegative _ => "nonnegative" | nonzero _ => "nonzero" | none => "none" /-- Extract a proof that `e` is positive, if possible, from `Strictness` information about `e`. -/ def Strictness.toPositive {e} : Strictness zα pα e → Option Q(0 < $e) | .positive pf => some pf | _ => .none /-- Extract a proof that `e` is nonnegative, if possible, from `Strictness` information about `e`. -/ def Strictness.toNonneg {e} : Strictness zα pα e → Option Q(0 ≤ $e) | .positive pf => some q(le_of_lt $pf) | .nonnegative pf => some pf | _ => .none /-- Extract a proof that `e` is nonzero, if possible, from `Strictness` information about `e`. -/ def Strictness.toNonzero {e} : Strictness zα pα e → Option Q($e ≠ 0) | .positive pf => some q(ne_of_gt $pf) | .nonzero pf => some pf | _ => .none /-- An extension for `positivity`. -/ structure PositivityExt where /-- Attempts to prove an expression `e : α` is `>0`, `≥0`, or `≠0`. -/ eval {u : Level} {α : Q(Type u)} (zα : Q(Zero $α)) (pα : Q(PartialOrder $α)) (e : Q($α)) : MetaM (Strictness zα pα e) /-- Read a `positivity` extension from a declaration of the right type. -/ def mkPositivityExt (n : Name) : ImportM PositivityExt := do let { env, opts, .. } ← read IO.ofExcept <| unsafe env.evalConstCheck PositivityExt opts ``PositivityExt n /-- Each `positivity` extension is labelled with a collection of patterns which determine the expressions to which it should be applied. -/ abbrev Entry := Array (Array DiscrTree.Key) × Name /-- Environment extensions for `positivity` declarations -/ initialize positivityExt : PersistentEnvExtension Entry (Entry × PositivityExt) (List Entry × DiscrTree PositivityExt) ← -- we only need this to deduplicate entries in the DiscrTree have : BEq PositivityExt := ⟨fun _ _ => false⟩ let insert kss v dt := kss.foldl (fun dt ks => dt.insertCore ks v) dt registerPersistentEnvExtension { mkInitial := pure ([], {}) addImportedFn := fun s => do let dt ← s.foldlM (init := {}) fun dt s => s.foldlM (init := dt) fun dt (kss, n) => do pure (insert kss (← mkPositivityExt n) dt) pure ([], dt) addEntryFn := fun (entries, s) ((kss, n), ext) => ((kss, n) :: entries, insert kss ext s) exportEntriesFn := fun s => s.1.reverse.toArray } initialize registerBuiltinAttribute { name := `positivity descr := "adds a positivity extension" applicationTime := .afterCompilation add := fun declName stx kind => match stx with | `(attr| positivity $es,*) => do unless kind == AttributeKind.global do throwError "invalid attribute 'positivity', must be global" let env ← getEnv unless (env.getModuleIdxFor? declName).isNone do throwError "invalid attribute 'positivity', declaration is in an imported module" if (IR.getSorryDep env declName).isSome then return -- ignore in progress definitions let ext ← mkPositivityExt declName let keys ← MetaM.run' <| es.getElems.mapM fun stx => do let e ← TermElabM.run' <| withSaveInfoContext <| withAutoBoundImplicit <| withReader ({ · with ignoreTCFailures := true }) do let e ← elabTerm stx none let (_, _, e) ← lambdaMetaTelescope (← mkLambdaFVars (← getLCtx).getFVars e) return e DiscrTree.mkPath e setEnv <| positivityExt.addEntry env ((keys, declName), ext) | _ => throwUnsupportedSyntax } variable {A : Type*} {e : A} lemma pos_of_isNat {n : ℕ} [Semiring A] [PartialOrder A] [IsOrderedRing A] [Nontrivial A] (h : NormNum.IsNat e n) (w : Nat.ble 1 n = true) : 0 < (e : A) := by rw [NormNum.IsNat.to_eq h rfl] apply Nat.cast_pos.2 simpa using w lemma pos_of_isNat' {n : ℕ} [AddMonoidWithOne A] [PartialOrder A] [AddLeftMono A] [ZeroLEOneClass A] [h'' : NeZero (1 : A)] (h : NormNum.IsNat e n) (w : Nat.ble 1 n = true) : 0 < (e : A) := by rw [NormNum.IsNat.to_eq h rfl] apply Nat.cast_pos'.2 simpa using w lemma nonneg_of_isNat {n : ℕ} [Semiring A] [PartialOrder A] [IsOrderedRing A] (h : NormNum.IsNat e n) : 0 ≤ (e : A) := by rw [NormNum.IsNat.to_eq h rfl] exact Nat.cast_nonneg n lemma nonneg_of_isNat' {n : ℕ} [AddMonoidWithOne A] [PartialOrder A] [AddLeftMono A] [ZeroLEOneClass A] (h : NormNum.IsNat e n) : 0 ≤ (e : A) := by rw [NormNum.IsNat.to_eq h rfl] exact Nat.cast_nonneg' n lemma nz_of_isNegNat {n : ℕ} [Ring A] [PartialOrder A] [IsStrictOrderedRing A] (h : NormNum.IsInt e (.negOfNat n)) (w : Nat.ble 1 n = true) : (e : A) ≠ 0 := by rw [NormNum.IsInt.neg_to_eq h rfl] simp only [ne_eq, neg_eq_zero] apply ne_of_gt simpa using w lemma pos_of_isNNRat {n d : ℕ} [Semiring A] [LinearOrder A] [IsStrictOrderedRing A] : (NormNum.IsNNRat e n d) → (decide (0 < n)) → ((0 : A) < (e : A)) | ⟨inv, eq⟩, h => by have pos_invOf_d : (0 < ⅟ (d : A)) := pos_invOf_of_invertible_cast d have pos_n : (0 < (n : A)) := Nat.cast_pos (n := n) |>.2 (of_decide_eq_true h) rw [eq] exact mul_pos pos_n pos_invOf_d lemma pos_of_isRat {n : ℤ} {d : ℕ} [Ring A] [LinearOrder A] [IsStrictOrderedRing A] : (NormNum.IsRat e n d) → (decide (0 < n)) → ((0 : A) < (e : A)) | ⟨inv, eq⟩, h => by have pos_invOf_d : (0 < ⅟(d : A)) := pos_invOf_of_invertible_cast d have pos_n : (0 < (n : A)) := Int.cast_pos (n := n) |>.2 (of_decide_eq_true h) rw [eq] exact mul_pos pos_n pos_invOf_d lemma nonneg_of_isNNRat {n d : ℕ} [Semiring A] [LinearOrder A] : (NormNum.IsNNRat e n d) → (decide (n = 0)) → (0 ≤ (e : A)) | ⟨inv, eq⟩, h => by rw [eq, of_decide_eq_true h]; simp lemma nonneg_of_isRat {n : ℤ} {d : ℕ} [Ring A] [LinearOrder A] : (NormNum.IsRat e n d) → (decide (n = 0)) → (0 ≤ (e : A)) | ⟨inv, eq⟩, h => by rw [eq, of_decide_eq_true h]; simp lemma nz_of_isRat {n : ℤ} {d : ℕ} [Ring A] [LinearOrder A] [IsStrictOrderedRing A] : (NormNum.IsRat e n d) → (decide (n < 0)) → ((e : A) ≠ 0) | ⟨inv, eq⟩, h => by have pos_invOf_d : (0 < ⅟(d : A)) := pos_invOf_of_invertible_cast d have neg_n : ((n : A) < 0) := Int.cast_lt_zero (n := n) |>.2 (of_decide_eq_true h) have neg := mul_neg_of_neg_of_pos neg_n pos_invOf_d rw [eq] exact ne_iff_lt_or_gt.2 (Or.inl neg) variable {zα pα} in /-- Converts a `MetaM Strictness` which can fail into one that never fails and returns `.none` instead. -/ def catchNone {e : Q($α)} (t : MetaM (Strictness zα pα e)) : MetaM (Strictness zα pα e) := try t catch e => trace[Tactic.positivity.failure] "{e.toMessageData}" pure .none variable {zα pα} in /-- Converts a `MetaM Strictness` which can return `.none` into one which never returns `.none` but fails instead. -/ def throwNone {m : Type → Type*} {e : Q($α)} [Monad m] [Alternative m] (t : m (Strictness zα pα e)) : m (Strictness zα pα e) := do match ← t with | .none => failure | r => pure r /-- Attempts to prove a `Strictness` result when `e` evaluates to a literal number. -/ def normNumPositivity (e : Q($α)) : MetaM (Strictness zα pα e) := catchNone do match ← NormNum.derive e with | .isBool .. => failure | .isNat _ lit p => if 0 < lit.natLit! then -- NB. The `try` branch is actually a special case of the `catch` branch, -- hence is not strictly necessary. However, this makes a small but measurable performance -- difference, as synthesising the `try` classes is a bit faster. try let _a ← synthInstanceQ q(Semiring $α) let _a ← synthInstanceQ q(PartialOrder $α) let _a ← synthInstanceQ q(IsOrderedRing $α) let _a ← synthInstanceQ q(Nontrivial $α) assumeInstancesCommute have p : Q(NormNum.IsNat $e $lit) := p haveI' p' : Nat.ble 1 $lit =Q true := ⟨⟩ pure (.positive q(pos_of_isNat (A := $α) $p $p')) catch e : Exception => trace[Tactic.positivity.failure] "{e.toMessageData}" let _a ← synthInstanceQ q(AddMonoidWithOne $α) let _a ← synthInstanceQ q(PartialOrder $α) let _a ← synthInstanceQ q(AddLeftMono $α) let _a ← synthInstanceQ q(ZeroLEOneClass $α) let _a ← synthInstanceQ q(NeZero (1 : $α)) assumeInstancesCommute have p : Q(NormNum.IsNat $e $lit) := p haveI' p' : Nat.ble 1 $lit =Q true := ⟨⟩ pure (.positive q(pos_of_isNat' (A := $α) $p $p')) else -- NB. The `try` branch is actually a special case of the `catch` branch, -- hence is not strictly necessary. However, this makes a small but measurable performance -- difference, as synthesising the `try` classes is a bit faster. try let _a ← synthInstanceQ q(Semiring $α) let _a ← synthInstanceQ q(PartialOrder $α) let _a ← synthInstanceQ q(IsOrderedRing $α) assumeInstancesCommute have p : Q(NormNum.IsNat $e $lit) := p pure (.nonnegative q(nonneg_of_isNat $p)) catch e : Exception => trace[Tactic.positivity.failure] "{e.toMessageData}" let _a ← synthInstanceQ q(AddMonoidWithOne $α) let _a ← synthInstanceQ q(PartialOrder $α) let _a ← synthInstanceQ q(AddLeftMono $α) let _a ← synthInstanceQ q(ZeroLEOneClass $α) assumeInstancesCommute have p : Q(NormNum.IsNat $e $lit) := p pure (.nonnegative q(nonneg_of_isNat' $p)) | .isNegNat _ lit p => let _a ← synthInstanceQ q(Ring $α) let _a ← synthInstanceQ q(PartialOrder $α) let _a ← synthInstanceQ q(IsStrictOrderedRing $α) assumeInstancesCommute have p : Q(NormNum.IsInt $e (Int.negOfNat $lit)) := p haveI' p' : Nat.ble 1 $lit =Q true := ⟨⟩ pure (.nonzero q(nz_of_isNegNat $p $p')) | .isNNRat _i q n d p => let _a ← synthInstanceQ q(Semiring $α) let _a ← synthInstanceQ q(LinearOrder $α) let _a ← synthInstanceQ q(IsStrictOrderedRing $α) assumeInstancesCommute have p : Q(NormNum.IsNNRat $e $n $d) := p if 0 < q then haveI' w : decide (0 < $n) =Q true := ⟨⟩ pure (.positive q(pos_of_isNNRat $p $w)) else -- should not be reachable, but just in case haveI' w : decide ($n = 0) =Q true := ⟨⟩ pure (.nonnegative q(nonneg_of_isNNRat $p $w)) | .isNegNNRat _i q n d p => let _a ← synthInstanceQ q(Ring $α) let _a ← synthInstanceQ q(LinearOrder $α) let _a ← synthInstanceQ q(IsStrictOrderedRing $α) assumeInstancesCommute have p : Q(NormNum.IsRat $e (.negOfNat $n) $d) := p if q < 0 then haveI' w : decide (Int.negOfNat $n < 0) =Q true := ⟨⟩ pure (.nonzero q(nz_of_isRat $p $w)) else -- should not be reachable, but just in case haveI' w : decide (Int.negOfNat $n = 0) =Q true := ⟨⟩ pure (.nonnegative q(nonneg_of_isRat $p $w)) /-- Attempts to prove that `e ≥ 0` using `zero_le` in a `CanonicallyOrderedAdd` monoid. -/ def positivityCanon (e : Q($α)) : MetaM (Strictness zα pα e) := do let _add ← synthInstanceQ q(AddMonoid $α) let _le ← synthInstanceQ q(PartialOrder $α) let _i ← synthInstanceQ q(CanonicallyOrderedAdd $α) assumeInstancesCommute pure (.nonnegative q(zero_le $e)) /-- A variation on `assumption` when the hypothesis is `lo ≤ e` where `lo` is a numeral. -/ def compareHypLE (lo e : Q($α)) (p₂ : Q($lo ≤ $e)) : MetaM (Strictness zα pα e) := do match ← normNumPositivity zα pα lo with | .positive p₁ => pure (.positive q(lt_of_lt_of_le $p₁ $p₂)) | .nonnegative p₁ => pure (.nonnegative q(le_trans $p₁ $p₂)) | _ => pure .none /-- A variation on `assumption` when the hypothesis is `lo < e` where `lo` is a numeral. -/ def compareHypLT (lo e : Q($α)) (p₂ : Q($lo < $e)) : MetaM (Strictness zα pα e) := do match ← normNumPositivity zα pα lo with | .positive p₁ => pure (.positive q(lt_trans $p₁ $p₂)) | .nonnegative p₁ => pure (.positive q(lt_of_le_of_lt $p₁ $p₂)) | _ => pure .none /-- A variation on `assumption` when the hypothesis is `x = e` where `x` is a numeral. -/ def compareHypEq (e x : Q($α)) (p₂ : Q($x = $e)) : MetaM (Strictness zα pα e) := do match ← normNumPositivity zα pα x with | .positive p₁ => pure (.positive q(lt_of_lt_of_eq $p₁ $p₂)) | .nonnegative p₁ => pure (.nonnegative q(le_of_le_of_eq $p₁ $p₂)) | .nonzero p₁ => pure (.nonzero q(ne_of_ne_of_eq' $p₁ $p₂)) | .none => pure .none initialize registerTraceClass `Tactic.positivity initialize registerTraceClass `Tactic.positivity.failure /-- A variation on `assumption` which checks if the hypothesis `ldecl` is `a [</≤/=] e` where `a` is a numeral. -/ def compareHyp (e : Q($α)) (ldecl : LocalDecl) : MetaM (Strictness zα pα e) := do have e' : Q(Prop) := ldecl.type let p : Q($e') := .fvar ldecl.fvarId match e' with | ~q(@LE.le.{u} $β $_le $lo $hi) => let .defEq (_ : $α =Q $β) ← isDefEqQ α β | return .none let .defEq _ ← isDefEqQ e hi | return .none match lo with | ~q(0) => assertInstancesCommute return .nonnegative q($p) | _ => compareHypLE zα pα lo e p | ~q(@LT.lt.{u} $β $_lt $lo $hi) => let .defEq (_ : $α =Q $β) ← isDefEqQ α β | return .none let .defEq _ ← isDefEqQ e hi | return .none match lo with | ~q(0) => assertInstancesCommute return .positive q($p) | _ => compareHypLT zα pα lo e p | ~q(@Eq.{u+1} $α' $lhs $rhs) => let .defEq (_ : $α =Q $α') ← isDefEqQ α α' | pure .none match ← isDefEqQ e rhs with | .defEq _ => match lhs with | ~q(0) => pure <| .nonnegative q(le_of_eq $p) | _ => compareHypEq zα pα e lhs q($p) | .notDefEq => let .defEq _ ← isDefEqQ e lhs | pure .none match rhs with | ~q(0) => pure <| .nonnegative q(ge_of_eq $p) | _ => compareHypEq zα pα e rhs q(Eq.symm $p) | ~q(@Ne.{u + 1} $α' $lhs $rhs) => let .defEq (_ : $α =Q $α') ← isDefEqQ α α' | pure .none match lhs, rhs with | ~q(0), _ => let .defEq _ ← isDefEqQ e rhs | pure .none pure <| .nonzero q(Ne.symm $p) | _, ~q(0) => let .defEq _ ← isDefEqQ e lhs | pure .none pure <| .nonzero q($p) | _, _ => pure .none | _ => pure .none variable {zα pα} in /-- The main combinator which combines multiple `positivity` results. It assumes `t₁` has already been run for a result, and runs `t₂` and takes the best result. It will skip `t₂` if `t₁` is already a proof of `.positive`, and can also combine `.nonnegative` and `.nonzero` to produce a `.positive` result. -/ def orElse {e : Q($α)} (t₁ : Strictness zα pα e) (t₂ : MetaM (Strictness zα pα e)) : MetaM (Strictness zα pα e) := do match t₁ with | .none => catchNone t₂ | p@(.positive _) => pure p | .nonnegative p₁ => match ← catchNone t₂ with | p@(.positive _) => pure p | .nonzero p₂ => pure (.positive q(lt_of_le_of_ne' $p₁ $p₂)) | _ => pure (.nonnegative p₁) | .nonzero p₁ => match ← catchNone t₂ with | p@(.positive _) => pure p | .nonnegative p₂ => pure (.positive q(lt_of_le_of_ne' $p₂ $p₁)) | _ => pure (.nonzero p₁) /-- Run each registered `positivity` extension on an expression, returning a `NormNum.Result`. -/ def core (e : Q($α)) : MetaM (Strictness zα pα e) := do let mut result := .none trace[Tactic.positivity] "trying to prove positivity of {e}" for ext in ← (positivityExt.getState (← getEnv)).2.getMatch e do try result ← orElse result <| ext.eval zα pα e catch err => trace[Tactic.positivity] "{e} failed: {err.toMessageData}" result ← orElse result <| normNumPositivity zα pα e result ← orElse result <| positivityCanon zα pα e if let .positive _ := result then trace[Tactic.positivity] "{e} => {result.toString}" return result for ldecl in ← getLCtx do if !ldecl.isImplementationDetail then result ← orElse result <| compareHyp zα pα e ldecl trace[Tactic.positivity] "{e} => {result.toString}" throwNone (pure result) private inductive OrderRel : Type | le : OrderRel -- `0 ≤ a` | lt : OrderRel -- `0 < a` | ne : OrderRel -- `a ≠ 0` | ne' : OrderRel -- `0 ≠ a` end Meta.Positivity namespace Meta.Positivity /-- Given an expression `e`, use the core method of the `positivity` tactic to prove it positive, or, failing that, nonnegative; return a Boolean (signalling whether the strict or non-strict inequality was established) together with the proof as an expression. -/ def bestResult (e : Expr) : MetaM (Bool × Expr) := do let ⟨u, α, _⟩ ← inferTypeQ' e let zα ← synthInstanceQ q(Zero $α) let pα ← synthInstanceQ q(PartialOrder $α) match ← try? (Meta.Positivity.core zα pα e) with | some (.positive pf) => pure (true, pf) | some (.nonnegative pf) => pure (false, pf) | _ => throwError "could not establish the nonnegativity of {e}" /-- Given an expression `e`, use the core method of the `positivity` tactic to prove it nonnegative. -/ def proveNonneg (e : Expr) : MetaM Expr := do let (strict, pf) ← bestResult e if strict then mkAppM ``le_of_lt #[pf] else pure pf /-- An auxiliary entry point to the `positivity` tactic. Given a proposition `t` of the form `0 [≤/</≠] e`, attempts to recurse on the structure of `t` to prove it. It returns a proof or fails. -/ def solve (t : Q(Prop)) : MetaM Expr := do let rest {u : Level} (α : Q(Type u)) z e (relDesired : OrderRel) : MetaM Expr := do let zα ← synthInstanceQ q(Zero $α) assumeInstancesCommute let .true ← isDefEq z q(0 : $α) | throwError "not a positivity goal" let pα ← synthInstanceQ q(PartialOrder $α) assumeInstancesCommute let r ← catchNone <| Meta.Positivity.core zα pα e let throw (a b : String) : MetaM Expr := throwError "failed to prove {a}, but it would be possible to prove {b} if desired" let p ← show MetaM Expr from match relDesired, r with | .lt, .positive p | .le, .nonnegative p | .ne, .nonzero p => pure p | .le, .positive p => pure q(le_of_lt $p) | .ne, .positive p => pure q(ne_of_gt $p) | .ne', .positive p => pure q(ne_of_lt $p) | .ne', .nonzero p => pure q(Ne.symm $p) | .lt, .nonnegative _ => throw "strict positivity" "nonnegativity" | .lt, .nonzero _ => throw "strict positivity" "nonzeroness" | .le, .nonzero _ => throw "nonnegativity" "nonzeroness" | .ne, .nonnegative _ | .ne', .nonnegative _ => throw "nonzeroness" "nonnegativity" | _, .none => throwError "failed to prove positivity/nonnegativity/nonzeroness" pure p match t with | ~q(@LE.le $α $_a $z $e) => rest α z e .le | ~q(@LT.lt $α $_a $z $e) => rest α z e .lt | ~q($a ≠ ($b : ($α : Type _))) => let _zα ← synthInstanceQ q(Zero $α) if ← isDefEq b q((0 : $α)) then rest α b a .ne else let .true ← isDefEq a q((0 : $α)) | throwError "not a positivity goal" rest α a b .ne' | _ => throwError "not a positivity goal" /-- The main entry point to the `positivity` tactic. Given a goal `goal` of the form `0 [≤/</≠] e`, attempts to recurse on the structure of `e` to prove the goal. It will either close `goal` or fail. -/ def positivity (goal : MVarId) : MetaM Unit := do let t : Q(Prop) ← withReducible goal.getType' let p ← solve t goal.assign p end Meta.Positivity namespace Tactic.Positivity open Tactic /-- Tactic solving goals of the form `0 ≤ x`, `0 < x` and `x ≠ 0`. The tactic works recursively according to the syntax of the expression `x`, if the atoms composing the expression all have numeric lower bounds which can be proved positive/nonnegative/nonzero by `norm_num`. This tactic either closes the goal or fails. `positivity [t₁, …, tₙ]` first executes `have := t₁; …; have := tₙ` in the current goal, then runs `positivity`. This is useful when `positivity` needs derived premises such as `0 < y` for division/reciprocal, or `0 ≤ x` for real powers. Examples: ``` example {a : ℤ} (ha : 3 < a) : 0 ≤ a ^ 3 + a := by positivity example {a : ℤ} (ha : 1 < a) : 0 < |(3:ℤ) + a| := by positivity example {b : ℤ} : 0 ≤ max (-3) (b ^ 2) := by positivity example {a b c d : ℝ} (hab : 0 < a * b) (hb : 0 ≤ b) (hcd : c < d) : 0 < a ^ c + 1 / (d - c) := by positivity [sub_pos_of_lt hcd, pos_of_mul_pos_left hab hb] ``` -/ syntax (name := positivity) "positivity" (" [" term,* "]")? : tactic elab_rules : tactic | `(tactic| positivity) => liftMetaTactic fun g => do Meta.Positivity.positivity g; pure [] macro_rules | `(tactic| positivity [$h,*]) => `(tactic| · ($[have := $h];*); positivity) end Positivity end Mathlib.Tactic /-! We set up `positivity` as a first-pass discharger for `gcongr` side goals. -/ macro_rules | `(tactic| gcongr_discharger) => `(tactic| positivity) /-! We register `positivity` with the `hint` tactic. -/ register_hint 1000 positivity
.lake/packages/mathlib/Mathlib/Tactic/Positivity/Finset.lean
import Mathlib.Algebra.Order.BigOperators.Group.Finset import Mathlib.Data.Finset.Density import Mathlib.Tactic.NormNum.Basic import Mathlib.Tactic.Positivity.Core /-! # Positivity extensions for finsets This file provides a few `positivity` extensions that cannot be in either the finset files (because they don't know about ordered fields) or in `Tactic.Positivity.Basic` (because it doesn't want to know about finiteness). -/ namespace Mathlib.Meta.Positivity open Qq Lean Meta Finset /-- Extension for `Finset.card`. `#s` is positive if `s` is nonempty. It calls `Mathlib.Meta.proveFinsetNonempty` to attempt proving that the finset is nonempty. -/ @[positivity Finset.card _] def evalFinsetCard : PositivityExt where eval {u α} _ _ e := do match u, α, e with | 0, ~q(ℕ), ~q(Finset.card $s) => let some ps ← proveFinsetNonempty s | return .none assertInstancesCommute return .positive q(Finset.Nonempty.card_pos $ps) | _ => throwError "not Finset.card" /-- Extension for `Fintype.card`. `Fintype.card α` is positive if `α` is nonempty. -/ @[positivity Fintype.card _] def evalFintypeCard : PositivityExt where eval {u α} _ _ e := do match u, α, e with | 0, ~q(ℕ), ~q(@Fintype.card $β $instβ) => let instβno ← synthInstanceQ q(Nonempty $β) assumeInstancesCommute return .positive q(@Fintype.card_pos $β $instβ $instβno) | _ => throwError "not Fintype.card" /-- Extension for `Finset.dens`. `s.dens` is positive if `s` is nonempty. It calls `Mathlib.Meta.proveFinsetNonempty` to attempt proving that the finset is nonempty. -/ @[positivity Finset.dens _] def evalFinsetDens : PositivityExt where eval {u 𝕜} _ _ e := do match u, 𝕜, e with | 0, ~q(ℚ≥0), ~q(@Finset.dens $α $instα $s) => let some ps ← proveFinsetNonempty s | return .none assumeInstancesCommute return .positive q(@Nonempty.dens_pos $α $instα $s $ps) | _, _, _ => throwError "not Finset.dens" attribute [local instance] monadLiftOptionMetaM in /-- The `positivity` extension which proves that `∑ i ∈ s, f i` is nonnegative if `f` is, and positive if each `f i` is and `s` is nonempty. TODO: The following example does not work ``` example (s : Finset ℕ) (f : ℕ → ℤ) (hf : ∀ n, 0 ≤ f n) : 0 ≤ s.sum f := by positivity ``` because `compareHyp` can't look for assumptions behind binders. -/ @[positivity Finset.sum _ _] def evalFinsetSum : PositivityExt where eval {u α} zα pα e := do match e with | ~q(@Finset.sum $ι _ $instα $s $f) => let i : Q($ι) ← mkFreshExprMVarQ q($ι) .syntheticOpaque have body : Q($α) := .betaRev f #[i] let rbody ← core zα pα body let p_pos : Option Q(0 < $e) := ← (do let .positive pbody := rbody | pure none -- Fail if the body is not provably positive let some ps ← proveFinsetNonempty s | pure none let .some pα' ← trySynthInstanceQ q(IsOrderedCancelAddMonoid $α) | pure none assertInstancesCommute let pr : Q(∀ i, 0 < $f i) ← mkLambdaFVars #[i] pbody return some q(@sum_pos $ι $α $instα $pα $pα' $f $s (fun i _ ↦ $pr i) $ps)) -- Try to show that the sum is positive if let some p_pos := p_pos then return .positive p_pos -- Fall back to showing that the sum is nonnegative else let pbody ← rbody.toNonneg let pr : Q(∀ i, 0 ≤ $f i) ← mkLambdaFVars #[i] pbody let pα' ← synthInstanceQ q(AddLeftMono $α) assertInstancesCommute return .nonnegative q(@sum_nonneg $ι $α $instα $pα $f $s $pα' fun i _ ↦ $pr i) | _ => throwError "not Finset.sum" variable {α : Type*} {s : Finset α} example : 0 ≤ #s := by positivity example (hs : s.Nonempty) : 0 < #s := by positivity variable [Fintype α] example : 0 ≤ Fintype.card α := by positivity example : 0 ≤ dens s := by positivity example (hs : s.Nonempty) : 0 < dens s := by positivity example (hs : s.Nonempty) : dens s ≠ 0 := by positivity example [Nonempty α] : 0 < #(univ : Finset α) := by positivity example [Nonempty α] : 0 < Fintype.card α := by positivity example [Nonempty α] : 0 < dens (univ : Finset α) := by positivity example [Nonempty α] : dens (univ : Finset α) ≠ 0 := by positivity example {G : Type*} {A : Finset G} : let f := fun _ : G ↦ 1; (∀ s, f s ^ 2 = 1) → 0 ≤ #A := by intros positivity -- Should succeed despite failing to prove `A` is nonempty. end Mathlib.Meta.Positivity
.lake/packages/mathlib/Mathlib/Tactic/Positivity/Basic.lean
import Mathlib.Algebra.Order.Group.PosPart import Mathlib.Algebra.Order.Ring.Basic import Mathlib.Algebra.Order.Hom.Basic import Mathlib.Data.Int.CharZero import Mathlib.Data.Nat.Factorial.Basic import Mathlib.Data.NNRat.Defs import Mathlib.Data.PNat.Defs import Mathlib.Tactic.Positivity.Core import Qq /-! ## `positivity` core extensions This file sets up the basic `positivity` extensions tagged with the `@[positivity]` attribute. -/ variable {α : Type*} namespace Mathlib.Meta.Positivity open Lean Meta Qq Function section ite variable [Zero α] (p : Prop) [Decidable p] {a b : α} private lemma ite_pos [LT α] (ha : 0 < a) (hb : 0 < b) : 0 < ite p a b := by by_cases p <;> simp [*] private lemma ite_nonneg [LE α] (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ ite p a b := by by_cases p <;> simp [*] private lemma ite_nonneg_of_pos_of_nonneg [Preorder α] (ha : 0 < a) (hb : 0 ≤ b) : 0 ≤ ite p a b := ite_nonneg _ ha.le hb private lemma ite_nonneg_of_nonneg_of_pos [Preorder α] (ha : 0 ≤ a) (hb : 0 < b) : 0 ≤ ite p a b := ite_nonneg _ ha hb.le private lemma ite_ne_zero (ha : a ≠ 0) (hb : b ≠ 0) : ite p a b ≠ 0 := by by_cases p <;> simp [*] private lemma ite_ne_zero_of_pos_of_ne_zero [Preorder α] (ha : 0 < a) (hb : b ≠ 0) : ite p a b ≠ 0 := ite_ne_zero _ ha.ne' hb private lemma ite_ne_zero_of_ne_zero_of_pos [Preorder α] (ha : a ≠ 0) (hb : 0 < b) : ite p a b ≠ 0 := ite_ne_zero _ ha hb.ne' end ite /-- The `positivity` extension which identifies expressions of the form `ite p a b`, such that `positivity` successfully recognises both `a` and `b`. -/ @[positivity ite _ _ _] def evalIte : PositivityExt where eval {u α} zα pα e := do let .app (.app (.app (.app f (p : Q(Prop))) (_ : Q(Decidable $p))) (a : Q($α))) (b : Q($α)) ← withReducible (whnf e) | throwError "not ite" haveI' : $e =Q ite $p $a $b := ⟨⟩ let ra ← core zα pα a; let rb ← core zα pα b guard <|← withDefault <| withNewMCtxDepth <| isDefEq f q(ite (α := $α)) match ra, rb with | .positive pa, .positive pb => pure (.positive q(ite_pos $p $pa $pb)) | .positive pa, .nonnegative pb => let _b ← synthInstanceQ q(Preorder $α) assumeInstancesCommute pure (.nonnegative q(ite_nonneg_of_pos_of_nonneg $p $pa $pb)) | .nonnegative pa, .positive pb => let _b ← synthInstanceQ q(Preorder $α) assumeInstancesCommute pure (.nonnegative q(ite_nonneg_of_nonneg_of_pos $p $pa $pb)) | .nonnegative pa, .nonnegative pb => pure (.nonnegative q(ite_nonneg $p $pa $pb)) | .positive pa, .nonzero pb => let _b ← synthInstanceQ q(Preorder $α) assumeInstancesCommute pure (.nonzero q(ite_ne_zero_of_pos_of_ne_zero $p $pa $pb)) | .nonzero pa, .positive pb => let _b ← synthInstanceQ q(Preorder $α) assumeInstancesCommute pure (.nonzero q(ite_ne_zero_of_ne_zero_of_pos $p $pa $pb)) | .nonzero pa, .nonzero pb => pure (.nonzero q(ite_ne_zero $p $pa $pb)) | _, _ => pure .none section LinearOrder variable {R : Type*} [LinearOrder R] {a b c : R} private lemma le_min_of_lt_of_le (ha : a < b) (hb : a ≤ c) : a ≤ min b c := le_min ha.le hb private lemma le_min_of_le_of_lt (ha : a ≤ b) (hb : a < c) : a ≤ min b c := le_min ha hb.le private lemma min_ne (ha : a ≠ c) (hb : b ≠ c) : min a b ≠ c := by grind private lemma min_ne_of_ne_of_lt (ha : a ≠ c) (hb : c < b) : min a b ≠ c := min_ne ha hb.ne' private lemma min_ne_of_lt_of_ne (ha : c < a) (hb : b ≠ c) : min a b ≠ c := min_ne ha.ne' hb private lemma max_ne (ha : a ≠ c) (hb : b ≠ c) : max a b ≠ c := by grind end LinearOrder /-- The `positivity` extension which identifies expressions of the form `min a b`, such that `positivity` successfully recognises both `a` and `b`. -/ @[positivity min _ _] def evalMin : PositivityExt where eval {u α} zα pα e := do let .app (.app (f : Q($α → $α → $α)) (a : Q($α))) (b : Q($α)) ← withReducible (whnf e) | throwError "not min" let _e_eq : $e =Q $f $a $b := ⟨⟩ let _a ← synthInstanceQ q(LinearOrder $α) assumeInstancesCommute let ⟨_f_eq⟩ ← withDefault <| withNewMCtxDepth <| assertDefEqQ q($f) q(min) match ← core zα pα a, ← core zα pα b with | .positive pa, .positive pb => pure (.positive q(lt_min $pa $pb)) | .positive pa, .nonnegative pb => pure (.nonnegative q(le_min_of_lt_of_le $pa $pb)) | .nonnegative pa, .positive pb => pure (.nonnegative q(le_min_of_le_of_lt $pa $pb)) | .nonnegative pa, .nonnegative pb => pure (.nonnegative q(le_min $pa $pb)) | .positive pa, .nonzero pb => pure (.nonzero q(min_ne_of_lt_of_ne $pa $pb)) | .nonzero pa, .positive pb => pure (.nonzero q(min_ne_of_ne_of_lt $pa $pb)) | .nonzero pa, .nonzero pb => pure (.nonzero q(min_ne $pa $pb)) | _, _ => pure .none /-- Extension for the `max` operator. The `max` of two numbers is nonnegative if at least one is nonnegative, strictly positive if at least one is positive, and nonzero if both are nonzero. -/ @[positivity max _ _] def evalMax : PositivityExt where eval {u α} zα pα e := do let .app (.app (f : Q($α → $α → $α)) (a : Q($α))) (b : Q($α)) ← withReducible (whnf e) | throwError "not max" let _e_eq : $e =Q $f $a $b := ⟨⟩ let _a ← synthInstanceQ q(LinearOrder $α) assumeInstancesCommute let ⟨_f_eq⟩ ← withDefault <| withNewMCtxDepth <| assertDefEqQ q($f) q(max) let result : Strictness zα pα e ← catchNone do let ra ← core zα pα a match ra with | .positive pa => pure (.positive q(lt_max_of_lt_left $pa)) | .nonnegative pa => pure (.nonnegative q(le_max_of_le_left $pa)) -- If `a ≠ 0`, we might prove `max a b ≠ 0` if `b ≠ 0` but we don't want to evaluate -- `b` before having ruled out `0 < a`, for performance. So we do that in the second branch -- of the `orElse'`. | _ => pure .none orElse result do let rb ← core zα pα b match rb with | .positive pb => pure (.positive q(lt_max_of_lt_right $pb)) | .nonnegative pb => pure (.nonnegative q(le_max_of_le_right $pb)) | .nonzero pb => do match ← core zα pα a with | .nonzero pa => pure (.nonzero q(max_ne $pa $pb)) | _ => pure .none | _ => pure .none /-- The `positivity` extension which identifies expressions of the form `a + b`, such that `positivity` successfully recognises both `a` and `b`. -/ @[positivity _ + _] def evalAdd : PositivityExt where eval {u α} zα pα e := do let .app (.app (f : Q($α → $α → $α)) (a : Q($α))) (b : Q($α)) ← withReducible (whnf e) | throwError "not +" let _e_eq : $e =Q $f $a $b := ⟨⟩ let _a ← synthInstanceQ q(AddZeroClass $α) assumeInstancesCommute let ⟨_f_eq⟩ ← withDefault <| withNewMCtxDepth <| assertDefEqQ q($f) q(HAdd.hAdd) let ra ← core zα pα a; let rb ← core zα pα b match ra, rb with | .positive pa, .positive pb => let _a ← synthInstanceQ q(AddLeftStrictMono $α) pure (.positive q(add_pos $pa $pb)) | .positive pa, .nonnegative pb => let _a ← synthInstanceQ q(AddLeftMono $α) pure (.positive q(add_pos_of_pos_of_nonneg $pa $pb)) | .nonnegative pa, .positive pb => let _a ← synthInstanceQ q(AddRightMono $α) pure (.positive q(Right.add_pos_of_nonneg_of_pos $pa $pb)) | .nonnegative pa, .nonnegative pb => let _a ← synthInstanceQ q(AddLeftMono $α) pure (.nonnegative q(add_nonneg $pa $pb)) | _, _ => failure /-- The `positivity` extension which identifies expressions of the form `a * b`, such that `positivity` successfully recognises both `a` and `b`. -/ @[positivity _ * _] def evalMul : PositivityExt where eval {u α} zα pα e := do let .app (.app (f : Q($α → $α → $α)) (a : Q($α))) (b : Q($α)) ← withReducible (whnf e) | throwError "not *" let _e_eq : $e =Q $f $a $b := ⟨⟩ let _a ← synthInstanceQ q(Mul $α) let ⟨_f_eq⟩ ← withDefault <| withNewMCtxDepth <| assertDefEqQ q($f) q(HMul.hMul) let ra ← core zα pα a; let rb ← core zα pα b let tryProveNonzero (pa? : Option Q($a ≠ 0)) (pb? : Option Q($b ≠ 0)) : MetaM (Strictness zα pα e) := do let pa ← liftOption pa? let pb ← liftOption pb? let _a ← synthInstanceQ q(NoZeroDivisors $α) pure (.nonzero q(mul_ne_zero $pa $pb)) let tryProveNonneg (pa? : Option Q(0 ≤ $a)) (pb? : Option Q(0 ≤ $b)) : MetaM (Strictness zα pα e) := do let pa ← liftOption pa? let pb ← liftOption pb? let _a ← synthInstanceQ q(MulZeroClass $α) let _a ← synthInstanceQ q(PosMulMono $α) assumeInstancesCommute pure (.nonnegative q(mul_nonneg $pa $pb)) let tryProvePositive (pa? : Option Q(0 < $a)) (pb? : Option Q(0 < $b)) : MetaM (Strictness zα pα e) := do let pa ← liftOption pa? let pb ← liftOption pb? let _a ← synthInstanceQ q(MulZeroClass $α) let _a ← synthInstanceQ q(PosMulStrictMono $α) assumeInstancesCommute pure (.positive q(mul_pos $pa $pb)) let mut result := .none result ← orElse result (tryProvePositive ra.toPositive rb.toPositive) result ← orElse result (tryProveNonneg ra.toNonneg rb.toNonneg) result ← orElse result (tryProveNonzero ra.toNonzero rb.toNonzero) return result private lemma int_div_self_pos {a : ℤ} (ha : 0 < a) : 0 < a / a := by rw [Int.ediv_self ha.ne']; exact zero_lt_one private lemma int_div_nonneg_of_pos_of_nonneg {a b : ℤ} (ha : 0 < a) (hb : 0 ≤ b) : 0 ≤ a / b := Int.ediv_nonneg ha.le hb private lemma int_div_nonneg_of_nonneg_of_pos {a b : ℤ} (ha : 0 ≤ a) (hb : 0 < b) : 0 ≤ a / b := Int.ediv_nonneg ha hb.le private lemma int_div_nonneg_of_pos_of_pos {a b : ℤ} (ha : 0 < a) (hb : 0 < b) : 0 ≤ a / b := Int.ediv_nonneg ha.le hb.le /-- The `positivity` extension which identifies expressions of the form `a / b`, where `a` and `b` are integers. -/ @[positivity (_ : ℤ) / (_ : ℤ)] def evalIntDiv : PositivityExt where eval {u α} _ _ e := do match u, α, e with | 0, ~q(ℤ), ~q($a / $b) => let ra ← core q(inferInstance) q(inferInstance) a let rb ← core q(inferInstance) q(inferInstance) b assertInstancesCommute match ra, rb with | .positive (pa : Q(0 < $a)), .positive (pb : Q(0 < $b)) => -- Only attempts to prove `0 < a / a`, otherwise falls back to `0 ≤ a / b` match ← isDefEqQ a b with | .defEq _ => pure (.positive q(int_div_self_pos $pa)) | .notDefEq => pure (.nonnegative q(int_div_nonneg_of_pos_of_pos $pa $pb)) | .positive (pa : Q(0 < $a)), .nonnegative (pb : Q(0 ≤ $b)) => pure (.nonnegative q(int_div_nonneg_of_pos_of_nonneg $pa $pb)) | .nonnegative (pa : Q(0 ≤ $a)), .positive (pb : Q(0 < $b)) => pure (.nonnegative q(int_div_nonneg_of_nonneg_of_pos $pa $pb)) | .nonnegative (pa : Q(0 ≤ $a)), .nonnegative (pb : Q(0 ≤ $b)) => pure (.nonnegative q(Int.ediv_nonneg $pa $pb)) | _, _ => pure .none | _, _, _ => throwError "not /" private theorem pow_zero_pos [Semiring α] [PartialOrder α] [IsOrderedRing α] [Nontrivial α] (a : α) : 0 < a ^ 0 := zero_lt_one.trans_le (pow_zero a).ge /-- The `positivity` extension which identifies expressions of the form `a ^ (0 : ℕ)`. This extension is run in addition to the general `a ^ b` extension (they are overlapping). -/ @[positivity _ ^ (0 : ℕ)] def evalPowZeroNat : PositivityExt where eval {u α} _zα _pα e := do let .app (.app _ (a : Q($α))) _ ← withReducible (whnf e) | throwError "not ^" let _a ← synthInstanceQ q(Semiring $α) let _a ← synthInstanceQ q(PartialOrder $α) let _a ← synthInstanceQ q(IsOrderedRing $α) _ ← synthInstanceQ q(Nontrivial $α) pure (.positive (q(pow_zero_pos $a) : Expr)) /-- The `positivity` extension which identifies expressions of the form `a ^ (b : ℕ)`, such that `positivity` successfully recognises both `a` and `b`. -/ @[positivity _ ^ (_ : ℕ)] def evalPow : PositivityExt where eval {u α} zα pα e := do let .app (.app _ (a : Q($α))) (b : Q(ℕ)) ← withReducible (whnf e) | throwError "not ^" let result ← catchNone do let .true := b.isAppOfArity ``OfNat.ofNat 3 | throwError "not a ^ n where n is a literal" let some n := (b.getRevArg! 1).rawNatLit? | throwError "not a ^ n where n is a literal" guard (n % 2 = 0) have m : Q(ℕ) := mkRawNatLit (n / 2) haveI' : $b =Q 2 * $m := ⟨⟩ let _a ← synthInstanceQ q(Ring $α) let _a ← synthInstanceQ q(LinearOrder $α) let _a ← synthInstanceQ q(IsStrictOrderedRing $α) assumeInstancesCommute haveI' : $e =Q $a ^ $b := ⟨⟩ pure (.nonnegative q((even_two_mul $m).pow_nonneg $a)) orElse result do let ra ← core zα pα a let ofNonneg (pa : Q(0 ≤ $a)) (_rα : Q(Semiring $α)) (_oα : Q(IsOrderedRing $α)) : MetaM (Strictness zα pα e) := do haveI' : $e =Q $a ^ $b := ⟨⟩ assumeInstancesCommute pure (.nonnegative q(pow_nonneg $pa $b)) let ofNonzero (pa : Q($a ≠ 0)) (_rα : Q(Semiring $α)) (_oα : Q(IsOrderedRing $α)) : MetaM (Strictness zα pα e) := do haveI' : $e =Q $a ^ $b := ⟨⟩ assumeInstancesCommute let _a ← synthInstanceQ q(NoZeroDivisors $α) pure (.nonzero q(pow_ne_zero $b $pa)) match ra with | .positive pa => try let _a ← synthInstanceQ q(Semiring $α) let _a ← synthInstanceQ q(IsStrictOrderedRing $α) assumeInstancesCommute haveI' : $e =Q $a ^ $b := ⟨⟩ pure (.positive q(pow_pos $pa $b)) catch e : Exception => trace[Tactic.positivity.failure] "{e.toMessageData}" let rα ← synthInstanceQ q(Semiring $α) let oα ← synthInstanceQ q(IsOrderedRing $α) orElse (← catchNone (ofNonneg q(le_of_lt $pa) rα oα)) (ofNonzero q(ne_of_gt $pa) rα oα) | .nonnegative pa => let sα ← synthInstanceQ q(Semiring $α) let oα ← synthInstanceQ q(IsOrderedRing $α) ofNonneg q($pa) q($sα) q($oα) | .nonzero pa => let sα ← synthInstanceQ q(Semiring $α) let oα ← synthInstanceQ q(IsOrderedRing $α) ofNonzero q($pa) q($sα) q($oα) | .none => pure .none private theorem abs_pos_of_ne_zero {α : Type*} [AddGroup α] [LinearOrder α] [AddLeftMono α] {a : α} : a ≠ 0 → 0 < |a| := abs_pos.mpr /-- The `positivity` extension which identifies expressions of the form `|a|`. -/ @[positivity |_|] def evalAbs : PositivityExt where eval {_u} (α zα pα) (e : Q($α)) := do let ~q(@abs _ (_) (_) $a) := e | throwError "not |·|" try match ← core zα pα a with | .positive pa => let pa' ← mkAppM ``abs_pos_of_pos #[pa] pure (.positive pa') | .nonzero pa => let pa' ← mkAppM ``abs_pos_of_ne_zero #[pa] pure (.positive pa') | _ => pure .none catch _ => do let pa' ← mkAppM ``abs_nonneg #[a] pure (.nonnegative pa') private theorem int_natAbs_pos {n : ℤ} (hn : 0 < n) : 0 < n.natAbs := Int.natAbs_pos.mpr hn.ne' /-- Extension for the `positivity` tactic: `Int.natAbs` is positive when its input is. Since the output type of `Int.natAbs` is `ℕ`, the nonnegative case is handled by the default `positivity` tactic. -/ @[positivity Int.natAbs _] def evalNatAbs : PositivityExt where eval {u α} _zα _pα e := do match u, α, e with | 0, ~q(ℕ), ~q(Int.natAbs $a) => let zα' : Q(Zero Int) := q(inferInstance) let pα' : Q(PartialOrder Int) := q(inferInstance) let ra ← core zα' pα' a match ra with | .positive pa => assertInstancesCommute pure (.positive q(int_natAbs_pos $pa)) | .nonzero pa => assertInstancesCommute pure (.positive q(Int.natAbs_pos.mpr $pa)) | .nonnegative _pa => pure .none | .none => pure .none | _, _, _ => throwError "not Int.natAbs" /-- Extension for the `positivity` tactic: `Nat.cast` is always non-negative, and positive when its input is. -/ @[positivity Nat.cast _] def evalNatCast : PositivityExt where eval {u α} _zα _pα e := do let ~q(@Nat.cast _ (_) ($a : ℕ)) := e | throwError "not Nat.cast" let zα' : Q(Zero Nat) := q(inferInstance) let pα' : Q(PartialOrder Nat) := q(inferInstance) let (_i1 : Q(AddMonoidWithOne $α)) ← synthInstanceQ q(AddMonoidWithOne $α) let (_i2 : Q(AddLeftMono $α)) ← synthInstanceQ q(AddLeftMono $α) let (_i3 : Q(ZeroLEOneClass $α)) ← synthInstanceQ q(ZeroLEOneClass $α) assumeInstancesCommute match ← core zα' pα' a with | .positive pa => let _nz ← synthInstanceQ q(NeZero (1 : $α)) pure (.positive q(Nat.cast_pos'.2 $pa)) | _ => pure (.nonnegative q(Nat.cast_nonneg' _)) /-- Extension for the `positivity` tactic: `Int.cast` is positive (resp. non-negative) if its input is. -/ @[positivity Int.cast _] def evalIntCast : PositivityExt where eval {u α} _zα _pα e := do let ~q(@Int.cast _ (_) ($a : ℤ)) := e | throwError "not Int.cast" let zα' : Q(Zero Int) := q(inferInstance) let pα' : Q(PartialOrder Int) := q(inferInstance) let ra ← core zα' pα' a match ra with | .positive pa => let _rα ← synthInstanceQ q(Ring $α) let _oα ← synthInstanceQ q(IsOrderedRing $α) let _nt ← synthInstanceQ q(Nontrivial $α) assumeInstancesCommute pure (.positive q(Int.cast_pos.mpr $pa)) | .nonnegative pa => let _rα ← synthInstanceQ q(Ring $α) let _oα ← synthInstanceQ q(IsOrderedRing $α) let _nt ← synthInstanceQ q(Nontrivial $α) assumeInstancesCommute pure (.nonnegative q(Int.cast_nonneg $pa)) | .nonzero pa => let _oα ← synthInstanceQ q(AddGroupWithOne $α) let _nt ← synthInstanceQ q(CharZero $α) assumeInstancesCommute pure (.nonzero q(Int.cast_ne_zero.mpr $pa)) | .none => pure .none /-- Extension for `Nat.succ`. -/ @[positivity Nat.succ _] def evalNatSucc : PositivityExt where eval {u α} _zα _pα e := do match u, α, e with | 0, ~q(ℕ), ~q(Nat.succ $a) => assertInstancesCommute pure (.positive q(Nat.succ_pos $a)) | _, _, _ => throwError "not Nat.succ" /-- Extension for `PNat.val`. -/ @[positivity PNat.val _] def evalPNatVal : PositivityExt where eval {u α} _zα _pα e := do match u, α, e with | 0, ~q(ℕ), ~q(PNat.val $a) => assertInstancesCommute pure (.positive q(PNat.pos $a)) | _, _, _ => throwError "not PNat.val" /-- Extension for `Nat.factorial`. -/ @[positivity Nat.factorial _] def evalFactorial : PositivityExt where eval {u α} _ _ e := do match u, α, e with | 0, ~q(ℕ), ~q(Nat.factorial $a) => assertInstancesCommute pure (.positive q(Nat.factorial_pos $a)) | _, _, _ => throwError "failed to match Nat.factorial" /-- Extension for `Nat.ascFactorial`. -/ @[positivity Nat.ascFactorial _ _] def evalAscFactorial : PositivityExt where eval {u α} _ _ e := do match u, α, e with | 0, ~q(ℕ), ~q(Nat.ascFactorial ($n + 1) $k) => assertInstancesCommute pure (.positive q(Nat.ascFactorial_pos $n $k)) | _, _, _ => throwError "failed to match Nat.ascFactorial" /-- Extension for `Nat.gcd`. Uses positivity of the left term, if available, then tries the right term. The implementation relies on the fact that `Positivity.core` on `ℕ` never returns `nonzero`. -/ @[positivity Nat.gcd _ _] def evalNatGCD : PositivityExt where eval {u α} z p e := do match u, α, e with | 0, ~q(ℕ), ~q(Nat.gcd $a $b) => assertInstancesCommute match ← core z p a with | .positive pa => return .positive q(Nat.gcd_pos_of_pos_left $b $pa) | _ => match ← core z p b with | .positive pb => return .positive q(Nat.gcd_pos_of_pos_right $a $pb) | _ => failure | _, _, _ => throwError "not Nat.gcd" /-- Extension for `Nat.lcm`. -/ @[positivity Nat.lcm _ _] def evalNatLCM : PositivityExt where eval {u α} z p e := do match u, α, e with | 0, ~q(ℕ), ~q(Nat.lcm $a $b) => assertInstancesCommute match ← core z p a with | .positive pa => match ← core z p b with | .positive pb => return .positive q(Nat.lcm_pos $pa $pb) | _ => failure | _ => failure | _, _, _ => throwError "not Nat.lcm" /-- Extension for `Nat.sqrt`. -/ @[positivity Nat.sqrt _] def evalNatSqrt : PositivityExt where eval {u α} z p e := do match u, α, e with | 0, ~q(ℕ), ~q(Nat.sqrt $n) => assumeInstancesCommute match ← core z p n with | .positive pa => return .positive q(Nat.sqrt_pos.mpr $pa) | _ => failure | _, _, _ => throwError "not Nat.sqrt" /-- Extension for `Int.gcd`. Uses positivity of the left term, if available, then tries the right term. -/ @[positivity Int.gcd _ _] def evalIntGCD : PositivityExt where eval {u α} _ _ e := do match u, α, e with | 0, ~q(ℕ), ~q(Int.gcd $a $b) => let z ← synthInstanceQ (q(Zero ℤ) : Q(Type)) let p ← synthInstanceQ (q(PartialOrder ℤ) : Q(Type)) assertInstancesCommute match (← catchNone (core z p a)).toNonzero with | some na => return .positive q(Int.gcd_pos_of_ne_zero_left $b $na) | none => match (← core z p b).toNonzero with | some nb => return .positive q(Int.gcd_pos_of_ne_zero_right $a $nb) | none => failure | _, _, _ => throwError "not Int.gcd" /-- Extension for `Int.lcm`. -/ @[positivity Int.lcm _ _] def evalIntLCM : PositivityExt where eval {u α} _ _ e := do match u, α, e with | 0, ~q(ℕ), ~q(Int.lcm $a $b) => let z ← synthInstanceQ (q(Zero ℤ) : Q(Type)) let p ← synthInstanceQ (q(PartialOrder ℤ) : Q(Type)) assertInstancesCommute match (← core z p a).toNonzero with | some na => match (← core z p b).toNonzero with | some nb => return .positive q(Int.lcm_pos $na $nb) | _ => failure | _ => failure | _, _, _ => throwError "not Int.lcm" section NNRat open NNRat private alias ⟨_, NNRat.num_pos_of_pos⟩ := num_pos private alias ⟨_, NNRat.num_ne_zero_of_ne_zero⟩ := num_ne_zero /-- The `positivity` extension which identifies expressions of the form `NNRat.num q`, such that `positivity` successfully recognises `q`. -/ @[positivity NNRat.num _] def evalNNRatNum : PositivityExt where eval {u α} _ _ e := do match u, α, e with | 0, ~q(ℕ), ~q(NNRat.num $a) => let zα : Q(Zero ℚ≥0) := q(inferInstance) let pα : Q(PartialOrder ℚ≥0) := q(inferInstance) assumeInstancesCommute match ← core zα pα a with | .positive pa => return .positive q(NNRat.num_pos_of_pos $pa) | .nonzero pa => return .nonzero q(NNRat.num_ne_zero_of_ne_zero $pa) | _ => return .none | _, _, _ => throwError "not NNRat.num" /-- The `positivity` extension which identifies expressions of the form `Rat.den a`. -/ @[positivity NNRat.den _] def evalNNRatDen : PositivityExt where eval {u α} _ _ e := do match u, α, e with | 0, ~q(ℕ), ~q(NNRat.den $a) => assumeInstancesCommute return .positive q(den_pos $a) | _, _, _ => throwError "not NNRat.den" variable {q : ℚ≥0} example (hq : 0 < q) : 0 < q.num := by positivity example (hq : q ≠ 0) : q.num ≠ 0 := by positivity example : 0 < q.den := by positivity end NNRat open Rat private alias ⟨_, num_pos_of_pos⟩ := num_pos private alias ⟨_, num_nonneg_of_nonneg⟩ := num_nonneg private alias ⟨_, num_ne_zero_of_ne_zero⟩ := num_ne_zero /-- The `positivity` extension which identifies expressions of the form `Rat.num a`, such that `positivity` successfully recognises `a`. -/ @[positivity Rat.num _] def evalRatNum : PositivityExt where eval {u α} _ _ e := do match u, α, e with | 0, ~q(ℤ), ~q(Rat.num $a) => let zα : Q(Zero ℚ) := q(inferInstance) let pα : Q(PartialOrder ℚ) := q(inferInstance) assumeInstancesCommute match ← core zα pα a with | .positive pa => pure <| .positive q(num_pos_of_pos $pa) | .nonnegative pa => pure <| .nonnegative q(num_nonneg_of_nonneg $pa) | .nonzero pa => pure <| .nonzero q(num_ne_zero_of_ne_zero $pa) | .none => pure .none | _, _ => throwError "not Rat.num" /-- The `positivity` extension which identifies expressions of the form `Rat.den a`. -/ @[positivity Rat.den _] def evalRatDen : PositivityExt where eval {u α} _ _ e := do match u, α, e with | 0, ~q(ℕ), ~q(Rat.den $a) => assumeInstancesCommute pure <| .positive q(den_pos $a) | _, _ => throwError "not Rat.num" /-- Extension for `posPart`. `a⁺` is always nonnegative, and positive if `a` is. -/ @[positivity _⁺] def evalPosPart : PositivityExt where eval {u α} zα pα e := do match e with | ~q(@posPart _ $instαpospart $a) => let _instαlat ← synthInstanceQ q(Lattice $α) let _instαgrp ← synthInstanceQ q(AddGroup $α) assertInstancesCommute -- FIXME: There seems to be a bug in `Positivity.core` that makes it fail (instead of returning -- `.none`) here sometimes. See e.g. the first test for `posPart`. This is why we need -- `catchNone` match ← catchNone (core zα pα a) with | .positive pf => return .positive q(posPart_pos $pf) | _ => return .nonnegative q(posPart_nonneg $a) | _ => throwError "not `posPart`" /-- Extension for `negPart`. `a⁻` is always nonnegative. -/ @[positivity _⁻] def evalNegPart : PositivityExt where eval {u α} _ _ e := do match e with | ~q(@negPart _ $instαnegpart $a) => let _instαlat ← synthInstanceQ q(Lattice $α) let _instαgrp ← synthInstanceQ q(AddGroup $α) assertInstancesCommute return .nonnegative q(negPart_nonneg $a) | _ => throwError "not `negPart`" /-- Extension for the `positivity` tactic: nonnegative maps take nonnegative values. -/ @[positivity DFunLike.coe _ _] def evalMap : PositivityExt where eval {_ β} _ _ e := do let .app (.app _ f) a ← whnfR e | throwError "not ↑f · where f is of NonnegHomClass" let pa ← mkAppOptM ``apply_nonneg #[none, none, β, none, none, none, none, f, a] pure (.nonnegative pa) end Positivity end Meta end Mathlib
.lake/packages/mathlib/Mathlib/Tactic/ArithMult/Init.lean
import Mathlib.Init import Aesop /-! # arith_mult Rule Set This module defines the `IsMultiplicative` Aesop rule set which is used by the `arith_mult` tactic. Aesop rule sets only become visible once the file in which they're declared is imported, so we must put this declaration into its own file. -/ declare_aesop_rule_sets [IsMultiplicative]
.lake/packages/mathlib/Mathlib/Tactic/ReduceModChar/Ext.lean
import Mathlib.Init import Lean.Meta.Tactic.Simp.Attr /-! # `@[reduce_mod_char]` attribute This file registers `@[reduce_mod_char]` as a `simp` attribute. -/ open Lean Meta /-- `@[reduce_mod_char]` is an attribute that tags lemmas for preprocessing and cleanup in the `reduce_mod_char` tactic -/ initialize reduceModCharExt : SimpExtension ← registerSimpAttr `reduce_mod_char "lemmas for preprocessing and cleanup in the `reduce_mod_char` tactic"
.lake/packages/mathlib/Mathlib/Order/WellFoundedSet.lean
import Mathlib.Data.Prod.Lex import Mathlib.Data.Sigma.Lex import Mathlib.Order.RelIso.Set import Mathlib.Order.WellQuasiOrder import Mathlib.Tactic.TFAE /-! # Well-founded sets This file introduces versions of `WellFounded` and `WellQuasiOrdered` for sets. ## Main Definitions * `Set.WellFoundedOn s r` indicates that the relation `r` is well-founded when restricted to the set `s`. * `Set.IsWF s` indicates that `<` is well-founded when restricted to `s`. * `Set.PartiallyWellOrderedOn s r` indicates that the relation `r` is partially well-ordered (also known as well quasi-ordered) when restricted to the set `s`. * `Set.IsPWO s` indicates that any infinite sequence of elements in `s` contains an infinite monotone subsequence. Note that this is equivalent to containing only two comparable elements. ## Main Results * Higman's Lemma, `Set.PartiallyWellOrderedOn.partiallyWellOrderedOn_sublistForall₂`, shows that if `r` is partially well-ordered on `s`, then `List.SublistForall₂` is partially well-ordered on the set of lists of elements of `s`. The result was originally published by Higman, but this proof more closely follows Nash-Williams. * `Set.wellFoundedOn_iff` relates `well_founded_on` to the well-foundedness of a relation on the original type, to avoid dealing with subtypes. * `Set.IsWF.mono` shows that a subset of a well-founded subset is well-founded. * `Set.IsWF.union` shows that the union of two well-founded subsets is well-founded. * `Finset.isWF` shows that all `Finset`s are well-founded. ## TODO * Prove that `s` is partially well-ordered iff it has no infinite descending chain or antichain. * Rename `Set.PartiallyWellOrderedOn` to `Set.WellQuasiOrderedOn` and `Set.IsPWO` to `Set.IsWQO`. ## References * [Higman, *Ordering by Divisibility in Abstract Algebras*][Higman52] * [Nash-Williams, *On Well-Quasi-Ordering Finite Trees*][Nash-Williams63] -/ assert_not_exists IsOrderedRing open scoped Function -- required for scoped `on` notation variable {ι α β γ : Type*} {π : ι → Type*} namespace Set /-! ### Relations well-founded on sets -/ /-- `s.WellFoundedOn r` indicates that the relation `r` is `WellFounded` when restricted to `s`. -/ def WellFoundedOn (s : Set α) (r : α → α → Prop) : Prop := WellFounded (Subrel r (· ∈ s)) @[simp] theorem wellFoundedOn_empty (r : α → α → Prop) : WellFoundedOn ∅ r := wellFounded_of_isEmpty _ section WellFoundedOn variable {r r' : α → α → Prop} section AnyRel variable {f : β → α} {s t : Set α} {x y : α} theorem wellFoundedOn_iff : s.WellFoundedOn r ↔ WellFounded fun a b : α => r a b ∧ a ∈ s ∧ b ∈ s := by have f : RelEmbedding (Subrel r (· ∈ s)) fun a b : α => r a b ∧ a ∈ s ∧ b ∈ s := ⟨⟨(↑), Subtype.coe_injective⟩, by simp⟩ refine ⟨fun h => ?_, f.wellFounded⟩ rw [WellFounded.wellFounded_iff_has_min] intro t ht by_cases hst : (s ∩ t).Nonempty · rw [← Subtype.preimage_coe_nonempty] at hst rcases h.has_min (Subtype.val ⁻¹' t) hst with ⟨⟨m, ms⟩, mt, hm⟩ exact ⟨m, mt, fun x xt ⟨xm, xs, _⟩ => hm ⟨x, xs⟩ xt xm⟩ · rcases ht with ⟨m, mt⟩ exact ⟨m, mt, fun x _ ⟨_, _, ms⟩ => hst ⟨m, ⟨ms, mt⟩⟩⟩ @[simp] theorem wellFoundedOn_univ : (univ : Set α).WellFoundedOn r ↔ WellFounded r := by simp [wellFoundedOn_iff] theorem _root_.WellFounded.wellFoundedOn : WellFounded r → s.WellFoundedOn r := InvImage.wf _ @[simp] theorem wellFoundedOn_range : (range f).WellFoundedOn r ↔ WellFounded (r on f) := by let f' : β → range f := fun c => ⟨f c, c, rfl⟩ refine ⟨fun h => (InvImage.wf f' h).mono fun c c' => id, fun h => ⟨?_⟩⟩ rintro ⟨_, c, rfl⟩ refine Acc.of_downward_closed f' ?_ _ ?_ · rintro _ ⟨_, c', rfl⟩ - exact ⟨c', rfl⟩ · exact h.apply _ @[simp] theorem wellFoundedOn_image {s : Set β} : (f '' s).WellFoundedOn r ↔ s.WellFoundedOn (r on f) := by rw [image_eq_range]; exact wellFoundedOn_range namespace WellFoundedOn protected theorem induction (hs : s.WellFoundedOn r) (hx : x ∈ s) {P : α → Prop} (hP : ∀ y ∈ s, (∀ z ∈ s, r z y → P z) → P y) : P x := by let Q : s → Prop := fun y => P y change Q ⟨x, hx⟩ refine WellFounded.induction hs ⟨x, hx⟩ ?_ simpa only [Subtype.forall] protected theorem mono (h : t.WellFoundedOn r') (hle : r ≤ r') (hst : s ⊆ t) : s.WellFoundedOn r := by rw [wellFoundedOn_iff] at * exact Subrelation.wf (fun xy => ⟨hle _ _ xy.1, hst xy.2.1, hst xy.2.2⟩) h theorem mono' (h : ∀ (a) (_ : a ∈ s) (b) (_ : b ∈ s), r' a b → r a b) : s.WellFoundedOn r → s.WellFoundedOn r' := Subrelation.wf @fun a b => h _ a.2 _ b.2 theorem subset (h : t.WellFoundedOn r) (hst : s ⊆ t) : s.WellFoundedOn r := h.mono le_rfl hst open Relation open List in /-- `a` is accessible under the relation `r` iff `r` is well-founded on the downward transitive closure of `a` under `r` (including `a` or not). -/ theorem acc_iff_wellFoundedOn {α} {r : α → α → Prop} {a : α} : TFAE [Acc r a, WellFoundedOn { b | ReflTransGen r b a } r, WellFoundedOn { b | TransGen r b a } r] := by tfae_have 1 → 2 := by refine fun h => ⟨fun b => InvImage.accessible Subtype.val ?_⟩ rw [← acc_transGen_iff] at h ⊢ obtain h' | h' := reflTransGen_iff_eq_or_transGen.1 b.2 · rwa [h'] at h · exact h.inv h' tfae_have 2 → 3 := fun h => h.subset fun _ => TransGen.to_reflTransGen tfae_have 3 → 1 := by refine fun h => Acc.intro _ (fun b hb => (h.apply ⟨b, .single hb⟩).of_fibration Subtype.val ?_) exact fun ⟨c, hc⟩ d h => ⟨⟨d, .head h hc⟩, h, rfl⟩ tfae_finish end WellFoundedOn end AnyRel section IsStrictOrder variable [IsStrictOrder α r] {s t : Set α} instance IsStrictOrder.subset : IsStrictOrder α fun a b : α => r a b ∧ a ∈ s ∧ b ∈ s where toIsIrrefl := ⟨fun a con => irrefl_of r a con.1⟩ toIsTrans := ⟨fun _ _ _ ab bc => ⟨trans_of r ab.1 bc.1, ab.2.1, bc.2.2⟩⟩ theorem wellFoundedOn_iff_no_descending_seq : s.WellFoundedOn r ↔ ∀ f : ((· > ·) : ℕ → ℕ → Prop) ↪r r, ¬∀ n, f n ∈ s := by simp only [wellFoundedOn_iff, RelEmbedding.wellFounded_iff_isEmpty, ← not_exists, ← not_nonempty_iff, not_iff_not] constructor · rintro ⟨⟨f, hf⟩⟩ have H : ∀ n, f n ∈ s := fun n => (hf.2 n.lt_succ_self).2.2 refine ⟨⟨f, ?_⟩, H⟩ simpa only [H, and_true] using @hf · rintro ⟨⟨f, hf⟩, hfs : ∀ n, f n ∈ s⟩ refine ⟨⟨f, ?_⟩⟩ simpa only [hfs, and_true] using @hf theorem WellFoundedOn.union (hs : s.WellFoundedOn r) (ht : t.WellFoundedOn r) : (s ∪ t).WellFoundedOn r := by rw [wellFoundedOn_iff_no_descending_seq] at * rintro f hf rcases Nat.exists_subseq_of_forall_mem_union f hf with ⟨g, hg | hg⟩ exacts [hs (g.dual.ltEmbedding.trans f) hg, ht (g.dual.ltEmbedding.trans f) hg] @[simp] theorem wellFoundedOn_union : (s ∪ t).WellFoundedOn r ↔ s.WellFoundedOn r ∧ t.WellFoundedOn r := ⟨fun h => ⟨h.subset subset_union_left, h.subset subset_union_right⟩, fun h => h.1.union h.2⟩ end IsStrictOrder end WellFoundedOn /-! ### Sets well-founded w.r.t. the strict inequality -/ section LT variable [LT α] {s t : Set α} /-- `s.IsWF` indicates that `<` is well-founded when restricted to `s`. -/ def IsWF (s : Set α) : Prop := WellFoundedOn s (· < ·) @[simp] theorem isWF_empty : IsWF (∅ : Set α) := wellFounded_of_isEmpty _ theorem IsWF.mono (h : IsWF t) (st : s ⊆ t) : IsWF s := h.subset st theorem isWF_univ_iff : IsWF (univ : Set α) ↔ WellFoundedLT α := by simp [IsWF, wellFoundedOn_iff, isWellFounded_iff] theorem IsWF.of_wellFoundedLT [h : WellFoundedLT α] (s : Set α) : s.IsWF := (Set.isWF_univ_iff.2 h).mono s.subset_univ end LT section Preorder variable [Preorder α] {s t : Set α} {a : α} protected nonrec theorem IsWF.union (hs : IsWF s) (ht : IsWF t) : IsWF (s ∪ t) := hs.union ht @[simp] theorem isWF_union : IsWF (s ∪ t) ↔ IsWF s ∧ IsWF t := wellFoundedOn_union end Preorder section Preorder variable [Preorder α] {s t : Set α} {a : α} theorem isWF_iff_no_descending_seq : IsWF s ↔ ∀ f : ℕ → α, StrictAnti f → ¬∀ n, f n ∈ s := wellFoundedOn_iff_no_descending_seq.trans ⟨fun H f hf => H ⟨⟨f, hf.injective⟩, hf.lt_iff_gt⟩, fun H f => H f fun _ _ => f.map_rel_iff.2⟩ end Preorder /-! ### Partially well-ordered sets -/ /-- `s.PartiallyWellOrderedOn r` indicates that the relation `r` is `WellQuasiOrdered` when restricted to `s`. A set is partially well-ordered by a relation `r` when any infinite sequence contains two elements where the first is related to the second by `r`. Equivalently, any antichain (see `IsAntichain`) is finite, see `Set.partiallyWellOrderedOn_iff_finite_antichains`. TODO: rename this to `WellQuasiOrderedOn` to match `WellQuasiOrdered`. -/ def PartiallyWellOrderedOn (s : Set α) (r : α → α → Prop) : Prop := WellQuasiOrdered (Subrel r (· ∈ s)) section PartiallyWellOrderedOn variable {r : α → α → Prop} {r' : β → β → Prop} {f : α → β} {s : Set α} {t : Set α} {a : α} theorem PartiallyWellOrderedOn.exists_lt (hs : s.PartiallyWellOrderedOn r) {f : ℕ → α} (hf : ∀ n, f n ∈ s) : ∃ m n, m < n ∧ r (f m) (f n) := hs fun n ↦ ⟨_, hf n⟩ theorem partiallyWellOrderedOn_iff_exists_lt : s.PartiallyWellOrderedOn r ↔ ∀ f : ℕ → α, (∀ n, f n ∈ s) → ∃ m n, m < n ∧ r (f m) (f n) := ⟨PartiallyWellOrderedOn.exists_lt, fun hf f ↦ hf _ fun n ↦ (f n).2⟩ theorem partiallyWellOrderedOn_univ_iff : univ.PartiallyWellOrderedOn r ↔ WellQuasiOrdered r := (RelIso.subrelUnivIso (by simp)).wellQuasiOrdered_iff theorem PartiallyWellOrderedOn.mono (ht : t.PartiallyWellOrderedOn r) (h : s ⊆ t) : s.PartiallyWellOrderedOn r := fun f ↦ ht (Set.inclusion h ∘ f) theorem partiallyWellOrderedOn_of_wellQuasiOrdered (h : WellQuasiOrdered r) (s : Set α) : s.PartiallyWellOrderedOn r := (partiallyWellOrderedOn_univ_iff.mpr h).mono s.subset_univ @[simp] theorem partiallyWellOrderedOn_empty (r : α → α → Prop) : PartiallyWellOrderedOn ∅ r := wellQuasiOrdered_of_isEmpty _ theorem PartiallyWellOrderedOn.union (hs : s.PartiallyWellOrderedOn r) (ht : t.PartiallyWellOrderedOn r) : (s ∪ t).PartiallyWellOrderedOn r := by intro f obtain ⟨g, hgs | hgt⟩ := Nat.exists_subseq_of_forall_mem_union _ fun x ↦ (f x).2 · rcases hs.exists_lt hgs with ⟨m, n, hlt, hr⟩ exact ⟨g m, g n, g.strictMono hlt, hr⟩ · rcases ht.exists_lt hgt with ⟨m, n, hlt, hr⟩ exact ⟨g m, g n, g.strictMono hlt, hr⟩ @[simp] theorem partiallyWellOrderedOn_union : (s ∪ t).PartiallyWellOrderedOn r ↔ s.PartiallyWellOrderedOn r ∧ t.PartiallyWellOrderedOn r := ⟨fun h ↦ ⟨h.mono subset_union_left, h.mono subset_union_right⟩, fun h ↦ h.1.union h.2⟩ theorem PartiallyWellOrderedOn.image_of_monotone_on (hs : s.PartiallyWellOrderedOn r) (hf : ∀ a₁ ∈ s, ∀ a₂ ∈ s, r a₁ a₂ → r' (f a₁) (f a₂)) : (f '' s).PartiallyWellOrderedOn r' := by rw [partiallyWellOrderedOn_iff_exists_lt] at * intro g' hg' choose g hgs heq using hg' obtain rfl : f ∘ g = g' := funext heq obtain ⟨m, n, hlt, hmn⟩ := hs g hgs exact ⟨m, n, hlt, hf _ (hgs m) _ (hgs n) hmn⟩ -- TODO: prove this in terms of `IsAntichain.finite_of_wellQuasiOrdered` theorem _root_.IsAntichain.finite_of_partiallyWellOrderedOn (ha : IsAntichain r s) (hp : s.PartiallyWellOrderedOn r) : s.Finite := by refine not_infinite.1 fun hi => ?_ obtain ⟨m, n, hmn, h⟩ := hp (hi.natEmbedding _) exact hmn.ne ((hi.natEmbedding _).injective <| Subtype.val_injective <| ha.eq (hi.natEmbedding _ m).2 (hi.natEmbedding _ n).2 h) section IsRefl variable [IsRefl α r] protected theorem Finite.partiallyWellOrderedOn (hs : s.Finite) : s.PartiallyWellOrderedOn r := hs.to_subtype.wellQuasiOrdered _ theorem _root_.IsAntichain.partiallyWellOrderedOn_iff (hs : IsAntichain r s) : s.PartiallyWellOrderedOn r ↔ s.Finite := ⟨hs.finite_of_partiallyWellOrderedOn, Finite.partiallyWellOrderedOn⟩ @[simp] theorem partiallyWellOrderedOn_singleton (a : α) : PartiallyWellOrderedOn {a} r := (finite_singleton a).partiallyWellOrderedOn @[nontriviality] theorem Subsingleton.partiallyWellOrderedOn (hs : s.Subsingleton) : PartiallyWellOrderedOn s r := hs.finite.partiallyWellOrderedOn @[simp] theorem partiallyWellOrderedOn_insert : PartiallyWellOrderedOn (insert a s) r ↔ PartiallyWellOrderedOn s r := by simp only [← singleton_union, partiallyWellOrderedOn_union, partiallyWellOrderedOn_singleton, true_and] protected theorem PartiallyWellOrderedOn.insert (h : PartiallyWellOrderedOn s r) (a : α) : PartiallyWellOrderedOn (insert a s) r := partiallyWellOrderedOn_insert.2 h theorem partiallyWellOrderedOn_iff_finite_antichains [IsSymm α r] : s.PartiallyWellOrderedOn r ↔ ∀ t, t ⊆ s → IsAntichain r t → t.Finite := by refine ⟨fun h t ht hrt => hrt.finite_of_partiallyWellOrderedOn (h.mono ht), ?_⟩ rw [partiallyWellOrderedOn_iff_exists_lt] intro hs f hf by_contra! H refine infinite_range_of_injective (fun m n hmn => ?_) (hs _ (range_subset_iff.2 hf) ?_) · obtain h | h | h := lt_trichotomy m n · refine (H _ _ h ?_).elim rw [hmn] exact refl _ · exact h · refine (H _ _ h ?_).elim rw [hmn] exact refl _ rintro _ ⟨m, hm, rfl⟩ _ ⟨n, hn, rfl⟩ hmn obtain h | h := (ne_of_apply_ne _ hmn).lt_or_gt · exact H _ _ h · exact mt symm (H _ _ h) end IsRefl section IsPreorder variable [IsPreorder α r] theorem PartiallyWellOrderedOn.exists_monotone_subseq (h : s.PartiallyWellOrderedOn r) {f : ℕ → α} (hf : ∀ n, f n ∈ s) : ∃ g : ℕ ↪o ℕ, ∀ m n : ℕ, m ≤ n → r (f (g m)) (f (g n)) := WellQuasiOrdered.exists_monotone_subseq h fun n ↦ ⟨_, hf n⟩ theorem partiallyWellOrderedOn_iff_exists_monotone_subseq : s.PartiallyWellOrderedOn r ↔ ∀ f : ℕ → α, (∀ n, f n ∈ s) → ∃ g : ℕ ↪o ℕ, ∀ m n : ℕ, m ≤ n → r (f (g m)) (f (g n)) := by use PartiallyWellOrderedOn.exists_monotone_subseq rw [PartiallyWellOrderedOn, wellQuasiOrdered_iff_exists_monotone_subseq] exact fun H f ↦ H _ fun n ↦ (f n).2 protected theorem PartiallyWellOrderedOn.prod {t : Set β} (hs : PartiallyWellOrderedOn s r) (ht : PartiallyWellOrderedOn t r') : PartiallyWellOrderedOn (s ×ˢ t) fun x y : α × β => r x.1 y.1 ∧ r' x.2 y.2 := by rw [partiallyWellOrderedOn_iff_exists_lt] intro f hf obtain ⟨g₁, h₁⟩ := hs.exists_monotone_subseq fun n => (hf n).1 obtain ⟨m, n, hlt, hle⟩ := ht.exists_lt fun n => (hf _).2 exact ⟨g₁ m, g₁ n, g₁.strictMono hlt, h₁ _ _ hlt.le, hle⟩ theorem PartiallyWellOrderedOn.wellFoundedOn (h : s.PartiallyWellOrderedOn r) : s.WellFoundedOn fun a b => r a b ∧ ¬ r b a := h.wellFounded end IsPreorder end PartiallyWellOrderedOn section IsPWO variable [Preorder α] [Preorder β] {s t : Set α} /-- A subset of a preorder is partially well-ordered when any infinite sequence contains a monotone subsequence of length 2 (or equivalently, an infinite monotone subsequence). -/ def IsPWO (s : Set α) : Prop := PartiallyWellOrderedOn s (· ≤ ·) nonrec theorem IsPWO.mono (ht : t.IsPWO) : s ⊆ t → s.IsPWO := ht.mono nonrec theorem IsPWO.exists_monotone_subseq (h : s.IsPWO) {f : ℕ → α} (hf : ∀ n, f n ∈ s) : ∃ g : ℕ ↪o ℕ, Monotone (f ∘ g) := h.exists_monotone_subseq hf theorem isPWO_univ_iff : (univ : Set α).IsPWO ↔ WellQuasiOrderedLE α := partiallyWellOrderedOn_univ_iff.trans (wellQuasiOrderedLE_def _).symm theorem isPWO_of_wellQuasiOrderedLE [h : WellQuasiOrderedLE α] (s : Set α) : s.IsPWO := partiallyWellOrderedOn_of_wellQuasiOrdered h.wqo s theorem isPWO_iff_exists_monotone_subseq : s.IsPWO ↔ ∀ f : ℕ → α, (∀ n, f n ∈ s) → ∃ g : ℕ ↪o ℕ, Monotone (f ∘ g) := partiallyWellOrderedOn_iff_exists_monotone_subseq protected theorem IsPWO.isWF (h : s.IsPWO) : s.IsWF := by simpa only [← lt_iff_le_not_ge] using h.wellFoundedOn nonrec theorem IsPWO.prod {t : Set β} (hs : s.IsPWO) (ht : t.IsPWO) : IsPWO (s ×ˢ t) := hs.prod ht theorem IsPWO.image_of_monotoneOn (hs : s.IsPWO) {f : α → β} (hf : MonotoneOn f s) : IsPWO (f '' s) := hs.image_of_monotone_on hf theorem IsPWO.image_of_monotone (hs : s.IsPWO) {f : α → β} (hf : Monotone f) : IsPWO (f '' s) := hs.image_of_monotone_on (hf.monotoneOn _) protected nonrec theorem IsPWO.union (hs : IsPWO s) (ht : IsPWO t) : IsPWO (s ∪ t) := hs.union ht @[simp] theorem isPWO_union : IsPWO (s ∪ t) ↔ IsPWO s ∧ IsPWO t := partiallyWellOrderedOn_union protected theorem Finite.isPWO (hs : s.Finite) : IsPWO s := hs.partiallyWellOrderedOn @[simp] theorem isPWO_of_finite [Finite α] : s.IsPWO := s.toFinite.isPWO @[simp] theorem isPWO_singleton (a : α) : IsPWO ({a} : Set α) := (finite_singleton a).isPWO @[simp] theorem isPWO_empty : IsPWO (∅ : Set α) := finite_empty.isPWO protected theorem Subsingleton.isPWO (hs : s.Subsingleton) : IsPWO s := hs.finite.isPWO @[simp] theorem isPWO_insert {a} : IsPWO (insert a s) ↔ IsPWO s := by simp only [← singleton_union, isPWO_union, isPWO_singleton, true_and] protected theorem IsPWO.insert (h : IsPWO s) (a : α) : IsPWO (insert a s) := isPWO_insert.2 h protected theorem Finite.isWF (hs : s.Finite) : IsWF s := hs.isPWO.isWF @[simp] theorem isWF_singleton {a : α} : IsWF ({a} : Set α) := (finite_singleton a).isWF protected theorem Subsingleton.isWF (hs : s.Subsingleton) : IsWF s := hs.isPWO.isWF @[simp] theorem isWF_insert {a} : IsWF (insert a s) ↔ IsWF s := by simp only [← singleton_union, isWF_union, isWF_singleton, true_and] protected theorem IsWF.insert (h : IsWF s) (a : α) : IsWF (insert a s) := isWF_insert.2 h theorem IsPWO.exists_le_minimal {a} (hs : s.IsPWO) (ha : a ∈ s) : ∃ b ≤ a, Minimal (· ∈ s) b := by let t : Set s := {x | x ≤ a} let h : t.Nonempty := ⟨⟨a, ha⟩, le_rfl⟩ refine ⟨hs.wellFounded.min t h, hs.wellFounded.min_mem t h, (hs.wellFounded.min t h).2, fun y hy hle => ?_⟩ by_contra hnle exact hs.wellFounded.not_lt_min t h (x := ⟨y, hy⟩) (hle.trans (hs.wellFounded.min_mem t h)) ⟨hle, hnle⟩ theorem IsPWO.exists_minimal (h : s.IsPWO) (hs : s.Nonempty) : ∃ a, Minimal (· ∈ s) a := by rcases hs with ⟨a, ha⟩ obtain ⟨b, _, hb⟩ := h.exists_le_minimal ha exact ⟨b, hb⟩ theorem IsPWO.exists_minimalFor (f : ι → α) (s : Set ι) (h : (f '' s).IsPWO) (hs : s.Nonempty) : ∃ i, MinimalFor (· ∈ s) f i := by obtain ⟨_, h⟩ := h.exists_minimal (hs.image _) obtain ⟨a, ha, rfl⟩ := h.1 exact ⟨a, ha, fun b hb => h.2 (mem_image_of_mem _ hb)⟩ end IsPWO section WellFoundedOn variable {r : α → α → Prop} [IsStrictOrder α r] {s : Set α} {a : α} protected theorem Finite.wellFoundedOn (hs : s.Finite) : s.WellFoundedOn r := letI := partialOrderOfSO r hs.isWF @[simp] theorem wellFoundedOn_singleton : WellFoundedOn ({a} : Set α) r := (finite_singleton a).wellFoundedOn protected theorem Subsingleton.wellFoundedOn (hs : s.Subsingleton) : s.WellFoundedOn r := hs.finite.wellFoundedOn @[simp] theorem wellFoundedOn_insert : WellFoundedOn (insert a s) r ↔ WellFoundedOn s r := by simp only [← singleton_union, wellFoundedOn_union, wellFoundedOn_singleton, true_and] @[simp] theorem wellFoundedOn_sdiff_singleton : WellFoundedOn (s \ {a}) r ↔ WellFoundedOn s r := by simp only [← wellFoundedOn_insert (a := a), insert_diff_singleton, mem_insert_iff, true_or, insert_eq_of_mem] protected theorem WellFoundedOn.insert (h : WellFoundedOn s r) (a : α) : WellFoundedOn (insert a s) r := wellFoundedOn_insert.2 h protected theorem WellFoundedOn.sdiff_singleton (h : WellFoundedOn s r) (a : α) : WellFoundedOn (s \ {a}) r := wellFoundedOn_sdiff_singleton.2 h lemma WellFoundedOn.mapsTo {α β : Type*} {r : α → α → Prop} (f : β → α) {s : Set α} {t : Set β} (h : MapsTo f t s) (hw : s.WellFoundedOn r) : t.WellFoundedOn (r on f) := by exact InvImage.wf (fun x : t ↦ ⟨f x, h x.prop⟩) hw end WellFoundedOn section LinearOrder variable [LinearOrder α] {s : Set α} /-- In a linear order, the predicates `Set.IsPWO` and `Set.IsWF` are equivalent. -/ theorem isPWO_iff_isWF : s.IsPWO ↔ s.IsWF := by change WellQuasiOrdered (· ≤ ·) ↔ WellFounded (· < ·) rw [← wellQuasiOrderedLE_def, ← isWellFounded_iff, wellQuasiOrderedLE_iff_wellFoundedLT] alias ⟨_, IsWF.isPWO⟩ := isPWO_iff_isWF /-- If `α` is a linear order with well-founded `<`, then any set in it is a partially well-ordered set. Note this does not hold without the linearity assumption. -/ lemma IsPWO.of_linearOrder [WellFoundedLT α] (s : Set α) : s.IsPWO := (IsWF.of_wellFoundedLT s).isPWO end LinearOrder end Set namespace Finset variable {r : α → α → Prop} @[simp] protected theorem partiallyWellOrderedOn [IsRefl α r] (s : Finset α) : (s : Set α).PartiallyWellOrderedOn r := s.finite_toSet.partiallyWellOrderedOn @[simp] protected theorem isPWO [Preorder α] (s : Finset α) : Set.IsPWO (↑s : Set α) := s.partiallyWellOrderedOn @[simp] protected theorem isWF [Preorder α] (s : Finset α) : Set.IsWF (↑s : Set α) := s.finite_toSet.isWF @[simp] protected theorem wellFoundedOn [IsStrictOrder α r] (s : Finset α) : Set.WellFoundedOn (↑s : Set α) r := letI := partialOrderOfSO r s.isWF theorem wellFoundedOn_sup [IsStrictOrder α r] (s : Finset ι) {f : ι → Set α} : (s.sup f).WellFoundedOn r ↔ ∀ i ∈ s, (f i).WellFoundedOn r := Finset.cons_induction_on s (by simp) fun a s ha hs => by simp [-sup_set_eq_biUnion, hs] theorem partiallyWellOrderedOn_sup (s : Finset ι) {f : ι → Set α} : (s.sup f).PartiallyWellOrderedOn r ↔ ∀ i ∈ s, (f i).PartiallyWellOrderedOn r := Finset.cons_induction_on s (by simp) fun a s ha hs => by simp [-sup_set_eq_biUnion, hs] theorem isWF_sup [Preorder α] (s : Finset ι) {f : ι → Set α} : (s.sup f).IsWF ↔ ∀ i ∈ s, (f i).IsWF := s.wellFoundedOn_sup theorem isPWO_sup [Preorder α] (s : Finset ι) {f : ι → Set α} : (s.sup f).IsPWO ↔ ∀ i ∈ s, (f i).IsPWO := s.partiallyWellOrderedOn_sup @[simp] theorem wellFoundedOn_bUnion [IsStrictOrder α r] (s : Finset ι) {f : ι → Set α} : (⋃ i ∈ s, f i).WellFoundedOn r ↔ ∀ i ∈ s, (f i).WellFoundedOn r := by simpa only [Finset.sup_eq_iSup] using s.wellFoundedOn_sup @[simp] theorem partiallyWellOrderedOn_bUnion (s : Finset ι) {f : ι → Set α} : (⋃ i ∈ s, f i).PartiallyWellOrderedOn r ↔ ∀ i ∈ s, (f i).PartiallyWellOrderedOn r := by simpa only [Finset.sup_eq_iSup] using s.partiallyWellOrderedOn_sup @[simp] theorem isWF_bUnion [Preorder α] (s : Finset ι) {f : ι → Set α} : (⋃ i ∈ s, f i).IsWF ↔ ∀ i ∈ s, (f i).IsWF := s.wellFoundedOn_bUnion @[simp] theorem isPWO_bUnion [Preorder α] (s : Finset ι) {f : ι → Set α} : (⋃ i ∈ s, f i).IsPWO ↔ ∀ i ∈ s, (f i).IsPWO := s.partiallyWellOrderedOn_bUnion end Finset namespace Set section Preorder variable [Preorder α] {s t : Set α} {a : α} /-- `Set.IsWF.min` returns a minimal element of a nonempty well-founded set. -/ noncomputable nonrec def IsWF.min (hs : IsWF s) (hn : s.Nonempty) : α := hs.min univ (nonempty_iff_univ_nonempty.1 hn.to_subtype) theorem IsWF.min_mem (hs : IsWF s) (hn : s.Nonempty) : hs.min hn ∈ s := (WellFounded.min hs univ (nonempty_iff_univ_nonempty.1 hn.to_subtype)).2 nonrec theorem IsWF.not_lt_min (hs : IsWF s) (hn : s.Nonempty) (ha : a ∈ s) : ¬a < hs.min hn := hs.not_lt_min univ (nonempty_iff_univ_nonempty.1 hn.to_subtype) (mem_univ (⟨a, ha⟩ : s)) theorem IsWF.min_of_subset_not_lt_min {hs : s.IsWF} {hsn : s.Nonempty} {ht : t.IsWF} {htn : t.Nonempty} (hst : s ⊆ t) : ¬hs.min hsn < ht.min htn := ht.not_lt_min htn (hst (min_mem hs hsn)) @[simp] theorem isWF_min_singleton (a) {hs : IsWF ({a} : Set α)} {hn : ({a} : Set α).Nonempty} : hs.min hn = a := eq_of_mem_singleton (IsWF.min_mem hs hn) theorem IsWF.min_eq_of_lt (hs : s.IsWF) (ha : a ∈ s) (hlt : ∀ b ∈ s, b ≠ a → a < b) : hs.min (nonempty_of_mem ha) = a := by by_contra h exact (hs.not_lt_min (nonempty_of_mem ha) ha) (hlt (hs.min (nonempty_of_mem ha)) (hs.min_mem (nonempty_of_mem ha)) h) end Preorder section PartialOrder variable [PartialOrder α] {s : Set α} {a : α} theorem IsWF.min_eq_of_le (hs : s.IsWF) (ha : a ∈ s) (hle : ∀ b ∈ s, a ≤ b) : hs.min (nonempty_of_mem ha) = a := (eq_of_le_of_not_lt (hle (hs.min (nonempty_of_mem ha)) (hs.min_mem (nonempty_of_mem ha))) (hs.not_lt_min (nonempty_of_mem ha) ha)).symm end PartialOrder section LinearOrder variable [LinearOrder α] {s t : Set α} {a : α} theorem IsWF.min_le (hs : s.IsWF) (hn : s.Nonempty) (ha : a ∈ s) : hs.min hn ≤ a := le_of_not_gt (hs.not_lt_min hn ha) theorem IsWF.le_min_iff (hs : s.IsWF) (hn : s.Nonempty) : a ≤ hs.min hn ↔ ∀ b, b ∈ s → a ≤ b := ⟨fun ha _b hb => le_trans ha (hs.min_le hn hb), fun h => h _ (hs.min_mem _)⟩ theorem IsWF.min_le_min_of_subset {hs : s.IsWF} {hsn : s.Nonempty} {ht : t.IsWF} {htn : t.Nonempty} (hst : s ⊆ t) : ht.min htn ≤ hs.min hsn := (IsWF.le_min_iff _ _).2 fun _b hb => ht.min_le htn (hst hb) theorem IsWF.min_union (hs : s.IsWF) (hsn : s.Nonempty) (ht : t.IsWF) (htn : t.Nonempty) : (hs.union ht).min (union_nonempty.2 (Or.intro_left _ hsn)) = Min.min (hs.min hsn) (ht.min htn) := by refine le_antisymm (le_min (IsWF.min_le_min_of_subset subset_union_left) (IsWF.min_le_min_of_subset subset_union_right)) ?_ rw [min_le_iff] exact ((mem_union _ _ _).1 ((hs.union ht).min_mem (union_nonempty.2 (.inl hsn)))).imp (hs.min_le _) (ht.min_le _) end LinearOrder end Set open Set section LocallyFiniteOrder variable {s : Set α} [Preorder α] [LocallyFiniteOrder α] theorem BddBelow.wellFoundedOn_lt : BddBelow s → s.WellFoundedOn (· < ·) := by rw [wellFoundedOn_iff_no_descending_seq] rintro ⟨a, ha⟩ f hf refine infinite_range_of_injective f.injective ?_ exact (finite_Icc a <| f 0).subset <| range_subset_iff.2 <| fun n => ⟨ha <| hf _, antitone_iff_forall_lt.2 (fun a b hab => (f.map_rel_iff.2 hab).le) <| Nat.zero_le _⟩ theorem BddAbove.wellFoundedOn_gt : BddAbove s → s.WellFoundedOn (· > ·) := fun h => h.dual.wellFoundedOn_lt theorem BddBelow.isWF : BddBelow s → IsWF s := BddBelow.wellFoundedOn_lt end LocallyFiniteOrder namespace Set.PartiallyWellOrderedOn variable {r : α → α → Prop} theorem bddAbove_preimage {s : Set α} (hs : s.PartiallyWellOrderedOn r) {f : ℕ → α} (hf : ∀ m n : ℕ, m < n → ¬ r (f m) (f n)) : BddAbove (s.preimage f) := by contrapose! hf rw [not_bddAbove_iff] at hf obtain ⟨φ, hφm, hφs⟩ := Nat.exists_strictMono_subsequence fun n ↦ (hf n).casesOn fun m h ↦ h.casesOn fun hs hmn ↦ Exists.intro m ⟨hmn, hs⟩ rw [partiallyWellOrderedOn_iff_exists_lt] at hs obtain ⟨m, n, hmn, hr⟩ := hs (fun n ↦ f (φ n)) hφs use (φ m), (φ n) exact ⟨hφm hmn, hr⟩ theorem exists_notMem_of_gt {s : Set α} (hs : s.PartiallyWellOrderedOn r) {f : ℕ → α} (hf : ∀ m n : ℕ, m < n → ¬ r (f m) (f n)) : ∃ k : ℕ, ∀ m, k < m → f m ∉ s := by have := hs.bddAbove_preimage hf contrapose! this simpa [not_bddAbove_iff, and_comm] @[deprecated (since := "2025-05-23")] alias exists_not_mem_of_gt := exists_notMem_of_gt -- TODO: move this material to the main file on WQOs. /-- In the context of partial well-orderings, a bad sequence is a nonincreasing sequence whose range is contained in a particular set `s`. One exists if and only if `s` is not partially well-ordered. -/ def IsBadSeq (r : α → α → Prop) (s : Set α) (f : ℕ → α) : Prop := (∀ n, f n ∈ s) ∧ ∀ m n : ℕ, m < n → ¬r (f m) (f n) theorem iff_forall_not_isBadSeq (r : α → α → Prop) (s : Set α) : s.PartiallyWellOrderedOn r ↔ ∀ f, ¬IsBadSeq r s f := by rw [partiallyWellOrderedOn_iff_exists_lt] exact forall_congr' fun f => by simp [IsBadSeq] /-- This indicates that every bad sequence `g` that agrees with `f` on the first `n` terms has `rk (f n) ≤ rk (g n)`. -/ def IsMinBadSeq (r : α → α → Prop) (rk : α → ℕ) (s : Set α) (n : ℕ) (f : ℕ → α) : Prop := ∀ g : ℕ → α, (∀ m : ℕ, m < n → f m = g m) → rk (g n) < rk (f n) → ¬IsBadSeq r s g /-- Given a bad sequence `f`, this constructs a bad sequence that agrees with `f` on the first `n` terms and is minimal at `n`. -/ noncomputable def minBadSeqOfBadSeq (r : α → α → Prop) (rk : α → ℕ) (s : Set α) (n : ℕ) (f : ℕ → α) (hf : IsBadSeq r s f) : { g : ℕ → α // (∀ m : ℕ, m < n → f m = g m) ∧ IsBadSeq r s g ∧ IsMinBadSeq r rk s n g } := by classical have h : ∃ (k : ℕ) (g : ℕ → α), (∀ m, m < n → f m = g m) ∧ IsBadSeq r s g ∧ rk (g n) = k := ⟨_, f, fun _ _ => rfl, hf, rfl⟩ obtain ⟨h1, h2, h3⟩ := Classical.choose_spec (Nat.find_spec h) refine ⟨Classical.choose (Nat.find_spec h), h1, by convert h2, fun g hg1 hg2 con => ?_⟩ refine Nat.find_min h ?_ ⟨g, fun m mn => (h1 m mn).trans (hg1 m mn), con, rfl⟩ rwa [← h3] theorem exists_min_bad_of_exists_bad (r : α → α → Prop) (rk : α → ℕ) (s : Set α) : (∃ f, IsBadSeq r s f) → ∃ f, IsBadSeq r s f ∧ ∀ n, IsMinBadSeq r rk s n f := by rintro ⟨f0, hf0 : IsBadSeq r s f0⟩ let fs : ∀ n : ℕ, { f : ℕ → α // IsBadSeq r s f ∧ IsMinBadSeq r rk s n f } := by refine Nat.rec ?_ fun n fn => ?_ · exact ⟨(minBadSeqOfBadSeq r rk s 0 f0 hf0).1, (minBadSeqOfBadSeq r rk s 0 f0 hf0).2.2⟩ · exact ⟨(minBadSeqOfBadSeq r rk s (n + 1) fn.1 fn.2.1).1, (minBadSeqOfBadSeq r rk s (n + 1) fn.1 fn.2.1).2.2⟩ have h : ∀ m n, m ≤ n → (fs m).1 m = (fs n).1 m := fun m n mn => by obtain ⟨k, rfl⟩ := Nat.exists_eq_add_of_le mn; clear mn induction k with | zero => rfl | succ k ih => rw [ih, (minBadSeqOfBadSeq r rk s (m + k + 1) (fs (m + k)).1 (fs (m + k)).2.1).2.1 m (Nat.lt_succ_iff.2 (Nat.add_le_add_left k.zero_le m))] rfl refine ⟨fun n => (fs n).1 n, ⟨fun n => (fs n).2.1.1 n, fun m n mn => ?_⟩, fun n g hg1 hg2 => ?_⟩ · dsimp rw [h m n mn.le] exact (fs n).2.1.2 m n mn · refine (fs n).2.2 g (fun m mn => ?_) hg2 rw [← h m n mn.le, ← hg1 m mn] theorem iff_not_exists_isMinBadSeq (rk : α → ℕ) {s : Set α} : s.PartiallyWellOrderedOn r ↔ ¬∃ f, IsBadSeq r s f ∧ ∀ n, IsMinBadSeq r rk s n f := by rw [iff_forall_not_isBadSeq, ← not_exists, not_congr] constructor · apply exists_min_bad_of_exists_bad · rintro ⟨f, hf1, -⟩ exact ⟨f, hf1⟩ /-- Higman's Lemma, which states that for any reflexive, transitive relation `r` which is partially well-ordered on a set `s`, the relation `List.SublistForall₂ r` is partially well-ordered on the set of lists of elements of `s`. That relation is defined so that `List.SublistForall₂ r l₁ l₂` whenever `l₁` related pointwise by `r` to a sublist of `l₂`. -/ theorem partiallyWellOrderedOn_sublistForall₂ (r : α → α → Prop) [IsPreorder α r] {s : Set α} (h : s.PartiallyWellOrderedOn r) : { l : List α | ∀ x, x ∈ l → x ∈ s }.PartiallyWellOrderedOn (List.SublistForall₂ r) := by rcases isEmpty_or_nonempty α · exact subsingleton_of_subsingleton.partiallyWellOrderedOn inhabit α rw [iff_not_exists_isMinBadSeq List.length] rintro ⟨f, hf1, hf2⟩ have hnil : ∀ n, f n ≠ List.nil := fun n con => hf1.2 n n.succ n.lt_succ_self (con.symm ▸ List.SublistForall₂.nil) obtain ⟨g, hg⟩ := h.exists_monotone_subseq fun n => hf1.1 n _ (List.head!_mem_self (hnil n)) have hf' := hf2 (g 0) (fun n => if n < g 0 then f n else List.tail (f (g (n - g 0)))) (fun m hm => (if_pos hm).symm) ?_ swap · simp only [if_neg (lt_irrefl (g 0)), Nat.sub_self] rw [List.length_tail, ← Nat.pred_eq_sub_one] exact Nat.pred_lt fun con => hnil _ (List.length_eq_zero_iff.1 con) rw [IsBadSeq] at hf' push_neg at hf' obtain ⟨m, n, mn, hmn⟩ := hf' fun n x hx => by split_ifs at hx with hn exacts [hf1.1 _ _ hx, hf1.1 _ _ (List.tail_subset _ hx)] by_cases hn : n < g 0 · apply hf1.2 m n mn rwa [if_pos hn, if_pos (mn.trans hn)] at hmn · obtain ⟨n', rfl⟩ := Nat.exists_eq_add_of_le (not_lt.1 hn) rw [if_neg hn, add_comm (g 0) n', Nat.add_sub_cancel_right] at hmn split_ifs at hmn with hm · apply hf1.2 m (g n') (lt_of_lt_of_le hm (g.monotone n'.zero_le)) exact _root_.trans hmn (List.tail_sublistForall₂_self _) · rw [← Nat.sub_lt_iff_lt_add' (le_of_not_gt hm)] at mn apply hf1.2 _ _ (g.lt_iff_lt.2 mn) rw [← List.cons_head!_tail (hnil (g (m - g 0))), ← List.cons_head!_tail (hnil (g n'))] exact List.SublistForall₂.cons (hg _ _ (le_of_lt mn)) hmn theorem subsetProdLex [PartialOrder α] [Preorder β] {s : Set (α ×ₗ β)} (hα : ((fun (x : α ×ₗ β) => (ofLex x).1) '' s).IsPWO) (hβ : ∀ a, {y | toLex (a, y) ∈ s}.IsPWO) : s.IsPWO := by rw [IsPWO, partiallyWellOrderedOn_iff_exists_lt] intro f hf rw [isPWO_iff_exists_monotone_subseq] at hα obtain ⟨g, hg⟩ : ∃ (g : (ℕ ↪o ℕ)), Monotone fun n => (ofLex f (g n)).1 := hα (fun n => (ofLex f n).1) (fun k => mem_image_of_mem (fun x => (ofLex x).1) (hf k)) have hhg : ∀ n, (ofLex f (g 0)).1 ≤ (ofLex f (g n)).1 := fun n => hg n.zero_le by_cases! hc : ∃ n, (ofLex f (g 0)).1 < (ofLex f (g n)).1 · obtain ⟨n, hn⟩ := hc use (g 0), (g n) constructor · by_contra hx simp_all · exact Prod.Lex.toLex_le_toLex.mpr <| .inl hn · have hhc : ∀ n, (ofLex f (g 0)).1 = (ofLex f (g n)).1 := by intro n exact (hhg n).eq_of_not_lt (hc n) obtain ⟨g', hg'⟩ : ∃ g' : ℕ ↪o ℕ, Monotone ((fun n ↦ (ofLex f (g (g' n))).2)) := by simp_rw [isPWO_iff_exists_monotone_subseq] at hβ apply hβ (ofLex f (g 0)).1 fun n ↦ (ofLex f (g n)).2 intro n rw [hhc n] simpa using hf _ use (g (g' 0)), (g (g' 1)) suffices (f (g (g' 0))) ≤ (f (g (g' 1))) by simpa · refine Prod.Lex.toLex_le_toLex.mpr <| .inr ⟨?_, ?_⟩ · exact (hhc (g' 0)).symm.trans (hhc (g' 1)) · exact hg' (Nat.zero_le 1) theorem imageProdLex [Preorder α] [Preorder β] {s : Set (α ×ₗ β)} (hαβ : s.IsPWO) : ((fun (x : α ×ₗ β) => (ofLex x).1)'' s).IsPWO := IsPWO.image_of_monotone hαβ Prod.Lex.monotone_fst theorem fiberProdLex [Preorder α] [Preorder β] {s : Set (α ×ₗ β)} (hαβ : s.IsPWO) (a : α) : {y | toLex (a, y) ∈ s}.IsPWO := by let f : α ×ₗ β → β := fun x => (ofLex x).2 have h : {y | toLex (a, y) ∈ s} = f '' (s ∩ (fun x ↦ (ofLex x).1) ⁻¹' {a}) := by ext x simp [f] rw [h] apply IsPWO.image_of_monotoneOn (hαβ.mono inter_subset_left) rintro b ⟨-, hb⟩ c ⟨-, hc⟩ hbc simp only [mem_preimage, mem_singleton_iff] at hb hc have : (ofLex b).1 < (ofLex c).1 ∨ (ofLex b).1 = (ofLex c).1 ∧ f b ≤ f c := Prod.Lex.toLex_le_toLex.mp hbc simp_all only [lt_self_iff_false, true_and, false_or] theorem ProdLex_iff [PartialOrder α] [Preorder β] {s : Set (α ×ₗ β)} : s.IsPWO ↔ ((fun (x : α ×ₗ β) ↦ (ofLex x).1) '' s).IsPWO ∧ ∀ a, {y | toLex (a, y) ∈ s}.IsPWO := ⟨fun h ↦ ⟨imageProdLex h, fiberProdLex h⟩, fun h ↦ subsetProdLex h.1 h.2⟩ end Set.PartiallyWellOrderedOn /-- A version of **Dickson's lemma** any subset of functions `Π s : σ, α s` is partially well ordered, when `σ` is a `Fintype` and each `α s` is a linear well order. This includes the classical case of Dickson's lemma that `ℕ ^ n` is a well partial order. Some generalizations would be possible based on this proof, to include cases where the target is partially well-ordered, and also to consider the case of `Set.PartiallyWellOrderedOn` instead of `Set.IsPWO`. -/ theorem Pi.isPWO {α : ι → Type*} [∀ i, LinearOrder (α i)] [∀ i, IsWellOrder (α i) (· < ·)] [Finite ι] (s : Set (∀ i, α i)) : s.IsPWO := by cases nonempty_fintype ι suffices ∀ (s : Finset ι) (f : ℕ → ∀ s, α s), ∃ g : ℕ ↪o ℕ, ∀ ⦃a b : ℕ⦄, a ≤ b → ∀ x, x ∈ s → (f ∘ g) a x ≤ (f ∘ g) b x by refine isPWO_iff_exists_monotone_subseq.2 fun f _ => ?_ simpa only [Finset.mem_univ, true_imp_iff] using this Finset.univ f refine Finset.cons_induction ?_ ?_ · intro f exists RelEmbedding.refl (· ≤ ·) simp only [IsEmpty.forall_iff, imp_true_iff, Finset.notMem_empty] · intro x s hx ih f obtain ⟨g, hg⟩ := (IsPWO.of_linearOrder univ).exists_monotone_subseq (f := (f · x)) mem_univ obtain ⟨g', hg'⟩ := ih (f ∘ g) refine ⟨g'.trans g, fun a b hab => (Finset.forall_mem_cons _ _).2 ?_⟩ exact ⟨hg (OrderHomClass.mono g' hab), hg' hab⟩ instance Pi.wellQuasiOrderedLE {α : ι → Type*} [∀ i, LinearOrder (α i)] [∀ i, WellFoundedLT (α i)] [Finite ι] : WellQuasiOrderedLE (∀ i, α i) := isPWO_univ_iff.mp (Pi.isPWO _) section ProdLex variable {rα : α → α → Prop} {rβ : β → β → Prop} {f : γ → α} {g : γ → β} {s : Set γ} /-- Stronger version of `WellFounded.prod_lex`. Instead of requiring `rβ on g` to be well-founded, we only require it to be well-founded on fibers of `f`. -/ theorem WellFounded.prod_lex_of_wellFoundedOn_fiber (hα : WellFounded (rα on f)) (hβ : ∀ a, (f ⁻¹' {a}).WellFoundedOn (rβ on g)) : WellFounded (Prod.Lex rα rβ on fun c => (f c, g c)) := by refine ((psigma_lex (wellFoundedOn_range.2 hα) fun a => hβ a).onFun (f := fun c => ⟨⟨_, c, rfl⟩, c, rfl⟩)).mono fun c c' h => ?_ obtain h' | h' := Prod.lex_iff.1 h · exact PSigma.Lex.left _ _ h' · dsimp only [InvImage, (· on ·)] at h' ⊢ convert PSigma.Lex.right (⟨_, c', rfl⟩ : range f) _ using 1; swap exacts [⟨c, h'.1⟩, PSigma.subtype_ext (Subtype.ext h'.1) rfl, h'.2] theorem Set.WellFoundedOn.prod_lex_of_wellFoundedOn_fiber (hα : s.WellFoundedOn (rα on f)) (hβ : ∀ a, (s ∩ f ⁻¹' {a}).WellFoundedOn (rβ on g)) : s.WellFoundedOn (Prod.Lex rα rβ on fun c => (f c, g c)) := WellFounded.prod_lex_of_wellFoundedOn_fiber hα fun a ↦ ((hβ a).onFun (f := fun x => ⟨x, x.1.2, x.2⟩)).mono (fun _ _ h ↦ ‹_›) end ProdLex section SigmaLex variable {rι : ι → ι → Prop} {rπ : ∀ i, π i → π i → Prop} {f : γ → ι} {g : ∀ i, γ → π i} {s : Set γ} /-- Stronger version of `PSigma.lex_wf`. Instead of requiring `rπ on g` to be well-founded, we only require it to be well-founded on fibers of `f`. -/ theorem WellFounded.sigma_lex_of_wellFoundedOn_fiber (hι : WellFounded (rι on f)) (hπ : ∀ i, (f ⁻¹' {i}).WellFoundedOn (rπ i on g i)) : WellFounded (Sigma.Lex rι rπ on fun c => ⟨f c, g (f c) c⟩) := by refine ((psigma_lex (wellFoundedOn_range.2 hι) fun a => hπ a).onFun (f := fun c => ⟨⟨_, c, rfl⟩, c, rfl⟩)).mono fun c c' h => ?_ obtain h' | ⟨h', h''⟩ := Sigma.lex_iff.1 h · exact PSigma.Lex.left _ _ h' · dsimp only [InvImage, (· on ·)] at h' ⊢ convert PSigma.Lex.right (⟨_, c', rfl⟩ : range f) _ using 1; swap · exact ⟨c, h'⟩ · exact PSigma.subtype_ext (Subtype.ext h') rfl · dsimp only [Subtype.coe_mk, Subrel, Order.Preimage] at * grind theorem Set.WellFoundedOn.sigma_lex_of_wellFoundedOn_fiber (hι : s.WellFoundedOn (rι on f)) (hπ : ∀ i, (s ∩ f ⁻¹' {i}).WellFoundedOn (rπ i on g i)) : s.WellFoundedOn (Sigma.Lex rι rπ on fun c => ⟨f c, g (f c) c⟩) := by change WellFounded (Sigma.Lex rι rπ on fun c : s => ⟨f c, g (f c) c⟩) exact @WellFounded.sigma_lex_of_wellFoundedOn_fiber _ s _ _ rπ (fun c => f c) (fun i c => g _ c) hι fun i => ((hπ i).onFun (f := fun x => ⟨x, x.1.2, x.2⟩)).mono (fun b c h => ‹_›) end SigmaLex
.lake/packages/mathlib/Mathlib/Order/CompleteLatticeIntervals.lean
import Mathlib.Order.ConditionallyCompleteLattice.Basic import Mathlib.Order.LatticeIntervals import Mathlib.Order.Interval.Set.OrdConnected /-! # Subtypes of conditionally complete linear orders In this file we give conditions on a subset of a conditionally complete linear order, to ensure that the subtype is itself conditionally complete. We check that an `OrdConnected` set satisfies these conditions. ## TODO Add appropriate instances for all `Set.Ixx`. This requires a refactor that will allow different default values for `sSup` and `sInf`. -/ assert_not_exists Multiset open Set variable {ι : Sort*} {α : Type*} (s : Set α) section SupSet variable [Preorder α] [SupSet α] open Classical in /-- `SupSet` structure on a nonempty subset `s` of a preorder with `SupSet`. This definition is non-canonical (it uses `default s`); it should be used only as here, as an auxiliary instance in the construction of the `ConditionallyCompleteLinearOrder` structure. -/ noncomputable def subsetSupSet [Inhabited s] : SupSet s where sSup t := if ht : t.Nonempty ∧ BddAbove t ∧ sSup ((↑) '' t : Set α) ∈ s then ⟨sSup ((↑) '' t : Set α), ht.2.2⟩ else default attribute [local instance] subsetSupSet open Classical in @[simp] theorem subset_sSup_def [Inhabited s] : @sSup s _ = fun t => if ht : t.Nonempty ∧ BddAbove t ∧ sSup ((↑) '' t : Set α) ∈ s then ⟨sSup ((↑) '' t : Set α), ht.2.2⟩ else default := rfl theorem subset_sSup_of_within [Inhabited s] {t : Set s} (h' : t.Nonempty) (h'' : BddAbove t) (h : sSup ((↑) '' t : Set α) ∈ s) : sSup ((↑) '' t : Set α) = (@sSup s _ t : α) := by simp [h, h', h''] theorem subset_sSup_emptyset [Inhabited s] : sSup (∅ : Set s) = default := by simp [sSup] theorem subset_sSup_of_not_bddAbove [Inhabited s] {t : Set s} (ht : ¬BddAbove t) : sSup t = default := by simp [sSup, ht] end SupSet section InfSet variable [Preorder α] [InfSet α] open Classical in /-- `InfSet` structure on a nonempty subset `s` of a preorder with `InfSet`. This definition is non-canonical (it uses `default s`); it should be used only as here, as an auxiliary instance in the construction of the `ConditionallyCompleteLinearOrder` structure. -/ noncomputable def subsetInfSet [Inhabited s] : InfSet s where sInf t := if ht : t.Nonempty ∧ BddBelow t ∧ sInf ((↑) '' t : Set α) ∈ s then ⟨sInf ((↑) '' t : Set α), ht.2.2⟩ else default attribute [local instance] subsetInfSet open Classical in @[simp] theorem subset_sInf_def [Inhabited s] : @sInf s _ = fun t => if ht : t.Nonempty ∧ BddBelow t ∧ sInf ((↑) '' t : Set α) ∈ s then ⟨sInf ((↑) '' t : Set α), ht.2.2⟩ else default := rfl theorem subset_sInf_of_within [Inhabited s] {t : Set s} (h' : t.Nonempty) (h'' : BddBelow t) (h : sInf ((↑) '' t : Set α) ∈ s) : sInf ((↑) '' t : Set α) = (@sInf s _ t : α) := by simp [h, h', h''] theorem subset_sInf_emptyset [Inhabited s] : sInf (∅ : Set s) = default := by simp [sInf] theorem subset_sInf_of_not_bddBelow [Inhabited s] {t : Set s} (ht : ¬BddBelow t) : sInf t = default := by simp [sInf, ht] end InfSet section OrdConnected variable [ConditionallyCompleteLinearOrder α] attribute [local instance] subsetSupSet attribute [local instance] subsetInfSet /-- For a nonempty subset of a conditionally complete linear order to be a conditionally complete linear order, it suffices that it contain the `sSup` of all its nonempty bounded-above subsets, and the `sInf` of all its nonempty bounded-below subsets. See note [reducible non-instances]. -/ noncomputable abbrev subsetConditionallyCompleteLinearOrder [Inhabited s] (h_Sup : ∀ {t : Set s} (_ : t.Nonempty) (_h_bdd : BddAbove t), sSup ((↑) '' t : Set α) ∈ s) (h_Inf : ∀ {t : Set s} (_ : t.Nonempty) (_h_bdd : BddBelow t), sInf ((↑) '' t : Set α) ∈ s) : ConditionallyCompleteLinearOrder s := { subsetSupSet s, subsetInfSet s, DistribLattice.toLattice, (inferInstance : LinearOrder s) with le_csSup := by rintro t c h_bdd hct rw [← Subtype.coe_le_coe, ← subset_sSup_of_within s ⟨c, hct⟩ h_bdd (h_Sup ⟨c, hct⟩ h_bdd)] exact (Subtype.mono_coe _).le_csSup_image hct h_bdd csSup_le := by rintro t B ht hB rw [← Subtype.coe_le_coe, ← subset_sSup_of_within s ht ⟨B, hB⟩ (h_Sup ht ⟨B, hB⟩)] exact (Subtype.mono_coe s).csSup_image_le ht hB le_csInf := by intro t B ht hB rw [← Subtype.coe_le_coe, ← subset_sInf_of_within s ht ⟨B, hB⟩ (h_Inf ht ⟨B, hB⟩)] exact (Subtype.mono_coe s).le_csInf_image ht hB csInf_le := by rintro t c h_bdd hct rw [← Subtype.coe_le_coe, ← subset_sInf_of_within s ⟨c, hct⟩ h_bdd (h_Inf ⟨c, hct⟩ h_bdd)] exact (Subtype.mono_coe s).csInf_image_le hct h_bdd csSup_of_not_bddAbove := fun t ht ↦ by simp [ht] csInf_of_not_bddBelow := fun t ht ↦ by simp [ht] } /-- The `sSup` function on a nonempty `OrdConnected` set `s` in a conditionally complete linear order takes values within `s`, for all nonempty bounded-above subsets of `s`. -/ theorem sSup_within_of_ordConnected {s : Set α} [hs : OrdConnected s] ⦃t : Set s⦄ (ht : t.Nonempty) (h_bdd : BddAbove t) : sSup ((↑) '' t : Set α) ∈ s := by obtain ⟨c, hct⟩ : ∃ c, c ∈ t := ht obtain ⟨B, hB⟩ : ∃ B, B ∈ upperBounds t := h_bdd refine hs.out c.2 B.2 ⟨?_, ?_⟩ · exact (Subtype.mono_coe s).le_csSup_image hct ⟨B, hB⟩ · exact (Subtype.mono_coe s).csSup_image_le ⟨c, hct⟩ hB /-- The `sInf` function on a nonempty `OrdConnected` set `s` in a conditionally complete linear order takes values within `s`, for all nonempty bounded-below subsets of `s`. -/ theorem sInf_within_of_ordConnected {s : Set α} [hs : OrdConnected s] ⦃t : Set s⦄ (ht : t.Nonempty) (h_bdd : BddBelow t) : sInf ((↑) '' t : Set α) ∈ s := by obtain ⟨c, hct⟩ : ∃ c, c ∈ t := ht obtain ⟨B, hB⟩ : ∃ B, B ∈ lowerBounds t := h_bdd refine hs.out B.2 c.2 ⟨?_, ?_⟩ · exact (Subtype.mono_coe s).le_csInf_image ⟨c, hct⟩ hB · exact (Subtype.mono_coe s).csInf_image_le hct ⟨B, hB⟩ /-- A nonempty `OrdConnected` set in a conditionally complete linear order is naturally a conditionally complete linear order. -/ noncomputable instance ordConnectedSubsetConditionallyCompleteLinearOrder [Inhabited s] [OrdConnected s] : ConditionallyCompleteLinearOrder s := subsetConditionallyCompleteLinearOrder s (fun h => sSup_within_of_ordConnected h) (fun h => sInf_within_of_ordConnected h) end OrdConnected section Icc open Classical in /-- Complete lattice structure on `Set.Icc` -/ noncomputable instance Set.Icc.completeLattice [ConditionallyCompleteLattice α] {a b : α} [Fact (a ≤ b)] : CompleteLattice (Set.Icc a b) where __ := (inferInstance : BoundedOrder ↑(Icc a b)) sSup S := if hS : S = ∅ then ⟨a, le_rfl, Fact.out⟩ else ⟨sSup ((↑) '' S), by rw [← Set.not_nonempty_iff_eq_empty, not_not] at hS refine ⟨?_, csSup_le (hS.image Subtype.val) (fun _ ⟨c, _, hc⟩ ↦ hc ▸ c.2.2)⟩ obtain ⟨c, hc⟩ := hS exact c.2.1.trans (le_csSup ⟨b, fun _ ⟨d, _, hd⟩ ↦ hd ▸ d.2.2⟩ ⟨c, hc, rfl⟩)⟩ le_sSup S c hc := by by_cases hS : S = ∅ <;> simp only [hS, dite_true, dite_false] · simp [hS] at hc · exact le_csSup ⟨b, fun _ ⟨d, _, hd⟩ ↦ hd ▸ d.2.2⟩ ⟨c, hc, rfl⟩ sSup_le S c hc := by by_cases hS : S = ∅ <;> simp only [hS, dite_true, dite_false] · exact c.2.1 · exact csSup_le ((Set.nonempty_iff_ne_empty.mpr hS).image Subtype.val) (fun _ ⟨d, h, hd⟩ ↦ hd ▸ hc d h) sInf S := if hS : S = ∅ then ⟨b, Fact.out, le_rfl⟩ else ⟨sInf ((↑) '' S), by rw [← Set.not_nonempty_iff_eq_empty, not_not] at hS refine ⟨le_csInf (hS.image Subtype.val) (fun _ ⟨c, _, hc⟩ ↦ hc ▸ c.2.1), ?_⟩ obtain ⟨c, hc⟩ := hS exact le_trans (csInf_le ⟨a, fun _ ⟨d, _, hd⟩ ↦ hd ▸ d.2.1⟩ ⟨c, hc, rfl⟩) c.2.2⟩ sInf_le S c hc := by by_cases hS : S = ∅ <;> simp only [hS, dite_true, dite_false] · simp [hS] at hc · exact csInf_le ⟨a, fun _ ⟨d, _, hd⟩ ↦ hd ▸ d.2.1⟩ ⟨c, hc, rfl⟩ le_sInf S c hc := by by_cases hS : S = ∅ <;> simp only [hS, dite_true, dite_false] · exact c.2.2 · exact le_csInf ((Set.nonempty_iff_ne_empty.mpr hS).image Subtype.val) (fun _ ⟨d, h, hd⟩ ↦ hd ▸ hc d h) /-- Complete linear order structure on `Set.Icc` -/ noncomputable instance [ConditionallyCompleteLinearOrder α] {a b : α} [Fact (a ≤ b)] : CompleteLinearOrder (Set.Icc a b) := { Set.Icc.completeLattice, Subtype.instLinearOrder _, LinearOrder.toBiheytingAlgebra _ with } lemma Set.Icc.coe_sSup [ConditionallyCompleteLattice α] {a b : α} (h : a ≤ b) {S : Set (Set.Icc a b)} (hS : S.Nonempty) : have : Fact (a ≤ b) := ⟨h⟩ ↑(sSup S) = sSup ((↑) '' S : Set α) := congrArg Subtype.val (dif_neg hS.ne_empty) lemma Set.Icc.coe_sInf [ConditionallyCompleteLattice α] {a b : α} (h : a ≤ b) {S : Set (Set.Icc a b)} (hS : S.Nonempty) : have : Fact (a ≤ b) := ⟨h⟩ ↑(sInf S) = sInf ((↑) '' S : Set α) := congrArg Subtype.val (dif_neg hS.ne_empty) lemma Set.Icc.coe_iSup [ConditionallyCompleteLattice α] {a b : α} (h : a ≤ b) [Nonempty ι] {S : ι → Set.Icc a b} : have : Fact (a ≤ b) := ⟨h⟩ ↑(iSup S) = (⨆ i, S i : α) := (Set.Icc.coe_sSup h (range_nonempty S)).trans (congrArg sSup (range_comp Subtype.val S).symm) lemma Set.Icc.coe_iInf [ConditionallyCompleteLattice α] {a b : α} (h : a ≤ b) [Nonempty ι] {S : ι → Set.Icc a b} : have : Fact (a ≤ b) := ⟨h⟩ ↑(iInf S) = (⨅ i, S i : α) := (Set.Icc.coe_sInf h (range_nonempty S)).trans (congrArg sInf (range_comp Subtype.val S).symm) end Icc namespace Set.Iic variable [CompleteLattice α] {a : α} instance instCompleteLattice : CompleteLattice (Iic a) where sSup S := ⟨sSup ((↑) '' S), by simpa using fun b hb _ ↦ hb⟩ sInf S := ⟨a ⊓ sInf ((↑) '' S), by simp⟩ le_sSup _ _ hb := le_sSup <| mem_image_of_mem Subtype.val hb sSup_le _ _ hb := sSup_le <| fun _ ⟨c, hc, hc'⟩ ↦ hc' ▸ hb c hc sInf_le _ _ hb := inf_le_of_right_le <| sInf_le <| mem_image_of_mem Subtype.val hb le_sInf _ b hb := le_inf_iff.mpr ⟨b.property, le_sInf fun _ ⟨d, hd, hd'⟩ ↦ hd' ▸ hb d hd⟩ le_top := by simp bot_le := by simp variable (S : Set <| Iic a) (f : ι → Iic a) (p : ι → Prop) @[simp] theorem coe_sSup : (↑(sSup S) : α) = sSup ((↑) '' S) := rfl @[simp] theorem coe_iSup : (↑(⨆ i, f i) : α) = ⨆ i, (f i : α) := by rw [iSup, coe_sSup]; congr; ext; simp theorem coe_biSup : (↑(⨆ i, ⨆ (_ : p i), f i) : α) = ⨆ i, ⨆ (_ : p i), (f i : α) := by simp @[simp] theorem coe_sInf : (↑(sInf S) : α) = a ⊓ sInf ((↑) '' S) := rfl @[simp] theorem coe_iInf : (↑(⨅ i, f i) : α) = a ⊓ ⨅ i, (f i : α) := by rw [iInf, coe_sInf]; congr; ext; simp theorem coe_biInf : (↑(⨅ i, ⨅ (_ : p i), f i) : α) = a ⊓ ⨅ i, ⨅ (_ : p i), (f i : α) := by cases isEmpty_or_nonempty ι · simp · simp_rw [coe_iInf, ← inf_iInf, ← inf_assoc, inf_idem] end Set.Iic
.lake/packages/mathlib/Mathlib/Order/CountableDenseLinearOrder.lean
import Mathlib.Order.Ideal import Mathlib.Data.Finset.Max /-! # The back and forth method and countable dense linear orders ## Results Suppose `α β` are linear orders, with `α` countable and `β` dense, nontrivial. Then there is an order embedding `α ↪ β`. If in addition `α` is dense, nonempty, without endpoints and `β` is countable, without endpoints, then we can upgrade this to an order isomorphism `α ≃ β`. The idea for both results is to consider "partial isomorphisms", which identify a finite subset of `α` with a finite subset of `β`, and prove that for any such partial isomorphism `f` and `a : α`, we can extend `f` to include `a` in its domain. ## References https://en.wikipedia.org/wiki/Back-and-forth_method ## Tags back and forth, dense, countable, order -/ noncomputable section namespace Order variable {α β : Type*} [LinearOrder α] [LinearOrder β] /-- Suppose `α` is a nonempty dense linear order without endpoints, and suppose `lo`, `hi`, are finite subsets with all of `lo` strictly before `hi`. Then there is an element of `α` strictly between `lo` and `hi`. -/ theorem exists_between_finsets [DenselyOrdered α] [NoMinOrder α] [NoMaxOrder α] [nonem : Nonempty α] (lo hi : Finset α) (lo_lt_hi : ∀ x ∈ lo, ∀ y ∈ hi, x < y) : ∃ m : α, (∀ x ∈ lo, x < m) ∧ ∀ y ∈ hi, m < y := if nlo : lo.Nonempty then if nhi : hi.Nonempty then -- both sets are nonempty, use `DenselyOrdered` Exists.elim (exists_between (lo_lt_hi _ (Finset.max'_mem _ nlo) _ (Finset.min'_mem _ nhi))) fun m hm ↦ ⟨m, fun x hx ↦ lt_of_le_of_lt (Finset.le_max' lo x hx) hm.1, fun y hy ↦ lt_of_lt_of_le hm.2 (Finset.min'_le hi y hy)⟩ else-- upper set is empty, use `NoMaxOrder` Exists.elim (exists_gt (Finset.max' lo nlo)) fun m hm ↦ ⟨m, fun x hx ↦ lt_of_le_of_lt (Finset.le_max' lo x hx) hm, fun y hy ↦ (nhi ⟨y, hy⟩).elim⟩ else if nhi : hi.Nonempty then -- lower set is empty, use `NoMinOrder` Exists.elim (exists_lt (Finset.min' hi nhi)) fun m hm ↦ ⟨m, fun x hx ↦ (nlo ⟨x, hx⟩).elim, fun y hy ↦ lt_of_lt_of_le hm (Finset.min'_le hi y hy)⟩ else -- both sets are empty, use `Nonempty` nonem.elim fun m ↦ ⟨m, fun x hx ↦ (nlo ⟨x, hx⟩).elim, fun y hy ↦ (nhi ⟨y, hy⟩).elim⟩ lemma exists_orderEmbedding_insert [DenselyOrdered β] [NoMinOrder β] [NoMaxOrder β] [nonem : Nonempty β] (S : Finset α) (f : S ↪o β) (a : α) : ∃ (g : (insert a S : Finset α) ↪o β), g ∘ (Set.inclusion ((S.subset_insert a) : ↑S ⊆ ↑(insert a S))) = f := by let Slt := {x ∈ S.attach | x.val < a}.image f let Sgt := {x ∈ S.attach | a < x.val}.image f obtain ⟨b, hb, hb'⟩ := Order.exists_between_finsets Slt Sgt (fun x hx y hy => by simp only [Finset.mem_image, Finset.mem_filter, Finset.mem_attach, true_and, Subtype.exists, exists_and_left, Slt, Sgt] at hx hy obtain ⟨_, hx, _, rfl⟩ := hx obtain ⟨_, hy, _, rfl⟩ := hy exact f.strictMono (hx.trans hy)) refine ⟨OrderEmbedding.ofStrictMono (fun (x : (insert a S : Finset α)) => if hx : x.1 ∈ S then f ⟨x.1, hx⟩ else b) ?_, ?_⟩ · rintro ⟨x, hx⟩ ⟨y, hy⟩ hxy if hxS : x ∈ S then if hyS : y ∈ S then simpa only [hxS, hyS, ↓reduceDIte, OrderEmbedding.lt_iff_lt, Subtype.mk_lt_mk] else obtain rfl := Finset.eq_of_mem_insert_of_notMem hy hyS simp only [hxS, hyS, ↓reduceDIte] exact hb _ (Finset.mem_image_of_mem _ (Finset.mem_filter.2 ⟨Finset.mem_attach _ _, hxy⟩)) else obtain rfl := Finset.eq_of_mem_insert_of_notMem hx hxS if hyS : y ∈ S then simp only [hxS, hyS, ↓reduceDIte] exact hb' _ (Finset.mem_image_of_mem _ (Finset.mem_filter.2 ⟨Finset.mem_attach _ _, hxy⟩)) else simp only [Finset.eq_of_mem_insert_of_notMem hy hyS, lt_self_iff_false] at hxy · ext x simp only [OrderEmbedding.coe_ofStrictMono, Function.comp_apply, Finset.coe_mem, ↓reduceDIte, Subtype.coe_eta] variable (α β) /-- The type of partial order isomorphisms between `α` and `β` defined on finite subsets. A partial order isomorphism is encoded as a finite subset of `α × β`, consisting of pairs which should be identified. -/ def PartialIso : Type _ := { f : Finset (α × β) // ∀ p ∈ f, ∀ q ∈ f, cmp (Prod.fst p) (Prod.fst q) = cmp (Prod.snd p) (Prod.snd q) } namespace PartialIso instance : Inhabited (PartialIso α β) := ⟨⟨∅, fun _p h _q ↦ (Finset.notMem_empty _ h).elim⟩⟩ instance : Preorder (PartialIso α β) := Subtype.preorder _ variable {α β} /-- For each `a`, we can find a `b` in the codomain, such that `a`'s relation to the domain of `f` is `b`'s relation to the image of `f`. Thus, if `a` is not already in `f`, then we can extend `f` by sending `a` to `b`. -/ theorem exists_across [DenselyOrdered β] [NoMinOrder β] [NoMaxOrder β] [Nonempty β] (f : PartialIso α β) (a : α) : ∃ b : β, ∀ p ∈ f.val, cmp (Prod.fst p) a = cmp (Prod.snd p) b := by by_cases h : ∃ b, (a, b) ∈ f.val · obtain ⟨b, hb⟩ := h exact ⟨b, fun p hp ↦ f.prop _ hp _ hb⟩ have : ∀ x ∈ {p ∈ f.val | p.fst < a}.image Prod.snd, ∀ y ∈ {p ∈ f.val | a < p.fst}.image Prod.snd, x < y := by intro x hx y hy rw [Finset.mem_image] at hx hy rcases hx with ⟨p, hp1, rfl⟩ rcases hy with ⟨q, hq1, rfl⟩ rw [Finset.mem_filter] at hp1 hq1 rw [← lt_iff_lt_of_cmp_eq_cmp (f.prop _ hp1.1 _ hq1.1)] exact lt_trans hp1.right hq1.right obtain ⟨b, hb⟩ := exists_between_finsets _ _ this use b rintro ⟨p1, p2⟩ hp have : p1 ≠ a := fun he ↦ h ⟨p2, he ▸ hp⟩ rcases lt_or_gt_of_ne this with hl | hr · have : p1 < a ∧ p2 < b := ⟨hl, hb.1 _ (Finset.mem_image.mpr ⟨(p1, p2), Finset.mem_filter.mpr ⟨hp, hl⟩, rfl⟩)⟩ rw [← cmp_eq_lt_iff, ← cmp_eq_lt_iff] at this exact this.1.trans this.2.symm · have : a < p1 ∧ b < p2 := ⟨hr, hb.2 _ (Finset.mem_image.mpr ⟨(p1, p2), Finset.mem_filter.mpr ⟨hp, hr⟩, rfl⟩)⟩ rw [← cmp_eq_gt_iff, ← cmp_eq_gt_iff] at this exact this.1.trans this.2.symm /-- A partial isomorphism between `α` and `β` is also a partial isomorphism between `β` and `α`. -/ protected def comm : PartialIso α β → PartialIso β α := Subtype.map (Finset.image (Equiv.prodComm _ _)) fun f hf p hp q hq ↦ Eq.symm <| hf ((Equiv.prodComm α β).symm p) (by rw [← Finset.mem_coe, Finset.coe_image, Equiv.image_eq_preimage_symm] at hp rwa [← Finset.mem_coe]) ((Equiv.prodComm α β).symm q) (by rw [← Finset.mem_coe, Finset.coe_image, Equiv.image_eq_preimage_symm] at hq rwa [← Finset.mem_coe]) variable (β) /-- The set of partial isomorphisms defined at `a : α`, together with a proof that any partial isomorphism can be extended to one defined at `a`. -/ def definedAtLeft [DenselyOrdered β] [NoMinOrder β] [NoMaxOrder β] [Nonempty β] (a : α) : Cofinal (PartialIso α β) where carrier := {f | ∃ b : β, (a, b) ∈ f.val} isCofinal f := by obtain ⟨b, a_b⟩ := exists_across f a refine ⟨⟨insert (a, b) f.val, fun p hp q hq ↦ ?_⟩, ⟨b, Finset.mem_insert_self _ _⟩, Finset.subset_insert _ _⟩ rw [Finset.mem_insert] at hp hq rcases hp with (rfl | pf) <;> rcases hq with (rfl | qf) · simp only [cmp_self_eq_eq] · rw [cmp_eq_cmp_symm] exact a_b _ qf · exact a_b _ pf · exact f.prop _ pf _ qf variable (α) {β} /-- The set of partial isomorphisms defined at `b : β`, together with a proof that any partial isomorphism can be extended to include `b`. We prove this by symmetry. -/ def definedAtRight [DenselyOrdered α] [NoMinOrder α] [NoMaxOrder α] [Nonempty α] (b : β) : Cofinal (PartialIso α β) where carrier := {f | ∃ a, (a, b) ∈ f.val} isCofinal f := by rcases (definedAtLeft α b).isCofinal f.comm with ⟨f', ⟨a, ha⟩, hl⟩ refine ⟨f'.comm, ⟨a, ?_⟩, ?_⟩ · change (a, b) ∈ f'.val.image _ rwa [← Finset.mem_coe, Finset.coe_image, Equiv.image_eq_preimage_symm] · change _ ⊆ f'.val.image _ rwa [← Finset.coe_subset, Finset.coe_image, ← Equiv.symm_image_subset, ← Finset.coe_image, Finset.coe_subset] variable {α} /-- Given an ideal which intersects `definedAtLeft β a`, pick `b : β` such that some partial function in the ideal maps `a` to `b`. -/ def funOfIdeal [DenselyOrdered β] [NoMinOrder β] [NoMaxOrder β] [Nonempty β] (a : α) (I : Ideal (PartialIso α β)) : (∃ f, f ∈ definedAtLeft β a ∧ f ∈ I) → { b // ∃ f ∈ I, (a, b) ∈ Subtype.val f } := Classical.indefiniteDescription _ ∘ fun ⟨f, ⟨b, hb⟩, hf⟩ ↦ ⟨b, f, hf, hb⟩ /-- Given an ideal which intersects `definedAtRight α b`, pick `a : α` such that some partial function in the ideal maps `a` to `b`. -/ def invOfIdeal [DenselyOrdered α] [NoMinOrder α] [NoMaxOrder α] [Nonempty α] (b : β) (I : Ideal (PartialIso α β)) : (∃ f, f ∈ definedAtRight α b ∧ f ∈ I) → { a // ∃ f ∈ I, (a, b) ∈ Subtype.val f } := Classical.indefiniteDescription _ ∘ fun ⟨f, ⟨a, ha⟩, hf⟩ ↦ ⟨a, f, hf, ha⟩ end PartialIso open PartialIso -- variable (α β) /-- Any countable linear order embeds in any nontrivial dense linear order. -/ theorem embedding_from_countable_to_dense [Countable α] [DenselyOrdered β] [Nontrivial β] : Nonempty (α ↪o β) := by cases nonempty_encodable α rcases exists_pair_lt β with ⟨x, y, hxy⟩ obtain ⟨a, ha⟩ := exists_between hxy haveI : Nonempty (Set.Ioo x y) := ⟨⟨a, ha⟩⟩ let our_ideal : Ideal (PartialIso α _) := idealOfCofinals default (definedAtLeft (Set.Ioo x y)) let F a := funOfIdeal a our_ideal (cofinal_meets_idealOfCofinals _ _ a) refine ⟨RelEmbedding.trans (OrderEmbedding.ofStrictMono (fun a ↦ (F a).val) fun a₁ a₂ ↦ ?_) (OrderEmbedding.subtype _)⟩ rcases (F a₁).prop with ⟨f, hf, ha₁⟩ rcases (F a₂).prop with ⟨g, hg, ha₂⟩ rcases our_ideal.directed _ hf _ hg with ⟨m, _hm, fm, gm⟩ exact (lt_iff_lt_of_cmp_eq_cmp <| m.prop (a₁, _) (fm ha₁) (a₂, _) (gm ha₂)).mp /-- Any two countable dense, nonempty linear orders without endpoints are order isomorphic. This is also known as **Cantor's isomorphism theorem**. -/ theorem iso_of_countable_dense [Countable α] [DenselyOrdered α] [NoMinOrder α] [NoMaxOrder α] [Nonempty α] [Countable β] [DenselyOrdered β] [NoMinOrder β] [NoMaxOrder β] [Nonempty β] : Nonempty (α ≃o β) := by cases nonempty_encodable α cases nonempty_encodable β let to_cofinal : α ⊕ β → Cofinal (PartialIso α β) := fun p ↦ Sum.recOn p (definedAtLeft β) (definedAtRight α) let our_ideal : Ideal (PartialIso α β) := idealOfCofinals default to_cofinal let F a := funOfIdeal a our_ideal (cofinal_meets_idealOfCofinals _ to_cofinal (Sum.inl a)) let G b := invOfIdeal b our_ideal (cofinal_meets_idealOfCofinals _ to_cofinal (Sum.inr b)) exact ⟨OrderIso.ofCmpEqCmp (fun a ↦ (F a).val) (fun b ↦ (G b).val) fun a b ↦ by rcases (F a).prop with ⟨f, hf, ha⟩ rcases (G b).prop with ⟨g, hg, hb⟩ rcases our_ideal.directed _ hf _ hg with ⟨m, _, fm, gm⟩ exact m.prop (a, _) (fm ha) (_, b) (gm hb)⟩ end Order
.lake/packages/mathlib/Mathlib/Order/KonigLemma.lean
import Mathlib.Data.Fintype.Pigeonhole import Mathlib.Order.Atoms.Finite import Mathlib.Order.Grade import Mathlib.Tactic.ApplyFun /-! # Kőnig's infinity lemma Kőnig's infinity lemma is most often stated as a graph theory result: every infinite, locally finite connected graph contains an infinite path. It has links to computability and proof theory, and it has a number of formulations. In practice, most applications are not to an abstract graph, but to a concrete collection of objects that are organized in a graph-like way, often where the graph is a rooted tree representing a graded order. In fact, the lemma is most easily stated and proved in terms of covers in a strongly atomic order rather than a graph; in this setting, the proof is almost trivial. A common formulation of Kőnig's lemma is in terms of directed systems, with the grading explicitly represented using an `ℕ`-indexed family of types, which we also provide in this module. This is a specialization of the much more general `nonempty_sections_of_finite_cofiltered_system`, which goes through topology and category theory, but here it is stated and proved independently with much fewer dependencies. We leave the explicitly graph-theoretic version of the statement as TODO. ## Main Results * `exists_seq_covby_of_forall_covby_finite` : Kőnig's lemma for strongly atomic orders. * `exists_orderEmbedding_covby_of_forall_covby_finite` : Kőnig's lemma, where the sequence is given as an `OrderEmbedding` instead of a function. * `exists_orderEmbedding_covby_of_forall_covby_finite_of_bot` : Kőnig's lemma where the sequence starts at the minimum of an infinite type. * `exist_seq_forall_proj_of_forall_finite` : Kőnig's lemma for inverse systems, proved using the above applied to an order on a sigma-type `(i : ℕ) × α i`. ## TODO Formulate the lemma as a statement about graphs. -/ open Set section Sequence variable {α : Type*} [PartialOrder α] [IsStronglyAtomic α] {b : α} /-- **Kőnig's infinity lemma** : if each element in a strongly atomic order is covered by only finitely many others, and `b` is an element with infinitely many things above it, then there is a sequence starting with `b` in which each element is covered by the next. -/ theorem exists_seq_covby_of_forall_covby_finite (hfin : ∀ (a : α), {x | a ⋖ x}.Finite) (hb : (Ici b).Infinite) : ∃ f : ℕ → α, f 0 = b ∧ ∀ i, f i ⋖ f (i + 1) := let h := fun a : {a : α // (Ici a).Infinite} ↦ exists_covby_infinite_Ici_of_infinite_Ici a.2 (hfin a) let ks : ℕ → {a : α // (Ici a).Infinite} := Nat.rec ⟨b, hb⟩ fun _ a ↦ ⟨_, (h a).choose_spec.2⟩ ⟨fun i ↦ (ks i).1, by simp [ks], fun i ↦ by simpa using (h (ks i)).choose_spec.1⟩ /-- The sequence given by Kőnig's lemma as an order embedding -/ theorem exists_orderEmbedding_covby_of_forall_covby_finite (hfin : ∀ (a : α), {x | a ⋖ x}.Finite) (hb : (Ici b).Infinite) : ∃ f : ℕ ↪o α, f 0 = b ∧ ∀ i, f i ⋖ f (i + 1) := by obtain ⟨f, hf⟩ := exists_seq_covby_of_forall_covby_finite hfin hb exact ⟨OrderEmbedding.ofStrictMono f (strictMono_nat_of_lt_succ (fun i ↦ (hf.2 i).lt)), hf⟩ /-- A version of Kőnig's lemma where the sequence starts at the minimum of an infinite order. -/ theorem exists_orderEmbedding_covby_of_forall_covby_finite_of_bot [OrderBot α] [Infinite α] (hfin : ∀ (a : α), {x | a ⋖ x}.Finite) : ∃ f : ℕ ↪o α, f 0 = ⊥ ∧ ∀ i, f i ⋖ f (i + 1) := exists_orderEmbedding_covby_of_forall_covby_finite hfin (by simpa using infinite_univ) theorem GradeMinOrder.exists_nat_orderEmbedding_of_forall_covby_finite [GradeMinOrder ℕ α] [OrderBot α] [Infinite α] (hfin : ∀ (a : α), {x | a ⋖ x}.Finite) : ∃ f : ℕ ↪o α, f 0 = ⊥ ∧ (∀ i, f i ⋖ f (i + 1)) ∧ ∀ i, grade ℕ (f i) = i := by obtain ⟨f, h0, hf⟩ := exists_orderEmbedding_covby_of_forall_covby_finite_of_bot hfin refine ⟨f, h0, hf, fun i ↦ ?_⟩ induction i with | zero => simp [h0] | succ i ih => simpa [Order.covBy_iff_add_one_eq, ih, eq_comm] using CovBy.grade ℕ <| hf i end Sequence section Graded /-- A formulation of Kőnig's infinity lemma, useful in applications. Given a sequence `α 0, α 1, ...` of nonempty types with `α 0` finite, and a well-behaved family of projections `π : α j → α i` for all `i ≤ j`, if each term in each `α i` is the projection of only finitely many terms in `α (i+1)`, then we can find a sequence `(f 0 : α 0), (f 1 : α 1), ...` where `f i` is the projection of `f j` for all `i ≤ j`. In a typical application, the `α i` are function types with increasingly large domains, and `π hij (f : α j)` is the restriction of the domain of `f` to that of `α i`. In this case, the sequence given by the lemma is essentially a function whose domain is the limit of the `α i`. See also `nonempty_sections_of_finite_cofiltered_system`. -/ theorem exists_seq_forall_proj_of_forall_finite {α : ℕ → Type*} [Finite (α 0)] [∀ i, Nonempty (α i)] (π : {i j : ℕ} → (hij : i ≤ j) → α j → α i) (π_refl : ∀ ⦃i⦄ (a : α i), π rfl.le a = a) (π_trans : ∀ ⦃i j k⦄ (hij : i ≤ j) (hjk : j ≤ k) a, π hij (π hjk a) = π (hij.trans hjk) a) (hfin : ∀ i a, {b : α (i+1) | π (Nat.le_add_right i 1) b = a}.Finite) : ∃ f : (i : ℕ) → α i, ∀ ⦃i j⦄ (hij : i ≤ j), π hij (f j) = f i := by set αs := (i : ℕ) × α i let _ : PartialOrder αs := { le := fun a b ↦ ∃ h, π h b.2 = a.2 le_refl := fun a ↦ ⟨rfl.le, π_refl _⟩ le_trans := fun _ _ c h h' ↦ ⟨h.1.trans h'.1, by rw [← π_trans h.1 h'.1 c.2, h'.2, h.2]⟩ le_antisymm := by rintro ⟨i, a⟩ ⟨j, b⟩ ⟨hij : i ≤ j, hab : π hij b = a⟩ ⟨hji : j ≤ i, hba : π hji a = b⟩ obtain rfl := hij.antisymm hji rw [show a = b by rwa [π_refl] at hba] } have hcovby : ∀ {a b : αs}, a ⋖ b ↔ a ≤ b ∧ a.1 + 1 = b.1 := by simp only [αs, covBy_iff_lt_and_eq_or_eq, lt_iff_le_and_ne, ne_eq, Sigma.forall, and_assoc, and_congr_right_iff, or_iff_not_imp_left] rintro i a j b ⟨h : i ≤ j, rfl : π h b = a⟩ refine ⟨fun ⟨hne, h'⟩ ↦ ?_, ?_⟩ · have hle' : i + 1 ≤ j := h.lt_of_ne <| by rintro rfl; simp [π_refl] at hne exact congr_arg Sigma.fst <| h' (i + 1) (π hle' b) ⟨by simp, by rw [π_trans]⟩ ⟨hle', by simp⟩ (fun h ↦ by simp at h) rintro rfl refine ⟨fun h ↦ by simp at h, ?_⟩ rintro j c ⟨hij : i ≤ j, hcb : π _ c = π _ b⟩ ⟨hji : j ≤ i + 1, rfl : π hji b = c⟩ hne replace hne := show i ≠ j by rintro rfl; contradiction obtain rfl := hji.antisymm (hij.lt_of_ne hne) rw [π_refl] have : IsStronglyAtomic αs := by simp_rw [isStronglyAtomic_iff, lt_iff_le_and_ne, hcovby] rintro ⟨i, a⟩ ⟨j, b⟩ ⟨⟨hij : i ≤ j, h2 : π hij b = a⟩, hne⟩ have hle : i + 1 ≤ j := hij.lt_of_ne (by rintro rfl; simp [← h2, π_refl] at hne) exact ⟨⟨_, π hle b⟩, ⟨⟨by simp, by rw [π_trans, ← h2]⟩, by simp⟩, ⟨hle, by simp⟩⟩ obtain ⟨a₀, ha₀, ha₀inf⟩ : ∃ a₀ : αs, a₀.1 = 0 ∧ (Ici a₀).Infinite := by obtain ⟨a₀, ha₀⟩ := Finite.exists_infinite_fiber (fun (a : αs) ↦ π (zero_le a.1) a.2) refine ⟨⟨0, a₀⟩, rfl, (infinite_coe_iff.1 ha₀).mono ?_⟩ simp only [αs, subset_def, mem_preimage, mem_singleton_iff, mem_Ici, Sigma.forall] exact fun i x h ↦ ⟨zero_le i, h⟩ have hfin : ∀ (a : αs), {x | a ⋖ x}.Finite := by refine fun ⟨i, a⟩ ↦ ((hfin i a).image (fun b ↦ ⟨_, b⟩)).subset ?_ simp only [αs, hcovby, subset_def, mem_setOf_eq, mem_image, and_imp, Sigma.forall] exact fun j b ⟨_, _⟩ hj ↦ ⟨π hj.le b, by rwa [π_trans], by cases hj; rw [π_refl]⟩ obtain ⟨f, hf0, hf⟩ := exists_orderEmbedding_covby_of_forall_covby_finite hfin ha₀inf have hr : ∀ i, (f i).1 = i := Nat.rec (by rw [hf0, ha₀]) (fun i ih ↦ by rw [← (hcovby.1 (hf i)).2, ih]) refine ⟨fun i ↦ by rw [← hr i]; exact (f i).2, fun i j hij ↦ ?_⟩ convert (f.monotone hij).2 <;> simp [hr] end Graded
.lake/packages/mathlib/Mathlib/Order/Part.lean
import Mathlib.Data.Part import Mathlib.Order.Hom.Basic import Mathlib.Tactic.Common /-! # Monotonicity of monadic operations on `Part` -/ open Part variable {α β γ : Type*} [Preorder α] section bind variable {f : α → Part β} {g : α → β → Part γ} lemma Monotone.partBind (hf : Monotone f) (hg : Monotone g) : Monotone fun x ↦ (f x).bind (g x) := by rintro x y h a simp only [and_imp, Part.mem_bind_iff, exists_imp] exact fun b hb ha ↦ ⟨b, hf h _ hb, hg h _ _ ha⟩ lemma Antitone.partBind (hf : Antitone f) (hg : Antitone g) : Antitone fun x ↦ (f x).bind (g x) := by rintro x y h a simp only [and_imp, Part.mem_bind_iff, exists_imp] exact fun b hb ha ↦ ⟨b, hf h _ hb, hg h _ _ ha⟩ end bind section map variable {f : β → γ} {g : α → Part β} lemma Monotone.partMap (hg : Monotone g) : Monotone fun x ↦ (g x).map f := by simpa only [← bind_some_eq_map] using hg.partBind monotone_const lemma Antitone.partMap (hg : Antitone g) : Antitone fun x ↦ (g x).map f := by simpa only [← bind_some_eq_map] using hg.partBind antitone_const end map section seq variable {β γ : Type _} {f : α → Part (β → γ)} {g : α → Part β} lemma Monotone.partSeq (hf : Monotone f) (hg : Monotone g) : Monotone fun x ↦ f x <*> g x := by simpa only [seq_eq_bind_map] using hf.partBind <| Monotone.of_apply₂ fun _ ↦ hg.partMap lemma Antitone.partSeq (hf : Antitone f) (hg : Antitone g) : Antitone fun x ↦ f x <*> g x := by simpa only [seq_eq_bind_map] using hf.partBind <| Antitone.of_apply₂ fun _ ↦ hg.partMap end seq namespace OrderHom /-- `Part.bind` as a monotone function -/ @[simps] def partBind (f : α →o Part β) (g : α →o β → Part γ) : α →o Part γ where toFun x := (f x).bind (g x) monotone' := f.2.partBind g.2 end OrderHom
.lake/packages/mathlib/Mathlib/Order/Synonym.lean
import Mathlib.Logic.Equiv.Defs import Mathlib.Logic.Nontrivial.Defs import Mathlib.Order.Basic /-! # Type synonyms This file provides three type synonyms for order theory: * `OrderDual α`: Type synonym of `α` to equip it with the dual order (`a ≤ b` becomes `b ≤ a`). * `Lex α`: Type synonym of `α` to equip it with its lexicographic order. The precise meaning depends on the type we take the lex of. Examples include `Prod`, `Sigma`, `List`, `Finset`. * `Colex α`: Type synonym of `α` to equip it with its colexicographic order. The precise meaning depends on the type we take the colex of. Examples include `Finset`. ## Notation `αᵒᵈ` is notation for `OrderDual α`. The general rule for notation of `Lex` types is to append `ₗ` to the usual notation. ## Implementation notes One should not abuse definitional equality between `α` and `αᵒᵈ`/`Lex α`. Instead, explicit coercions should be inserted: * `OrderDual`: `OrderDual.toDual : α → αᵒᵈ` and `OrderDual.ofDual : αᵒᵈ → α` * `Lex`: `toLex : α → Lex α` and `ofLex : Lex α → α`. * `Colex`: `toColex : α → Colex α` and `ofColex : Colex α → α`. ## See also This file is similar to `Algebra.Group.TypeTags`. -/ variable {α : Type*} /-! ### Order dual -/ namespace OrderDual instance [h : Nontrivial α] : Nontrivial αᵒᵈ := h /-- `toDual` is the identity function to the `OrderDual` of a linear order. -/ def toDual : α ≃ αᵒᵈ := Equiv.refl _ /-- `ofDual` is the identity function from the `OrderDual` of a linear order. -/ def ofDual : αᵒᵈ ≃ α := Equiv.refl _ @[simp] theorem toDual_symm_eq : (@toDual α).symm = ofDual := rfl @[simp] theorem ofDual_symm_eq : (@ofDual α).symm = toDual := rfl @[simp] theorem toDual_ofDual (a : αᵒᵈ) : toDual (ofDual a) = a := rfl @[simp] theorem ofDual_toDual (a : α) : ofDual (toDual a) = a := rfl theorem toDual_inj {a b : α} : toDual a = toDual b ↔ a = b := by simp theorem ofDual_inj {a b : αᵒᵈ} : ofDual a = ofDual b ↔ a = b := by simp @[ext] lemma ext {a b : αᵒᵈ} (h : ofDual a = ofDual b) : a = b := h @[simp] theorem toDual_le_toDual [LE α] {a b : α} : toDual a ≤ toDual b ↔ b ≤ a := Iff.rfl @[simp] theorem toDual_lt_toDual [LT α] {a b : α} : toDual a < toDual b ↔ b < a := Iff.rfl @[simp] theorem ofDual_le_ofDual [LE α] {a b : αᵒᵈ} : ofDual a ≤ ofDual b ↔ b ≤ a := Iff.rfl @[simp] theorem ofDual_lt_ofDual [LT α] {a b : αᵒᵈ} : ofDual a < ofDual b ↔ b < a := Iff.rfl theorem le_toDual [LE α] {a : αᵒᵈ} {b : α} : a ≤ toDual b ↔ b ≤ ofDual a := Iff.rfl theorem lt_toDual [LT α] {a : αᵒᵈ} {b : α} : a < toDual b ↔ b < ofDual a := Iff.rfl theorem toDual_le [LE α] {a : α} {b : αᵒᵈ} : toDual a ≤ b ↔ ofDual b ≤ a := Iff.rfl theorem toDual_lt [LT α] {a : α} {b : αᵒᵈ} : toDual a < b ↔ ofDual b < a := Iff.rfl /-- Recursor for `αᵒᵈ`. -/ @[elab_as_elim] protected def rec {motive : αᵒᵈ → Sort*} (toDual : ∀ a : α, motive (toDual a)) : ∀ a : αᵒᵈ, motive a := toDual @[simp] protected theorem «forall» {p : αᵒᵈ → Prop} : (∀ a, p a) ↔ ∀ a, p (toDual a) := Iff.rfl @[simp] protected theorem «exists» {p : αᵒᵈ → Prop} : (∃ a, p a) ↔ ∃ a, p (toDual a) := Iff.rfl alias ⟨_, _root_.LE.le.dual⟩ := toDual_le_toDual alias ⟨_, _root_.LT.lt.dual⟩ := toDual_lt_toDual alias ⟨_, _root_.LE.le.ofDual⟩ := ofDual_le_ofDual alias ⟨_, _root_.LT.lt.ofDual⟩ := ofDual_lt_ofDual end OrderDual /-! ### Lexicographic order -/ /-- A type synonym to equip a type with its lexicographic order. -/ def Lex (α : Type*) := α /-- `toLex` is the identity function to the `Lex` of a type. -/ @[match_pattern] def toLex : α ≃ Lex α := Equiv.refl _ /-- `ofLex` is the identity function from the `Lex` of a type. -/ @[match_pattern] def ofLex : Lex α ≃ α := Equiv.refl _ @[simp] theorem toLex_symm_eq : (@toLex α).symm = ofLex := rfl @[simp] theorem ofLex_symm_eq : (@ofLex α).symm = toLex := rfl @[simp] theorem toLex_ofLex (a : Lex α) : toLex (ofLex a) = a := rfl @[simp] theorem ofLex_toLex (a : α) : ofLex (toLex a) = a := rfl theorem toLex_inj {a b : α} : toLex a = toLex b ↔ a = b := by simp theorem ofLex_inj {a b : Lex α} : ofLex a = ofLex b ↔ a = b := by simp instance (α : Type*) [BEq α] : BEq (Lex α) where beq a b := ofLex a == ofLex b instance (α : Type*) [BEq α] [LawfulBEq α] : LawfulBEq (Lex α) := inferInstanceAs (LawfulBEq α) instance (α : Type*) [DecidableEq α] : DecidableEq (Lex α) := inferInstanceAs (DecidableEq α) instance (α : Type*) [Inhabited α] : Inhabited (Lex α) := inferInstanceAs (Inhabited α) instance {α γ} [H : CoeFun α γ] : CoeFun (Lex α) γ where coe f := H.coe (ofLex f) /-- A recursor for `Lex`. Use as `induction x`. -/ @[elab_as_elim, induction_eliminator, cases_eliminator] protected def Lex.rec {β : Lex α → Sort*} (h : ∀ a, β (toLex a)) : ∀ a, β a := fun a => h (ofLex a) @[simp] lemma Lex.forall {p : Lex α → Prop} : (∀ a, p a) ↔ ∀ a, p (toLex a) := Iff.rfl @[simp] lemma Lex.exists {p : Lex α → Prop} : (∃ a, p a) ↔ ∃ a, p (toLex a) := Iff.rfl /-! ### Colexicographic order -/ /-- A type synonym to equip a type with its lexicographic order. -/ def Colex (α : Type*) := α /-- `toColex` is the identity function to the `Colex` of a type. -/ @[match_pattern] def toColex : α ≃ Colex α := Equiv.refl _ /-- `ofColex` is the identity function from the `Colex` of a type. -/ @[match_pattern] def ofColex : Colex α ≃ α := Equiv.refl _ @[simp] theorem toColex_symm_eq : (@toColex α).symm = ofColex := rfl @[simp] theorem ofColex_symm_eq : (@ofColex α).symm = toColex := rfl @[simp] theorem toColex_ofColex (a : Colex α) : toColex (ofColex a) = a := rfl @[simp] theorem ofColex_toColex (a : α) : ofColex (toColex a) = a := rfl theorem toColex_inj {a b : α} : toColex a = toColex b ↔ a = b := by simp theorem ofColex_inj {a b : Colex α} : ofColex a = ofColex b ↔ a = b := by simp instance (α : Type*) [BEq α] : BEq (Colex α) where beq a b := ofColex a == ofColex b instance (α : Type*) [BEq α] [LawfulBEq α] : LawfulBEq (Colex α) := inferInstanceAs (LawfulBEq α) instance (α : Type*) [DecidableEq α] : DecidableEq (Colex α) := inferInstanceAs (DecidableEq α) instance (α : Type*) [Inhabited α] : Inhabited (Colex α) := inferInstanceAs (Inhabited α) instance {α γ} [H : CoeFun α γ] : CoeFun (Colex α) γ where coe f := H.coe (ofColex f) /-- A recursor for `Colex`. Use as `induction x`. -/ @[elab_as_elim, induction_eliminator, cases_eliminator] protected def Colex.rec {β : Colex α → Sort*} (h : ∀ a, β (toColex a)) : ∀ a, β a := fun a => h (ofColex a) @[simp] lemma Colex.forall {p : Colex α → Prop} : (∀ a, p a) ↔ ∀ a, p (toColex a) := Iff.rfl @[simp] lemma Colex.exists {p : Colex α → Prop} : (∃ a, p a) ↔ ∃ a, p (toColex a) := Iff.rfl
.lake/packages/mathlib/Mathlib/Order/Comparable.lean
import Mathlib.Order.Antisymmetrization /-! # Comparability and incomparability relations Two values in a preorder are said to be comparable whenever `a ≤ b` or `b ≤ a`. We define both the comparability and incomparability relations. In a linear order, `CompRel (· ≤ ·) a b` is always true, and `IncompRel (· ≤ ·) a b` is always false. ## Implementation notes Although comparability and incomparability are negations of each other, both relations are convenient in different contexts, and as such, it's useful to keep them distinct. To move from one to the other, use `not_compRel_iff` and `not_incompRel_iff`. ## Main declarations * `CompRel`: The comparability relation. `CompRel r a b` means that `a` and `b` is related in either direction by `r`. * `IncompRel`: The incomparability relation. `IncompRel r a b` means that `a` and `b` are related in neither direction by `r`. ## Todo These definitions should be linked to `IsChain` and `IsAntichain`. -/ open Function variable {α : Type*} {a b c d : α} /-! ### Comparability -/ section Relation variable {r : α → α → Prop} /-- The comparability relation `CompRel r a b` means that either `r a b` or `r b a`. -/ def CompRel (r : α → α → Prop) (a b : α) : Prop := r a b ∨ r b a theorem CompRel.of_rel (h : r a b) : CompRel r a b := Or.inl h theorem CompRel.of_rel_symm (h : r b a) : CompRel r a b := Or.inr h theorem compRel_swap (r : α → α → Prop) : CompRel (swap r) = CompRel r := funext₂ fun _ _ ↦ propext or_comm theorem compRel_swap_apply (r : α → α → Prop) : CompRel (swap r) a b ↔ CompRel r a b := or_comm @[simp, refl] theorem CompRel.refl (r : α → α → Prop) [IsRefl α r] (a : α) : CompRel r a a := .of_rel (_root_.refl _) theorem CompRel.rfl [IsRefl α r] : CompRel r a a := .refl .. instance [IsRefl α r] : IsRefl α (CompRel r) where refl := .refl r @[symm] theorem CompRel.symm : CompRel r a b → CompRel r b a := Or.symm instance : IsSymm α (CompRel r) where symm _ _ := CompRel.symm theorem compRel_comm {a b : α} : CompRel r a b ↔ CompRel r b a := comm instance CompRel.decidableRel [DecidableRel r] : DecidableRel (CompRel r) := fun _ _ ↦ inferInstanceAs (Decidable (_ ∨ _)) theorem AntisymmRel.compRel (h : AntisymmRel r a b) : CompRel r a b := Or.inl h.1 @[simp] theorem IsTotal.compRel [IsTotal α r] (a b : α) : CompRel r a b := IsTotal.total a b end Relation section LE variable [LE α] theorem CompRel.of_le (h : a ≤ b) : CompRel (· ≤ ·) a b := .of_rel h theorem CompRel.of_ge (h : b ≤ a) : CompRel (· ≤ ·) a b := .of_rel_symm h alias LE.le.compRel := CompRel.of_le alias LE.le.compRel_symm := CompRel.of_ge end LE section Preorder variable [Preorder α] theorem CompRel.of_lt (h : a < b) : CompRel (· ≤ ·) a b := h.le.compRel theorem CompRel.of_gt (h : b < a) : CompRel (· ≤ ·) a b := h.le.compRel_symm alias LT.lt.compRel := CompRel.of_lt alias LT.lt.compRel_symm := CompRel.of_gt @[trans] theorem CompRel.of_compRel_of_antisymmRel (h₁ : CompRel (· ≤ ·) a b) (h₂ : AntisymmRel (· ≤ ·) b c) : CompRel (· ≤ ·) a c := by obtain (h | h) := h₁ · exact (h.trans h₂.le).compRel · exact (h₂.ge.trans h).compRel_symm alias CompRel.trans_antisymmRel := CompRel.of_compRel_of_antisymmRel instance : @Trans α α α (CompRel (· ≤ ·)) (AntisymmRel (· ≤ ·)) (CompRel (· ≤ ·)) where trans := CompRel.of_compRel_of_antisymmRel @[trans] theorem CompRel.of_antisymmRel_of_compRel (h₁ : AntisymmRel (· ≤ ·) a b) (h₂ : CompRel (· ≤ ·) b c) : CompRel (· ≤ ·) a c := (h₂.symm.trans_antisymmRel h₁.symm).symm alias AntisymmRel.trans_compRel := CompRel.of_antisymmRel_of_compRel instance : @Trans α α α (AntisymmRel (· ≤ ·)) (CompRel (· ≤ ·)) (CompRel (· ≤ ·)) where trans := CompRel.of_antisymmRel_of_compRel theorem AntisymmRel.compRel_congr (h₁ : AntisymmRel (· ≤ ·) a b) (h₂ : AntisymmRel (· ≤ ·) c d) : CompRel (· ≤ ·) a c ↔ CompRel (· ≤ ·) b d where mp h := (h₁.symm.trans_compRel h).trans_antisymmRel h₂ mpr h := (h₁.trans_compRel h).trans_antisymmRel h₂.symm theorem AntisymmRel.compRel_congr_left (h : AntisymmRel (· ≤ ·) a b) : CompRel (· ≤ ·) a c ↔ CompRel (· ≤ ·) b c := h.compRel_congr .rfl theorem AntisymmRel.compRel_congr_right (h : AntisymmRel (· ≤ ·) b c) : CompRel (· ≤ ·) a b ↔ CompRel (· ≤ ·) a c := AntisymmRel.rfl.compRel_congr h end Preorder /-- A partial order where any two elements are comparable is a linear order. -/ def linearOrderOfComprel [PartialOrder α] [decLE : DecidableLE α] [decLT : DecidableLT α] [decEq : DecidableEq α] (h : ∀ a b : α, CompRel (· ≤ ·) a b) : LinearOrder α where le_total := h toDecidableLE := decLE toDecidableEq := decEq toDecidableLT := decLT /-! ### Incomparability relation -/ section Relation variable (r : α → α → Prop) /-- The incomparability relation `IncompRel r a b` means `¬ r a b` and `¬ r b a`. -/ def IncompRel (a b : α) : Prop := ¬ r a b ∧ ¬ r b a @[simp] theorem antisymmRel_compl : AntisymmRel rᶜ = IncompRel r := rfl theorem antisymmRel_compl_apply : AntisymmRel rᶜ a b ↔ IncompRel r a b := .rfl @[simp] theorem incompRel_compl : IncompRel rᶜ = AntisymmRel r := by simp [← antisymmRel_compl, compl] @[simp] theorem incompRel_compl_apply : IncompRel rᶜ a b ↔ AntisymmRel r a b := by simp theorem incompRel_swap : IncompRel (swap r) = IncompRel r := antisymmRel_swap rᶜ theorem incompRel_swap_apply : IncompRel (swap r) a b ↔ IncompRel r a b := antisymmRel_swap_apply rᶜ @[simp, refl] theorem IncompRel.refl [IsIrrefl α r] (a : α) : IncompRel r a a := AntisymmRel.refl rᶜ a variable {r} in theorem IncompRel.rfl [IsIrrefl α r] {a : α} : IncompRel r a a := .refl .. instance [IsIrrefl α r] : IsRefl α (IncompRel r) where refl := .refl r variable {r} @[symm] theorem IncompRel.symm : IncompRel r a b → IncompRel r b a := And.symm instance : IsSymm α (IncompRel r) where symm _ _ := IncompRel.symm theorem incompRel_comm {a b : α} : IncompRel r a b ↔ IncompRel r b a := comm instance IncompRel.decidableRel [DecidableRel r] : DecidableRel (IncompRel r) := fun _ _ ↦ inferInstanceAs (Decidable (¬ _ ∧ ¬ _)) theorem IncompRel.not_antisymmRel (h : IncompRel r a b) : ¬ AntisymmRel r a b := fun h' ↦ h.1 h'.1 theorem AntisymmRel.not_incompRel (h : AntisymmRel r a b) : ¬ IncompRel r a b := fun h' ↦ h'.1 h.1 theorem not_compRel_iff : ¬ CompRel r a b ↔ IncompRel r a b := by simp [CompRel, IncompRel] theorem not_incompRel_iff : ¬ IncompRel r a b ↔ CompRel r a b := by rw [← not_compRel_iff, not_not] @[simp] theorem IsTotal.not_incompRel [IsTotal α r] (a b : α) : ¬ IncompRel r a b := by rw [not_incompRel_iff] exact IsTotal.compRel a b end Relation section LE variable [LE α] theorem IncompRel.not_le (h : IncompRel (· ≤ ·) a b) : ¬ a ≤ b := h.1 theorem IncompRel.not_ge (h : IncompRel (· ≤ ·) a b) : ¬ b ≤ a := h.2 theorem LE.le.not_incompRel (h : a ≤ b) : ¬ IncompRel (· ≤ ·) a b := fun h' ↦ h'.not_le h end LE section Preorder variable [Preorder α] theorem IncompRel.not_lt (h : IncompRel (· ≤ ·) a b) : ¬ a < b := mt le_of_lt h.not_le theorem IncompRel.not_gt (h : IncompRel (· ≤ ·) a b) : ¬ b < a := mt le_of_lt h.not_ge theorem LT.lt.not_incompRel (h : a < b) : ¬ IncompRel (· ≤ ·) a b := fun h' ↦ h'.not_lt h theorem not_le_iff_lt_or_incompRel : ¬ b ≤ a ↔ a < b ∨ IncompRel (· ≤ ·) a b := by rw [lt_iff_le_not_ge, IncompRel] tauto /-- Exactly one of the following is true. -/ theorem lt_or_antisymmRel_or_gt_or_incompRel (a b : α) : a < b ∨ AntisymmRel (· ≤ ·) a b ∨ b < a ∨ IncompRel (· ≤ ·) a b := by simp_rw [lt_iff_le_not_ge] tauto @[trans] theorem incompRel_of_incompRel_of_antisymmRel (h₁ : IncompRel (· ≤ ·) a b) (h₂ : AntisymmRel (· ≤ ·) b c) : IncompRel (· ≤ ·) a c := ⟨fun h ↦ h₁.not_le (h.trans h₂.ge), fun h ↦ h₁.not_ge (h₂.le.trans h)⟩ alias IncompRel.trans_antisymmRel := incompRel_of_incompRel_of_antisymmRel instance : @Trans α α α (IncompRel (· ≤ ·)) (AntisymmRel (· ≤ ·)) (IncompRel (· ≤ ·)) where trans := incompRel_of_incompRel_of_antisymmRel @[trans] theorem incompRel_of_antisymmRel_of_incompRel (h₁ : AntisymmRel (· ≤ ·) a b) (h₂ : IncompRel (· ≤ ·) b c) : IncompRel (· ≤ ·) a c := (h₂.symm.trans_antisymmRel h₁.symm).symm alias AntisymmRel.trans_incompRel := incompRel_of_antisymmRel_of_incompRel instance : @Trans α α α (AntisymmRel (· ≤ ·)) (IncompRel (· ≤ ·)) (IncompRel (· ≤ ·)) where trans := incompRel_of_antisymmRel_of_incompRel theorem AntisymmRel.incompRel_congr (h₁ : AntisymmRel (· ≤ ·) a b) (h₂ : AntisymmRel (· ≤ ·) c d) : IncompRel (· ≤ ·) a c ↔ IncompRel (· ≤ ·) b d where mp h := (h₁.symm.trans_incompRel h).trans_antisymmRel h₂ mpr h := (h₁.trans_incompRel h).trans_antisymmRel h₂.symm theorem AntisymmRel.incompRel_congr_left (h : AntisymmRel (· ≤ ·) a b) : IncompRel (· ≤ ·) a c ↔ IncompRel (· ≤ ·) b c := h.incompRel_congr AntisymmRel.rfl theorem AntisymmRel.incompRel_congr_right (h : AntisymmRel (· ≤ ·) b c) : IncompRel (· ≤ ·) a b ↔ IncompRel (· ≤ ·) a c := AntisymmRel.rfl.incompRel_congr h end Preorder /-- Exactly one of the following is true. -/ theorem lt_or_eq_or_gt_or_incompRel [PartialOrder α] (a b : α) : a < b ∨ a = b ∨ b < a ∨ IncompRel (· ≤ ·) a b := by simpa using lt_or_antisymmRel_or_gt_or_incompRel a b
.lake/packages/mathlib/Mathlib/Order/Birkhoff.lean
import Mathlib.Data.Fintype.Order import Mathlib.Order.Interval.Finset.Basic import Mathlib.Order.Irreducible import Mathlib.Order.UpperLower.Closure /-! # Birkhoff representation This file proves two facts which together are commonly referred to as "Birkhoff representation": 1. Any nonempty finite partial order is isomorphic to the partial order of sup-irreducible elements in its lattice of lower sets. 2. Any nonempty finite distributive lattice is isomorphic to the lattice of lower sets of its partial order of sup-irreducible elements. ## Main declarations For a finite nonempty partial order `α`: * `OrderEmbedding.supIrredLowerSet`: `α` is isomorphic to the order of its irreducible lower sets. If `α` is moreover a distributive lattice: * `OrderIso.lowerSetSupIrred`: `α` is isomorphic to the lattice of lower sets of its irreducible elements. * `OrderEmbedding.birkhoffSet`, `OrderEmbedding.birkhoffFinset`: Order embedding of `α` into the powerset lattice of its irreducible elements. * `LatticeHom.birkhoffSet`, `LatticeHom.birkhoffFinet`: Same as the previous two, but bundled as an injective lattice homomorphism. * `exists_birkhoff_representation`: `α` embeds into some powerset algebra. You should prefer using this over the explicit Birkhoff embedding because the Birkhoff embedding is littered with decidability footguns that this existential-packaged version can afford to avoid. ## See also These results form the object part of finite Stone duality: the functorial contravariant equivalence between the category of finite distributive lattices and the category of finite partial orders. TODO: extend to morphisms. ## References * [G. Birkhoff, *Rings of sets*][birkhoff1937] ## Tags birkhoff, representation, stone duality, lattice embedding -/ open Finset Function OrderDual UpperSet LowerSet variable {α : Type*} section PartialOrder variable [PartialOrder α] namespace UpperSet variable {s : UpperSet α} @[simp] lemma infIrred_Ici (a : α) : InfIrred (Ici a) := by refine ⟨fun h ↦ Ici_ne_top h.eq_top, fun s t hst ↦ ?_⟩ have := mem_Ici_iff.2 (le_refl a) rw [← hst] at this exact this.imp (fun ha ↦ le_antisymm (le_Ici.2 ha) <| hst.ge.trans inf_le_left) fun ha ↦ le_antisymm (le_Ici.2 ha) <| hst.ge.trans inf_le_right variable [Finite α] @[simp] lemma infIrred_iff_of_finite : InfIrred s ↔ ∃ a, Ici a = s := by refine ⟨fun hs ↦ ?_, ?_⟩ · obtain ⟨a, ha, has⟩ := (s : Set α).toFinite.exists_minimal (coe_nonempty.2 hs.ne_top) exact ⟨a, (hs.2 <| erase_inf_Ici ha fun b hb ↦ le_imp_eq_iff_le_imp_ge.2 <| has hb).resolve_left (lt_erase.2 ha).ne'⟩ · rintro ⟨a, rfl⟩ exact infIrred_Ici _ end UpperSet namespace LowerSet variable {s : LowerSet α} @[simp] lemma supIrred_Iic (a : α) : SupIrred (Iic a) := by refine ⟨fun h ↦ Iic_ne_bot h.eq_bot, fun s t hst ↦ ?_⟩ have := mem_Iic_iff.2 (le_refl a) rw [← hst] at this exact this.imp (fun ha ↦ (le_sup_left.trans_eq hst).antisymm <| Iic_le.2 ha) fun ha ↦ (le_sup_right.trans_eq hst).antisymm <| Iic_le.2 ha variable [Finite α] @[simp] lemma supIrred_iff_of_finite : SupIrred s ↔ ∃ a, Iic a = s := by refine ⟨fun hs ↦ ?_, ?_⟩ · obtain ⟨a, ha, has⟩ := (s : Set α).toFinite.exists_maximal (coe_nonempty.2 hs.ne_bot) exact ⟨a, (hs.2 <| erase_sup_Iic ha fun b hb ↦ le_imp_eq_iff_le_imp_ge'.2 <| has hb).resolve_left (erase_lt.2 ha).ne⟩ · rintro ⟨a, rfl⟩ exact supIrred_Iic _ end LowerSet namespace OrderEmbedding /-- The **Birkhoff Embedding** of a finite partial order as sup-irreducible elements in its lattice of lower sets. -/ def supIrredLowerSet : α ↪o {s : LowerSet α // SupIrred s} where toFun a := ⟨Iic a, supIrred_Iic _⟩ inj' _ := by simp map_rel_iff' := by simp /-- The **Birkhoff Embedding** of a finite partial order as inf-irreducible elements in its lattice of lower sets. -/ def infIrredUpperSet : α ↪o {s : UpperSet α // InfIrred s} where toFun a := ⟨Ici a, infIrred_Ici _⟩ inj' _ := by simp map_rel_iff' := by simp @[simp] lemma supIrredLowerSet_apply (a : α) : supIrredLowerSet a = ⟨Iic a, supIrred_Iic _⟩ := rfl @[simp] lemma infIrredUpperSet_apply (a : α) : infIrredUpperSet a = ⟨Ici a, infIrred_Ici _⟩ := rfl variable [Finite α] lemma supIrredLowerSet_surjective : Surjective (supIrredLowerSet (α := α)) := by aesop (add simp Surjective) lemma infIrredUpperSet_surjective : Surjective (infIrredUpperSet (α := α)) := by aesop (add simp Surjective) end OrderEmbedding namespace OrderIso variable [Finite α] /-- **Birkhoff Representation for partial orders.** Any partial order is isomorphic to the partial order of sup-irreducible elements in its lattice of lower sets. -/ noncomputable def supIrredLowerSet : α ≃o {s : LowerSet α // SupIrred s} := RelIso.ofSurjective _ OrderEmbedding.supIrredLowerSet_surjective /-- **Birkhoff Representation for partial orders.** Any partial order is isomorphic to the partial order of inf-irreducible elements in its lattice of upper sets. -/ noncomputable def infIrredUpperSet : α ≃o {s : UpperSet α // InfIrred s} := RelIso.ofSurjective _ OrderEmbedding.infIrredUpperSet_surjective @[simp] lemma supIrredLowerSet_apply (a : α) : supIrredLowerSet a = ⟨Iic a, supIrred_Iic _⟩ := rfl @[simp] lemma infIrredUpperSet_apply (a : α) : infIrredUpperSet a = ⟨Ici a, infIrred_Ici _⟩ := rfl end OrderIso end PartialOrder namespace OrderIso section SemilatticeSup variable [SemilatticeSup α] [OrderBot α] [Finite α] @[simp] lemma supIrredLowerSet_symm_apply (s : {s : LowerSet α // SupIrred s}) [Fintype s] : supIrredLowerSet.symm s = (s.1 : Set α).toFinset.sup id := by classical obtain ⟨s, hs⟩ := s obtain ⟨a, rfl⟩ := supIrred_iff_of_finite.1 hs cases nonempty_fintype α have : LocallyFiniteOrder α := Fintype.toLocallyFiniteOrder simp [symm_apply_eq] end SemilatticeSup section SemilatticeInf variable [SemilatticeInf α] [OrderTop α] [Finite α] @[simp] lemma infIrredUpperSet_symm_apply (s : {s : UpperSet α // InfIrred s}) [Fintype s] : infIrredUpperSet.symm s = (s.1 : Set α).toFinset.inf id := by classical obtain ⟨s, hs⟩ := s obtain ⟨a, rfl⟩ := infIrred_iff_of_finite.1 hs cases nonempty_fintype α have : LocallyFiniteOrder α := Fintype.toLocallyFiniteOrder simp [symm_apply_eq] end SemilatticeInf end OrderIso section DistribLattice variable [DistribLattice α] [Fintype α] [@DecidablePred α SupIrred] open Classical in /-- **Birkhoff Representation for finite distributive lattices**. Any nonempty finite distributive lattice is isomorphic to the lattice of lower sets of its sup-irreducible elements. -/ noncomputable def OrderIso.lowerSetSupIrred [OrderBot α] : α ≃o LowerSet {a : α // SupIrred a} := Equiv.toOrderIso { toFun := fun a ↦ ⟨{b | ↑b ≤ a}, fun _ _ hcb hba ↦ hba.trans' hcb⟩ invFun := fun s ↦ (s : Set {a : α // SupIrred a}).toFinset.sup (↑) left_inv := fun a ↦ by refine le_antisymm (Finset.sup_le fun b ↦ Set.mem_toFinset.1) ?_ obtain ⟨s, rfl, hs⟩ := exists_supIrred_decomposition a exact Finset.sup_le fun i hi ↦ le_sup_of_le (b := ⟨i, hs hi⟩) (Set.mem_toFinset.2 <| le_sup (f := id) hi) le_rfl right_inv := fun s ↦ by ext a dsimp refine ⟨fun ha ↦ ?_, fun ha ↦ ?_⟩ · obtain ⟨i, hi, ha⟩ := a.2.supPrime.le_finset_sup.1 ha exact s.lower ha (Set.mem_toFinset.1 hi) · dsimp exact le_sup (Set.mem_toFinset.2 ha) } (fun _ _ hbc _ ↦ le_trans' hbc) fun _ _ hst ↦ Finset.sup_mono <| Set.toFinset_mono hst namespace OrderEmbedding /-- **Birkhoff's Representation Theorem**. Any finite distributive lattice can be embedded in a powerset lattice. -/ noncomputable def birkhoffSet : α ↪o Set {a : α // SupIrred a} := by by_cases! h : IsEmpty α · exact OrderEmbedding.ofIsEmpty have := Fintype.toOrderBot α exact OrderIso.lowerSetSupIrred.toOrderEmbedding.trans ⟨⟨_, SetLike.coe_injective⟩, Iff.rfl⟩ /-- **Birkhoff's Representation Theorem**. Any finite distributive lattice can be embedded in a powerset lattice. -/ noncomputable def birkhoffFinset : α ↪o Finset {a : α // SupIrred a} := by exact birkhoffSet.trans Fintype.finsetOrderIsoSet.symm.toOrderEmbedding @[simp] lemma coe_birkhoffFinset (a : α) : birkhoffFinset a = birkhoffSet a := by classical -- TODO: This should be a single `simp` call but `simp` refuses to use -- `OrderIso.coe_toOrderEmbedding` and `Fintype.coe_finsetOrderIsoSet_symm` simp [birkhoffFinset, (OrderIso.coe_toOrderEmbedding)] @[simp] lemma birkhoffSet_sup (a b : α) : birkhoffSet (a ⊔ b) = birkhoffSet a ∪ birkhoffSet b := by unfold OrderEmbedding.birkhoffSet; split <;> simp [eq_iff_true_of_subsingleton] @[simp] lemma birkhoffSet_inf (a b : α) : birkhoffSet (a ⊓ b) = birkhoffSet a ∩ birkhoffSet b := by unfold OrderEmbedding.birkhoffSet; split <;> simp [eq_iff_true_of_subsingleton] @[simp] lemma birkhoffSet_apply [OrderBot α] (a : α) : birkhoffSet a = OrderIso.lowerSetSupIrred a := by have : Subsingleton (OrderBot α) := inferInstance simp [birkhoffSet, this.allEq] variable [DecidableEq α] @[simp] lemma birkhoffFinset_sup (a b : α) : birkhoffFinset (a ⊔ b) = birkhoffFinset a ∪ birkhoffFinset b := by classical dsimp [OrderEmbedding.birkhoffFinset] rw [birkhoffSet_sup, OrderIso.coe_toOrderEmbedding] simp @[simp] lemma birkhoffFinset_inf (a b : α) : birkhoffFinset (a ⊓ b) = birkhoffFinset a ∩ birkhoffFinset b := by classical dsimp [OrderEmbedding.birkhoffFinset] rw [birkhoffSet_inf, OrderIso.coe_toOrderEmbedding] simp end OrderEmbedding namespace LatticeHom /-- **Birkhoff's Representation Theorem**. Any finite distributive lattice can be embedded in a powerset lattice. -/ noncomputable def birkhoffSet : LatticeHom α (Set {a : α // SupIrred a}) where toFun := OrderEmbedding.birkhoffSet map_sup' := OrderEmbedding.birkhoffSet_sup map_inf' := OrderEmbedding.birkhoffSet_inf open Classical in /-- **Birkhoff's Representation Theorem**. Any finite distributive lattice can be embedded in a powerset lattice. -/ noncomputable def birkhoffFinset : LatticeHom α (Finset {a : α // SupIrred a}) where toFun := OrderEmbedding.birkhoffFinset map_sup' := OrderEmbedding.birkhoffFinset_sup map_inf' := OrderEmbedding.birkhoffFinset_inf lemma birkhoffFinset_injective : Injective (birkhoffFinset (α := α)) := OrderEmbedding.birkhoffFinset.injective end LatticeHom lemma exists_birkhoff_representation.{u} (α : Type u) [Finite α] [DistribLattice α] : ∃ (β : Type u) (_ : DecidableEq β) (_ : Fintype β) (f : LatticeHom α (Finset β)), Injective f := by classical cases nonempty_fintype α exact ⟨{a : α // SupIrred a}, _, inferInstance, _, LatticeHom.birkhoffFinset_injective⟩ end DistribLattice
.lake/packages/mathlib/Mathlib/Order/Sublattice.lean
import Mathlib.Order.SupClosed /-! # Sublattices This file defines sublattices. ## TODO Subsemilattices, if people care about them. ## Tags sublattice -/ open Function Set variable {ι : Sort*} (α β γ : Type*) [Lattice α] [Lattice β] [Lattice γ] /-- A sublattice of a lattice is a set containing the suprema and infima of any of its elements. -/ structure Sublattice where /-- The underlying set of a sublattice. **Do not use directly**. Instead, use the coercion `Sublattice α → Set α`, which Lean should automatically insert for you in most cases. -/ carrier : Set α supClosed' : SupClosed carrier infClosed' : InfClosed carrier variable {α β γ} namespace Sublattice variable {L M : Sublattice α} {f : LatticeHom α β} {s t : Set α} {a b : α} instance instSetLike : SetLike (Sublattice α) α where coe L := L.carrier coe_injective' L M h := by cases L; congr /-- See Note [custom simps projection]. -/ def Simps.coe (L : Sublattice α) : Set α := L initialize_simps_projections Sublattice (carrier → coe, as_prefix coe) /-- Turn a set closed under supremum and infimum into a sublattice. -/ abbrev ofIsSublattice (s : Set α) (hs : IsSublattice s) : Sublattice α := ⟨s, hs.1, hs.2⟩ lemma coe_inj : (L : Set α) = M ↔ L = M := SetLike.coe_set_eq @[simp] lemma supClosed (L : Sublattice α) : SupClosed (L : Set α) := L.supClosed' @[simp] lemma infClosed (L : Sublattice α) : InfClosed (L : Set α) := L.infClosed' lemma sup_mem (ha : a ∈ L) (hb : b ∈ L) : a ⊔ b ∈ L := L.supClosed ha hb lemma inf_mem (ha : a ∈ L) (hb : b ∈ L) : a ⊓ b ∈ L := L.infClosed ha hb @[simp] lemma isSublattice (L : Sublattice α) : IsSublattice (L : Set α) := ⟨L.supClosed, L.infClosed⟩ @[simp] lemma mem_carrier : a ∈ L.carrier ↔ a ∈ L := Iff.rfl @[simp] lemma mem_mk (h_sup h_inf) : a ∈ mk s h_sup h_inf ↔ a ∈ s := Iff.rfl @[simp, norm_cast] lemma coe_mk (h_sup h_inf) : mk s h_sup h_inf = s := rfl @[simp] lemma mk_le_mk (hs_sup hs_inf ht_sup ht_inf) : mk s hs_sup hs_inf ≤ mk t ht_sup ht_inf ↔ s ⊆ t := Iff.rfl @[simp] lemma mk_lt_mk (hs_sup hs_inf ht_sup ht_inf) : mk s hs_sup hs_inf < mk t ht_sup ht_inf ↔ s ⊂ t := Iff.rfl /-- Copy of a sublattice with a new `carrier` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (L : Sublattice α) (s : Set α) (hs : s = L) : Sublattice α where carrier := s supClosed' := hs.symm ▸ L.supClosed' infClosed' := hs.symm ▸ L.infClosed' @[simp, norm_cast] lemma coe_copy (L : Sublattice α) (s : Set α) (hs) : L.copy s hs = s := rfl lemma copy_eq (L : Sublattice α) (s : Set α) (hs) : L.copy s hs = L := SetLike.coe_injective hs /-- Two sublattices are equal if they have the same elements. -/ lemma ext : (∀ a, a ∈ L ↔ a ∈ M) → L = M := SetLike.ext /-- A sublattice of a lattice inherits a supremum. -/ instance instSupCoe : Max L where max a b := ⟨a ⊔ b, L.supClosed a.2 b.2⟩ /-- A sublattice of a lattice inherits an infimum. -/ instance instInfCoe : Min L where min a b := ⟨a ⊓ b, L.infClosed a.2 b.2⟩ @[simp, norm_cast] lemma coe_sup (a b : L) : a ⊔ b = (a : α) ⊔ b := rfl @[simp, norm_cast] lemma coe_inf (a b : L) : a ⊓ b = (a : α) ⊓ b := rfl @[simp] lemma mk_sup_mk (a b : α) (ha hb) : (⟨a, ha⟩ ⊔ ⟨b, hb⟩ : L) = ⟨a ⊔ b, L.supClosed ha hb⟩ := rfl @[simp] lemma mk_inf_mk (a b : α) (ha hb) : (⟨a, ha⟩ ⊓ ⟨b, hb⟩ : L) = ⟨a ⊓ b, L.infClosed ha hb⟩ := rfl /-- A sublattice of a lattice inherits a lattice structure. -/ instance instLatticeCoe (L : Sublattice α) : Lattice L := Subtype.coe_injective.lattice _ (fun _ _ ↦ rfl) (fun _ _ ↦ rfl) /-- A sublattice of a distributive lattice inherits a distributive lattice structure. -/ instance instDistribLatticeCoe {α : Type*} [DistribLattice α] (L : Sublattice α) : DistribLattice L := Subtype.coe_injective.distribLattice _ (fun _ _ ↦ rfl) (fun _ _ ↦ rfl) /-- The natural lattice hom from a sublattice to the original lattice. -/ def subtype (L : Sublattice α) : LatticeHom L α where toFun := ((↑) : L → α) map_sup' _ _ := rfl map_inf' _ _ := rfl @[simp, norm_cast] lemma coe_subtype (L : Sublattice α) : L.subtype = ((↑) : L → α) := rfl lemma subtype_apply (L : Sublattice α) (a : L) : L.subtype a = a := rfl lemma subtype_injective (L : Sublattice α) : Injective <| subtype L := Subtype.coe_injective /-- The inclusion homomorphism from a sublattice `L` to a bigger sublattice `M`. -/ def inclusion (h : L ≤ M) : LatticeHom L M where toFun := Set.inclusion h map_sup' _ _ := rfl map_inf' _ _ := rfl @[simp] lemma coe_inclusion (h : L ≤ M) : inclusion h = Set.inclusion h := rfl lemma inclusion_apply (h : L ≤ M) (a : L) : inclusion h a = Set.inclusion h a := rfl lemma inclusion_injective (h : L ≤ M) : Injective <| inclusion h := Set.inclusion_injective h @[simp] lemma inclusion_rfl (L : Sublattice α) : inclusion le_rfl = LatticeHom.id L := rfl @[simp] lemma subtype_comp_inclusion (h : L ≤ M) : M.subtype.comp (inclusion h) = L.subtype := rfl /-- The maximum sublattice of a lattice. -/ instance instTop : Top (Sublattice α) where top.carrier := univ top.supClosed' := supClosed_univ top.infClosed' := infClosed_univ /-- The empty sublattice of a lattice. -/ instance instBot : Bot (Sublattice α) where bot.carrier := ∅ bot.supClosed' := supClosed_empty bot.infClosed' := infClosed_empty /-- The inf of two sublattices is their intersection. -/ instance instInf : Min (Sublattice α) where min L M := { carrier := L ∩ M supClosed' := L.supClosed.inter M.supClosed infClosed' := L.infClosed.inter M.infClosed } /-- The inf of sublattices is their intersection. -/ instance instInfSet : InfSet (Sublattice α) where sInf S := { carrier := ⨅ L ∈ S, L supClosed' := supClosed_sInter <| forall_mem_range.2 fun L ↦ supClosed_sInter <| forall_mem_range.2 fun _ ↦ L.supClosed infClosed' := infClosed_sInter <| forall_mem_range.2 fun L ↦ infClosed_sInter <| forall_mem_range.2 fun _ ↦ L.infClosed } instance instInhabited : Inhabited (Sublattice α) := ⟨⊥⟩ /-- The top sublattice is isomorphic to the original lattice. This is the sublattice version of `Equiv.Set.univ α`. -/ def topEquiv : (⊤ : Sublattice α) ≃o α where toEquiv := Equiv.Set.univ _ map_rel_iff' := Iff.rfl @[simp, norm_cast] lemma coe_top : (⊤ : Sublattice α) = (univ : Set α) := rfl @[simp, norm_cast] lemma coe_bot : (⊥ : Sublattice α) = (∅ : Set α) := rfl @[simp, norm_cast] lemma coe_inf' (L M : Sublattice α) : L ⊓ M = (L : Set α) ∩ M := rfl @[simp, norm_cast] lemma coe_sInf (S : Set (Sublattice α)) : sInf S = ⋂ L ∈ S, (L : Set α) := rfl @[simp, norm_cast] lemma coe_iInf (f : ι → Sublattice α) : ⨅ i, f i = ⋂ i, (f i : Set α) := by simp [iInf] @[simp, norm_cast] lemma coe_eq_univ : L = (univ : Set α) ↔ L = ⊤ := by rw [← coe_top, coe_inj] @[simp, norm_cast] lemma coe_eq_empty : L = (∅ : Set α) ↔ L = ⊥ := by rw [← coe_bot, coe_inj] @[simp] lemma notMem_bot (a : α) : a ∉ (⊥ : Sublattice α) := id @[simp] lemma mem_top (a : α) : a ∈ (⊤ : Sublattice α) := mem_univ _ @[simp] lemma mem_inf : a ∈ L ⊓ M ↔ a ∈ L ∧ a ∈ M := Iff.rfl @[simp] lemma mem_sInf {S : Set (Sublattice α)} : a ∈ sInf S ↔ ∀ L ∈ S, a ∈ L := by rw [← SetLike.mem_coe]; simp @[simp] lemma mem_iInf {f : ι → Sublattice α} : a ∈ ⨅ i, f i ↔ ∀ i, a ∈ f i := by rw [← SetLike.mem_coe]; simp @[deprecated (since := "2025-05-23")] alias not_mem_bot := notMem_bot /-- Sublattices of a lattice form a complete lattice. -/ instance instCompleteLattice : CompleteLattice (Sublattice α) where bot := ⊥ bot_le := fun _S _a ↦ False.elim top := ⊤ le_top := fun _S a _ha ↦ mem_top a inf := (· ⊓ ·) le_inf := fun _L _M _N hM hN _a ha ↦ ⟨hM ha, hN ha⟩ inf_le_left := fun _L _M _a ↦ And.left inf_le_right := fun _L _M _a ↦ And.right __ := completeLatticeOfInf (Sublattice α) fun _s ↦ IsGLB.of_image SetLike.coe_subset_coe isGLB_biInf lemma subsingleton_iff : Subsingleton (Sublattice α) ↔ IsEmpty α := ⟨fun _ ↦ univ_eq_empty_iff.1 <| coe_inj.2 <| Subsingleton.elim ⊤ ⊥, fun _ ↦ SetLike.coe_injective.subsingleton⟩ instance [IsEmpty α] : Unique (Sublattice α) where uniq _ := @Subsingleton.elim _ (subsingleton_iff.2 ‹_›) _ _ /-- The preimage of a sublattice along a lattice homomorphism. -/ def comap (f : LatticeHom α β) (L : Sublattice β) : Sublattice α where carrier := f ⁻¹' L supClosed' := L.supClosed.preimage _ infClosed' := L.infClosed.preimage _ @[simp, norm_cast] lemma coe_comap (L : Sublattice β) (f : LatticeHom α β) : L.comap f = f ⁻¹' L := rfl @[simp] lemma mem_comap {L : Sublattice β} : a ∈ L.comap f ↔ f a ∈ L := Iff.rfl lemma comap_mono : Monotone (comap f) := fun _ _ ↦ preimage_mono @[simp] lemma comap_id (L : Sublattice α) : L.comap (LatticeHom.id _) = L := rfl @[simp] lemma comap_comap (L : Sublattice γ) (g : LatticeHom β γ) (f : LatticeHom α β) : (L.comap g).comap f = L.comap (g.comp f) := rfl /-- The image of a sublattice along a monoid homomorphism is a sublattice. -/ def map (f : LatticeHom α β) (L : Sublattice α) : Sublattice β where carrier := f '' L supClosed' := L.supClosed.image f infClosed' := L.infClosed.image f @[simp] lemma coe_map (f : LatticeHom α β) (L : Sublattice α) : (L.map f : Set β) = f '' L := rfl @[simp] lemma mem_map {b : β} : b ∈ L.map f ↔ ∃ a ∈ L, f a = b := Iff.rfl lemma mem_map_of_mem (f : LatticeHom α β) {a : α} : a ∈ L → f a ∈ L.map f := mem_image_of_mem f lemma apply_coe_mem_map (f : LatticeHom α β) (a : L) : f a ∈ L.map f := mem_map_of_mem f a.prop lemma map_mono : Monotone (map f) := fun _ _ ↦ image_mono @[simp] lemma map_id : L.map (LatticeHom.id α) = L := SetLike.coe_injective <| image_id _ @[simp] lemma map_map (g : LatticeHom β γ) (f : LatticeHom α β) : (L.map f).map g = L.map (g.comp f) := SetLike.coe_injective <| image_image _ _ _ lemma mem_map_equiv {f : α ≃o β} {a : β} : a ∈ L.map f ↔ f.symm a ∈ L := Set.mem_image_equiv lemma apply_mem_map_iff (hf : Injective f) : f a ∈ L.map f ↔ a ∈ L := hf.mem_set_image lemma map_equiv_eq_comap_symm (f : α ≃o β) (L : Sublattice α) : L.map f = L.comap (f.symm : LatticeHom β α) := SetLike.coe_injective <| f.toEquiv.image_eq_preimage_symm L lemma comap_equiv_eq_map_symm (f : β ≃o α) (L : Sublattice α) : L.comap f = L.map (f.symm : LatticeHom α β) := (map_equiv_eq_comap_symm f.symm L).symm lemma map_symm_eq_iff_eq_map {M : Sublattice β} {e : β ≃o α} : L.map ↑e.symm = M ↔ L = M.map ↑e := by simp_rw [← coe_inj]; exact (Equiv.eq_image_iff_symm_image_eq _ _ _).symm lemma map_le_iff_le_comap {f : LatticeHom α β} {M : Sublattice β} : L.map f ≤ M ↔ L ≤ M.comap f := image_subset_iff lemma gc_map_comap (f : LatticeHom α β) : GaloisConnection (map f) (comap f) := fun _ _ ↦ map_le_iff_le_comap @[simp] lemma map_bot (f : LatticeHom α β) : (⊥ : Sublattice α).map f = ⊥ := (gc_map_comap f).l_bot lemma map_sup (f : LatticeHom α β) (L M : Sublattice α) : (L ⊔ M).map f = L.map f ⊔ M.map f := (gc_map_comap f).l_sup lemma map_iSup (f : LatticeHom α β) (L : ι → Sublattice α) : (⨆ i, L i).map f = ⨆ i, (L i).map f := (gc_map_comap f).l_iSup @[simp] lemma comap_top (f : LatticeHom α β) : (⊤ : Sublattice β).comap f = ⊤ := (gc_map_comap f).u_top lemma comap_inf (L M : Sublattice β) (f : LatticeHom α β) : (L ⊓ M).comap f = L.comap f ⊓ M.comap f := (gc_map_comap f).u_inf lemma comap_iInf (f : LatticeHom α β) (s : ι → Sublattice β) : (iInf s).comap f = ⨅ i, (s i).comap f := (gc_map_comap f).u_iInf lemma map_inf_le (L M : Sublattice α) (f : LatticeHom α β) : map f (L ⊓ M) ≤ map f L ⊓ map f M := map_mono.map_inf_le _ _ lemma le_comap_sup (L M : Sublattice β) (f : LatticeHom α β) : comap f L ⊔ comap f M ≤ comap f (L ⊔ M) := comap_mono.le_map_sup _ _ lemma le_comap_iSup (f : LatticeHom α β) (L : ι → Sublattice β) : ⨆ i, (L i).comap f ≤ (⨆ i, L i).comap f := comap_mono.le_map_iSup lemma map_inf (L M : Sublattice α) (f : LatticeHom α β) (hf : Injective f) : map f (L ⊓ M) = map f L ⊓ map f M := by rw [← SetLike.coe_set_eq] simp [Set.image_inter hf] lemma map_top (f : LatticeHom α β) (h : Surjective f) : Sublattice.map f ⊤ = ⊤ := SetLike.coe_injective <| by simp [h.range_eq] end Sublattice namespace Sublattice variable {L M : Sublattice α} {f : LatticeHom α β} {s t : Set α} {a : α} /-- Binary product of sublattices as a sublattice. -/ @[simps] def prod (L : Sublattice α) (M : Sublattice β) : Sublattice (α × β) where carrier := L ×ˢ M supClosed' := L.supClosed.prod M.supClosed infClosed' := L.infClosed.prod M.infClosed attribute [norm_cast] coe_prod @[simp] lemma mem_prod {M : Sublattice β} {p : α × β} : p ∈ L.prod M ↔ p.1 ∈ L ∧ p.2 ∈ M := Iff.rfl @[gcongr] lemma prod_mono {L₁ L₂ : Sublattice α} {M₁ M₂ : Sublattice β} (hL : L₁ ≤ L₂) (hM : M₁ ≤ M₂) : L₁.prod M₁ ≤ L₂.prod M₂ := Set.prod_mono hL hM lemma prod_mono_left {L₁ L₂ : Sublattice α} {M : Sublattice β} (hL : L₁ ≤ L₂) : L₁.prod M ≤ L₂.prod M := prod_mono hL le_rfl lemma prod_mono_right {M₁ M₂ : Sublattice β} (hM : M₁ ≤ M₂) : L.prod M₁ ≤ L.prod M₂ := prod_mono le_rfl hM lemma prod_left_mono : Monotone fun L : Sublattice α ↦ L.prod M := fun _ _ ↦ prod_mono_left lemma prod_right_mono : Monotone fun M : Sublattice β ↦ L.prod M := fun _ _ ↦ prod_mono_right lemma prod_top (L : Sublattice α) : L.prod (⊤ : Sublattice β) = L.comap LatticeHom.fst := ext fun a ↦ by simp [mem_prod, LatticeHom.coe_fst] lemma top_prod (L : Sublattice β) : (⊤ : Sublattice α).prod L = L.comap LatticeHom.snd := ext fun a ↦ by simp [mem_prod, LatticeHom.coe_snd] @[simp] lemma top_prod_top : (⊤ : Sublattice α).prod (⊤ : Sublattice β) = ⊤ := (top_prod _).trans <| comap_top _ @[simp] lemma prod_bot (L : Sublattice α) : L.prod (⊥ : Sublattice β) = ⊥ := SetLike.coe_injective prod_empty @[simp] lemma bot_prod (M : Sublattice β) : (⊥ : Sublattice α).prod M = ⊥ := SetLike.coe_injective empty_prod lemma le_prod_iff {M : Sublattice β} {N : Sublattice (α × β)} : N ≤ L.prod M ↔ N ≤ comap LatticeHom.fst L ∧ N ≤ comap LatticeHom.snd M := by simp [SetLike.le_def, forall_and] @[simp] lemma prod_eq_bot {M : Sublattice β} : L.prod M = ⊥ ↔ L = ⊥ ∨ M = ⊥ := by simpa only [← coe_inj] using Set.prod_eq_empty_iff @[simp] lemma prod_eq_top [Nonempty α] [Nonempty β] {M : Sublattice β} : L.prod M = ⊤ ↔ L = ⊤ ∧ M = ⊤ := by simpa only [← coe_inj] using Set.prod_eq_univ /-- The product of sublattices is isomorphic to their product as lattices. -/ @[simps! toEquiv apply symm_apply] def prodEquiv (L : Sublattice α) (M : Sublattice β) : L.prod M ≃o L × M where toEquiv := Equiv.Set.prod _ _ map_rel_iff' := Iff.rfl section Pi variable {κ : Type*} {π : κ → Type*} [∀ i, Lattice (π i)] /-- Arbitrary product of sublattices. Given an index set `s` and a family of sublattices `L : Π i, Sublattice (α i)`, `pi s L` is the sublattice of dependent functions `f : Π i, α i` such that `f i` belongs to `L i` whenever `i ∈ s`. -/ @[simps] def pi (s : Set κ) (L : ∀ i, Sublattice (π i)) : Sublattice (∀ i, π i) where carrier := s.pi fun i ↦ L i supClosed' := supClosed_pi fun i _ ↦ (L i).supClosed infClosed' := infClosed_pi fun i _ ↦ (L i).infClosed attribute [norm_cast] coe_pi @[simp] lemma mem_pi {s : Set κ} {L : ∀ i, Sublattice (π i)} {x : ∀ i, π i} : x ∈ pi s L ↔ ∀ i, i ∈ s → x i ∈ L i := Iff.rfl @[simp] lemma pi_empty (L : ∀ i, Sublattice (π i)) : pi ∅ L = ⊤ := ext fun a ↦ by simp [mem_pi] @[simp] lemma pi_top (s : Set κ) : (pi s fun _ ↦ ⊤ : Sublattice (∀ i, π i)) = ⊤ := ext fun a ↦ by simp [mem_pi] @[simp] lemma pi_bot {s : Set κ} (hs : s.Nonempty) : (pi s fun _ ↦ ⊥ : Sublattice (∀ i, π i)) = ⊥ := ext fun a ↦ by simpa [mem_pi] using hs lemma pi_univ_bot [Nonempty κ] : (pi univ fun _ ↦ ⊥ : Sublattice (∀ i, π i)) = ⊥ := by simp lemma le_pi {s : Set κ} {L : ∀ i, Sublattice (π i)} {M : Sublattice (∀ i, π i)} : M ≤ pi s L ↔ ∀ i ∈ s, M ≤ comap (Pi.evalLatticeHom i) (L i) := by simp [SetLike.le_def]; aesop @[simp] lemma pi_univ_eq_bot_iff {L : ∀ i, Sublattice (π i)} : pi univ L = ⊥ ↔ ∃ i, L i = ⊥ := by simp_rw [← coe_inj]; simp lemma pi_univ_eq_bot {L : ∀ i, Sublattice (π i)} {i : κ} (hL : L i = ⊥) : pi univ L = ⊥ := pi_univ_eq_bot_iff.2 ⟨i, hL⟩ end Pi end Sublattice
.lake/packages/mathlib/Mathlib/Order/Chain.lean
import Mathlib.Order.Preorder.Chain import Mathlib.Tactic.Linter.DeprecatedModule deprecated_module (since := "2025-04-13")
.lake/packages/mathlib/Mathlib/Order/PrimeIdeal.lean
import Mathlib.Order.Ideal import Mathlib.Order.PFilter /-! # Prime ideals ## 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. - `Order.Ideal.PrimePair`: A pair of an `Order.Ideal` and an `Order.PFilter` which form a partition of `P`. This is useful as giving the data of a prime ideal is the same as giving the data of a prime filter. - `Order.Ideal.IsPrime`: a predicate for prime ideals. Dual to the notion of a prime filter. - `Order.PFilter.IsPrime`: a predicate for prime filters. Dual to the notion of a prime ideal. ## References - <https://en.wikipedia.org/wiki/Ideal_(order_theory)> ## Tags ideal, prime -/ open Order.PFilter namespace Order variable {P : Type*} namespace Ideal /-- A pair of an `Order.Ideal` and an `Order.PFilter` which form a partition of `P`. -/ structure PrimePair (P : Type*) [Preorder P] where I : Ideal P F : PFilter P isCompl_I_F : IsCompl (I : Set P) F namespace PrimePair variable [Preorder P] (IF : PrimePair P) theorem compl_I_eq_F : (IF.I : Set P)ᶜ = IF.F := IF.isCompl_I_F.compl_eq theorem compl_F_eq_I : (IF.F : Set P)ᶜ = IF.I := IF.isCompl_I_F.eq_compl.symm theorem I_isProper : IsProper IF.I := by obtain ⟨w, h⟩ := IF.F.nonempty apply isProper_of_notMem (_ : w ∉ IF.I) rwa [← IF.compl_I_eq_F] at h protected theorem disjoint : Disjoint (IF.I : Set P) IF.F := IF.isCompl_I_F.disjoint theorem I_union_F : (IF.I : Set P) ∪ IF.F = Set.univ := IF.isCompl_I_F.sup_eq_top theorem F_union_I : (IF.F : Set P) ∪ IF.I = Set.univ := IF.isCompl_I_F.symm.sup_eq_top end PrimePair /-- An ideal `I` is prime if its complement is a filter. -/ @[mk_iff] class IsPrime [Preorder P] (I : Ideal P) : Prop extends IsProper I where compl_filter : IsPFilter (I : Set P)ᶜ section Preorder variable [Preorder P] /-- Create an element of type `Order.Ideal.PrimePair` from an ideal satisfying the predicate `Order.Ideal.IsPrime`. -/ def IsPrime.toPrimePair {I : Ideal P} (h : IsPrime I) : PrimePair P := { I F := h.compl_filter.toPFilter isCompl_I_F := isCompl_compl } theorem PrimePair.I_isPrime (IF : PrimePair P) : IsPrime IF.I := { IF.I_isProper with compl_filter := by rw [IF.compl_I_eq_F] exact IF.F.isPFilter } end Preorder section SemilatticeInf variable [SemilatticeInf P] {I : Ideal P} theorem IsPrime.mem_or_mem (hI : IsPrime I) {x y : P} : x ⊓ y ∈ I → x ∈ I ∨ y ∈ I := by contrapose! let F := hI.compl_filter.toPFilter change x ∈ F ∧ y ∈ F → x ⊓ y ∈ F exact fun h => inf_mem h.1 h.2 theorem IsPrime.of_mem_or_mem [IsProper I] (hI : ∀ {x y : P}, x ⊓ y ∈ I → x ∈ I ∨ y ∈ I) : IsPrime I := by rw [isPrime_iff] use ‹_› refine .of_def ?_ ?_ ?_ · exact Set.nonempty_compl.2 (I.isProper_iff.1 ‹_›) · intro x hx y hy exact ⟨x ⊓ y, fun h => (hI h).elim hx hy, inf_le_left, inf_le_right⟩ · exact @mem_compl_of_ge _ _ _ theorem isPrime_iff_mem_or_mem [IsProper I] : IsPrime I ↔ ∀ {x y : P}, x ⊓ y ∈ I → x ∈ I ∨ y ∈ I := ⟨IsPrime.mem_or_mem, IsPrime.of_mem_or_mem⟩ end SemilatticeInf section DistribLattice variable [DistribLattice P] {I : Ideal P} instance (priority := 100) IsMaximal.isPrime [IsMaximal I] : IsPrime I := by rw [isPrime_iff_mem_or_mem] intro x y contrapose! rintro ⟨hx, hynI⟩ hxy apply hynI let J := I ⊔ principal x have hJuniv : (J : Set P) = Set.univ := IsMaximal.maximal_proper (lt_sup_principal_of_notMem ‹_›) have hyJ : y ∈ (J : Set P) := Set.eq_univ_iff_forall.mp hJuniv y rw [coe_sup_eq] at hyJ rcases hyJ with ⟨a, ha, b, hb, hy⟩ rw [hy] refine sup_mem ha (I.lower (le_inf hb ?_) hxy) rw [hy] exact le_sup_right end DistribLattice section BooleanAlgebra variable [BooleanAlgebra P] {x : P} {I : Ideal P} theorem IsPrime.mem_or_compl_mem (hI : IsPrime I) : x ∈ I ∨ xᶜ ∈ I := by apply hI.mem_or_mem rw [inf_compl_eq_bot] exact I.bot_mem theorem IsPrime.compl_mem_of_notMem (hI : IsPrime I) (hxnI : x ∉ I) : xᶜ ∈ I := hI.mem_or_compl_mem.resolve_left hxnI @[deprecated (since := "2025-05-23")] alias IsPrime.mem_compl_of_not_mem := IsPrime.compl_mem_of_notMem theorem isPrime_of_mem_or_compl_mem [IsProper I] (h : ∀ {x : P}, x ∈ I ∨ xᶜ ∈ I) : IsPrime I := by simp only [isPrime_iff_mem_or_mem, or_iff_not_imp_left] intro x y hxy hxI have hxcI : xᶜ ∈ I := h.resolve_left hxI have ass : x ⊓ y ⊔ y ⊓ xᶜ ∈ I := sup_mem hxy (I.lower inf_le_right hxcI) rwa [inf_comm, sup_inf_inf_compl] at ass theorem isPrime_iff_mem_or_compl_mem [IsProper I] : IsPrime I ↔ ∀ {x : P}, x ∈ I ∨ xᶜ ∈ I := ⟨fun h _ => h.mem_or_compl_mem, isPrime_of_mem_or_compl_mem⟩ instance (priority := 100) IsPrime.isMaximal [IsPrime I] : IsMaximal I := by simp only [isMaximal_iff, Set.eq_univ_iff_forall, IsPrime.toIsProper, true_and] intro J hIJ x rcases Set.exists_of_ssubset hIJ with ⟨y, hyJ, hyI⟩ suffices ass : x ⊓ y ⊔ x ⊓ yᶜ ∈ J by rwa [sup_inf_inf_compl] at ass exact sup_mem (J.lower inf_le_right hyJ) (hIJ.le <| I.lower inf_le_right <| IsPrime.compl_mem_of_notMem ‹_› hyI) end BooleanAlgebra end Ideal namespace PFilter variable [Preorder P] /-- A filter `F` is prime if its complement is an ideal. -/ @[mk_iff] class IsPrime (F : PFilter P) : Prop where compl_ideal : IsIdeal (F : Set P)ᶜ /-- Create an element of type `Order.Ideal.PrimePair` from a filter satisfying the predicate `Order.PFilter.IsPrime`. -/ def IsPrime.toPrimePair {F : PFilter P} (h : IsPrime F) : Ideal.PrimePair P := { I := h.compl_ideal.toIdeal F isCompl_I_F := isCompl_compl.symm } theorem _root_.Order.Ideal.PrimePair.F_isPrime (IF : Ideal.PrimePair P) : IsPrime IF.F := { compl_ideal := by rw [IF.compl_F_eq_I] exact IF.I.isIdeal } end PFilter end Order
.lake/packages/mathlib/Mathlib/Order/Iterate.lean
import Mathlib.Logic.Function.Iterate import Mathlib.Order.Monotone.Basic /-! # Inequalities on iterates In this file we prove some inequalities comparing `f^[n] x` and `g^[n] x` where `f` and `g` are two self-maps that commute with each other. Current selection of inequalities is motivated by formalization of the rotation number of a circle homeomorphism. -/ open Function open Function (Commute) namespace Monotone variable {α : Type*} [Preorder α] {f : α → α} {x y : ℕ → α} /-! ### Comparison of two sequences If $f$ is a monotone function, then $∀ k, x_{k+1} ≤ f(x_k)$ implies that $x_k$ grows slower than $f^k(x_0)$, and similarly for the reversed inequalities. If $x_k$ and $y_k$ are two sequences such that $x_{k+1} ≤ f(x_k)$ and $y_{k+1} ≥ f(y_k)$ for all $k < n$, then $x_0 ≤ y_0$ implies $x_n ≤ y_n$, see `Monotone.seq_le_seq`. If some of the inequalities in this lemma are strict, then we have $x_n < y_n$. The rest of the lemmas in this section formalize this fact for different inequalities made strict. -/ theorem seq_le_seq (hf : Monotone f) (n : ℕ) (h₀ : x 0 ≤ y 0) (hx : ∀ k < n, x (k + 1) ≤ f (x k)) (hy : ∀ k < n, f (y k) ≤ y (k + 1)) : x n ≤ y n := by induction n with | zero => exact h₀ | succ n ihn => refine (hx _ n.lt_succ_self).trans ((hf <| ihn ?_ ?_).trans (hy _ n.lt_succ_self)) · exact fun k hk => hx _ (hk.trans n.lt_succ_self) · exact fun k hk => hy _ (hk.trans n.lt_succ_self) theorem seq_pos_lt_seq_of_lt_of_le (hf : Monotone f) {n : ℕ} (hn : 0 < n) (h₀ : x 0 ≤ y 0) (hx : ∀ k < n, x (k + 1) < f (x k)) (hy : ∀ k < n, f (y k) ≤ y (k + 1)) : x n < y n := by induction n with | zero => exact hn.false.elim | succ n ihn => suffices x n ≤ y n from (hx n n.lt_succ_self).trans_le ((hf this).trans <| hy n n.lt_succ_self) cases n with | zero => exact h₀ | succ n => refine (ihn n.zero_lt_succ (fun k hk => hx _ ?_) fun k hk => hy _ ?_).le <;> exact hk.trans n.succ.lt_succ_self theorem seq_pos_lt_seq_of_le_of_lt (hf : Monotone f) {n : ℕ} (hn : 0 < n) (h₀ : x 0 ≤ y 0) (hx : ∀ k < n, x (k + 1) ≤ f (x k)) (hy : ∀ k < n, f (y k) < y (k + 1)) : x n < y n := hf.dual.seq_pos_lt_seq_of_lt_of_le hn h₀ hy hx theorem seq_lt_seq_of_lt_of_le (hf : Monotone f) (n : ℕ) (h₀ : x 0 < y 0) (hx : ∀ k < n, x (k + 1) < f (x k)) (hy : ∀ k < n, f (y k) ≤ y (k + 1)) : x n < y n := by cases n exacts [h₀, hf.seq_pos_lt_seq_of_lt_of_le (Nat.zero_lt_succ _) h₀.le hx hy] theorem seq_lt_seq_of_le_of_lt (hf : Monotone f) (n : ℕ) (h₀ : x 0 < y 0) (hx : ∀ k < n, x (k + 1) ≤ f (x k)) (hy : ∀ k < n, f (y k) < y (k + 1)) : x n < y n := hf.dual.seq_lt_seq_of_lt_of_le n h₀ hy hx /-! ### Iterates of two functions In this section we compare the iterates of a monotone function `f : α → α` to iterates of any function `g : β → β`. If `h : β → α` satisfies `h ∘ g ≤ f ∘ h`, then `h (g^[n] x)` grows slower than `f^[n] (h x)`, and similarly for the reversed inequality. Then we specialize these two lemmas to the case `β = α`, `h = id`. -/ variable {β : Type*} {g : β → β} {h : β → α} open Function theorem le_iterate_comp_of_le (hf : Monotone f) (H : h ∘ g ≤ f ∘ h) (n : ℕ) : h ∘ g^[n] ≤ f^[n] ∘ h := fun x => by apply hf.seq_le_seq n <;> intros <;> simp [iterate_succ', -iterate_succ, comp_apply, id_eq, le_refl] case hx => exact H _ theorem iterate_comp_le_of_le (hf : Monotone f) (H : f ∘ h ≤ h ∘ g) (n : ℕ) : f^[n] ∘ h ≤ h ∘ g^[n] := hf.dual.le_iterate_comp_of_le H n /-- If `f ≤ g` and `f` is monotone, then `f^[n] ≤ g^[n]`. -/ theorem iterate_le_of_le {g : α → α} (hf : Monotone f) (h : f ≤ g) (n : ℕ) : f^[n] ≤ g^[n] := hf.iterate_comp_le_of_le h n /-- If `f ≤ g` and `g` is monotone, then `f^[n] ≤ g^[n]`. -/ theorem le_iterate_of_le {g : α → α} (hg : Monotone g) (h : f ≤ g) (n : ℕ) : f^[n] ≤ g^[n] := hg.dual.iterate_le_of_le h n end Monotone /-! ### Comparison of iterations and the identity function If $f(x) ≤ x$ for all $x$ (we express this as `f ≤ id` in the code), then the same is true for any iterate of $f$, and similarly for the reversed inequality. -/ namespace Function section Preorder variable {α : Type*} [Preorder α] {f : α → α} /-- If $x ≤ f x$ for all $x$ (we write this as `id ≤ f`), then the same is true for any iterate `f^[n]` of `f`. -/ theorem id_le_iterate_of_id_le (h : id ≤ f) (n : ℕ) : id ≤ f^[n] := by simpa only [iterate_id] using monotone_id.iterate_le_of_le h n theorem iterate_le_id_of_le_id (h : f ≤ id) (n : ℕ) : f^[n] ≤ id := @id_le_iterate_of_id_le αᵒᵈ _ f h n theorem monotone_iterate_of_id_le (h : id ≤ f) : Monotone fun m => f^[m] := monotone_nat_of_le_succ fun n x => by rw [iterate_succ_apply'] exact h _ theorem antitone_iterate_of_le_id (h : f ≤ id) : Antitone fun m => f^[m] := fun m n hmn => @monotone_iterate_of_id_le αᵒᵈ _ f h m n hmn end Preorder /-! ### Iterates of commuting functions If `f` and `g` are monotone and commute, then `f x ≤ g x` implies `f^[n] x ≤ g^[n] x`, see `Function.Commute.iterate_le_of_map_le`. We also prove two strict inequality versions of this lemma, as well as `iff` versions. -/ namespace Commute section Preorder variable {α : Type*} [Preorder α] {f g : α → α} theorem iterate_le_of_map_le (h : Commute f g) (hf : Monotone f) (hg : Monotone g) {x} (hx : f x ≤ g x) (n : ℕ) : f^[n] x ≤ g^[n] x := by apply hf.seq_le_seq n · rfl · intros; rw [iterate_succ_apply'] · simp [h.iterate_right _ _, hg.iterate _ hx] theorem iterate_pos_lt_of_map_lt (h : Commute f g) (hf : Monotone f) (hg : StrictMono g) {x} (hx : f x < g x) {n} (hn : 0 < n) : f^[n] x < g^[n] x := by apply hf.seq_pos_lt_seq_of_le_of_lt hn · rfl · intros; rw [iterate_succ_apply'] · simp [h.iterate_right _ _, hg.iterate _ hx] theorem iterate_pos_lt_of_map_lt' (h : Commute f g) (hf : StrictMono f) (hg : Monotone g) {x} (hx : f x < g x) {n} (hn : 0 < n) : f^[n] x < g^[n] x := @iterate_pos_lt_of_map_lt αᵒᵈ _ g f h.symm hg.dual hf.dual x hx n hn end Preorder variable {α : Type*} [LinearOrder α] {f g : α → α} theorem iterate_pos_lt_iff_map_lt (h : Commute f g) (hf : Monotone f) (hg : StrictMono g) {x n} (hn : 0 < n) : f^[n] x < g^[n] x ↔ f x < g x := by rcases lt_trichotomy (f x) (g x) with (H | H | H) · simp only [*, iterate_pos_lt_of_map_lt] · simp only [*, h.iterate_eq_of_map_eq, lt_irrefl] · simp only [lt_asymm H, lt_asymm (h.symm.iterate_pos_lt_of_map_lt' hg hf H hn)] theorem iterate_pos_lt_iff_map_lt' (h : Commute f g) (hf : StrictMono f) (hg : Monotone g) {x n} (hn : 0 < n) : f^[n] x < g^[n] x ↔ f x < g x := @iterate_pos_lt_iff_map_lt αᵒᵈ _ _ _ h.symm hg.dual hf.dual x n hn theorem iterate_pos_le_iff_map_le (h : Commute f g) (hf : Monotone f) (hg : StrictMono g) {x n} (hn : 0 < n) : f^[n] x ≤ g^[n] x ↔ f x ≤ g x := by simpa only [not_lt] using not_congr (h.symm.iterate_pos_lt_iff_map_lt' hg hf hn) theorem iterate_pos_le_iff_map_le' (h : Commute f g) (hf : StrictMono f) (hg : Monotone g) {x n} (hn : 0 < n) : f^[n] x ≤ g^[n] x ↔ f x ≤ g x := by simpa only [not_lt] using not_congr (h.symm.iterate_pos_lt_iff_map_lt hg hf hn) theorem iterate_pos_eq_iff_map_eq (h : Commute f g) (hf : Monotone f) (hg : StrictMono g) {x n} (hn : 0 < n) : f^[n] x = g^[n] x ↔ f x = g x := by simp only [le_antisymm_iff, h.iterate_pos_le_iff_map_le hf hg hn, h.symm.iterate_pos_le_iff_map_le' hg hf hn] end Commute end Function namespace Monotone variable {α : Type*} [Preorder α] {f : α → α} {x : α} /-- If `f` is a monotone map and `x ≤ f x` at some point `x`, then the iterates `f^[n] x` form a monotone sequence. -/ theorem monotone_iterate_of_le_map (hf : Monotone f) (hx : x ≤ f x) : Monotone fun n => f^[n] x := monotone_nat_of_le_succ fun n => by rw [iterate_succ_apply] exact hf.iterate n hx /-- If `f` is a monotone map and `f x ≤ x` at some point `x`, then the iterates `f^[n] x` form an antitone sequence. -/ theorem antitone_iterate_of_map_le (hf : Monotone f) (hx : f x ≤ x) : Antitone fun n => f^[n] x := hf.dual.monotone_iterate_of_le_map hx end Monotone namespace StrictMono variable {α : Type*} [Preorder α] {f : α → α} {x : α} /-- If `f` is a strictly monotone map and `x < f x` at some point `x`, then the iterates `f^[n] x` form a strictly monotone sequence. -/ theorem strictMono_iterate_of_lt_map (hf : StrictMono f) (hx : x < f x) : StrictMono fun n => f^[n] x := strictMono_nat_of_lt_succ fun n => by rw [iterate_succ_apply] exact hf.iterate n hx /-- If `f` is a strictly antitone map and `f x < x` at some point `x`, then the iterates `f^[n] x` form a strictly antitone sequence. -/ theorem strictAnti_iterate_of_map_lt (hf : StrictMono f) (hx : f x < x) : StrictAnti fun n => f^[n] x := hf.dual.strictMono_iterate_of_lt_map hx end StrictMono
.lake/packages/mathlib/Mathlib/Order/TransfiniteIteration.lean
import Mathlib.Order.SuccPred.Limit /-! # Transfinite iteration of a function `I → I` Given `φ : I → I` where `[SupSet I]`, we define the `j`th transfinite iteration of `φ` for any `j : J`, with `J` a well-ordered type: this is `transfiniteIterate φ j : I → I`. If `i₀ : I`, then `transfiniteIterate φ ⊥ i₀ = i₀`; if `j` is a non-maximal element, then `transfiniteIterate φ (Order.succ j) i₀ = φ (transfiniteIterate φ j i₀)`; and if `j` is a limit element, `transfiniteIterate φ j i₀` is the supremum of the `transfiniteIterate φ l i₀` for `l < j`. If `I` is a complete lattice, we show that `j ↦ transfiniteIterate φ j i₀` is a monotone function if `i ≤ φ i` for all `i`. Moreover, if `i < φ i` when `i ≠ ⊤`, we show in the lemma `top_mem_range_transfiniteIteration` that there exists `j : J` such that `transfiniteIteration φ i₀ j = ⊤` if we assume that `j ↦ transfiniteIterate φ i₀ j : J → I` is not injective (which shall hold when we know `Cardinal.mk I < Cardinal.mk J`). ## TODO (@joelriou) * deduce that in a Grothendieck abelian category, there is a *set* `I` of monomorphisms such that any monomorphism is a transfinite composition of pushouts of morphisms in `I`, and then an object `X` is injective iff `X ⟶ 0` has the right lifting property with respect to `I`. -/ universe w u section variable {I : Type u} [SupSet I] (φ : I → I) {J : Type w} [LinearOrder J] [SuccOrder J] [WellFoundedLT J] /-- The `j`th-iteration of a function `φ : I → I` when `j : J` belongs to a well-ordered type. -/ noncomputable def transfiniteIterate (j : J) : I → I := SuccOrder.limitRecOn j (fun _ _ ↦ id) (fun _ _ g ↦ φ ∘ g) (fun y _ h ↦ ⨆ (x : Set.Iio y), h x.1 x.2) @[simp] lemma transfiniteIterate_bot [OrderBot J] (i₀ : I) : transfiniteIterate φ (⊥ : J) i₀ = i₀ := by dsimp [transfiniteIterate] simp only [isMin_iff_eq_bot, SuccOrder.limitRecOn_isMin, id_eq] lemma transfiniteIterate_succ (i₀ : I) (j : J) (hj : ¬ IsMax j) : transfiniteIterate φ (Order.succ j) i₀ = φ (transfiniteIterate φ j i₀) := by dsimp [transfiniteIterate] rw [SuccOrder.limitRecOn_succ_of_not_isMax _ _ _ hj] rfl lemma transfiniteIterate_limit (i₀ : I) (j : J) (hj : Order.IsSuccLimit j) : transfiniteIterate φ j i₀ = ⨆ (x : Set.Iio j), transfiniteIterate φ x.1 i₀ := by dsimp [transfiniteIterate] rw [SuccOrder.limitRecOn_of_isSuccLimit _ _ _ hj] simp only [iSup_apply] end section variable {I : Type u} [CompleteLattice I] (φ : I → I) (i₀ : I) {J : Type w} [LinearOrder J] [OrderBot J] [SuccOrder J] [WellFoundedLT J] lemma monotone_transfiniteIterate (hφ : ∀ (i : I), i ≤ φ i) : Monotone (fun (j : J) ↦ transfiniteIterate φ j i₀) := by intro k j hkj induction j using SuccOrder.limitRecOn with | isMin k hk => obtain rfl := hk.eq_bot obtain rfl : k = ⊥ := by simpa using hkj rfl | succ k' hk' hkk' => obtain hkj | rfl := hkj.lt_or_eq · refine (hkk' ((Order.lt_succ_iff_of_not_isMax hk').mp hkj)).trans ?_ dsimp rw [transfiniteIterate_succ _ _ _ hk'] apply hφ · rfl | isSuccLimit k' hk' _ => obtain hkj | rfl := hkj.lt_or_eq · dsimp rw [transfiniteIterate_limit _ _ _ hk'] exact le_iSup (fun (⟨l, hl⟩ : Set.Iio k') ↦ transfiniteIterate φ l i₀) ⟨k, hkj⟩ · rfl lemma top_mem_range_transfiniteIterate (hφ' : ∀ i ≠ (⊤ : I), i < φ i) (φtop : φ ⊤ = ⊤) (H : ¬ Function.Injective (fun (j : J) ↦ transfiniteIterate φ j i₀)) : ∃ (j : J), transfiniteIterate φ j i₀ = ⊤ := by have hφ (i : I) : i ≤ φ i := by by_cases hi : i = ⊤ · subst hi rw [φtop] · exact (hφ' i hi).le obtain ⟨j₁, j₂, hj, eq⟩ : ∃ (j₁ j₂ : J) (hj : j₁ < j₂), transfiniteIterate φ j₁ i₀ = transfiniteIterate φ j₂ i₀ := by grind [Function.Injective] by_contra! suffices transfiniteIterate φ j₁ i₀ < transfiniteIterate φ j₂ i₀ by simp only [eq, lt_self_iff_false] at this have hj₁ : ¬ IsMax j₁ := by simp only [not_isMax_iff] exact ⟨_, hj⟩ refine lt_of_lt_of_le (hφ' _ (this j₁)) ?_ rw [← transfiniteIterate_succ φ i₀ j₁ hj₁] exact monotone_transfiniteIterate _ _ hφ (Order.succ_le_of_lt hj) end
.lake/packages/mathlib/Mathlib/Order/CompleteBooleanAlgebra.lean
import Mathlib.Logic.Equiv.Set import Mathlib.Logic.Pairwise import Mathlib.Order.CompleteLattice.Lemmas import Mathlib.Order.Directed import Mathlib.Order.GaloisConnection.Basic /-! # Frames, completely distributive lattices and complete Boolean algebras In this file we define and provide API for (co)frames, completely distributive lattices and complete Boolean algebras. We distinguish two different distributivity properties: 1. `inf_iSup_eq : (a ⊓ ⨆ i, f i) = ⨆ i, a ⊓ f i` (finite `⊓` distributes over infinite `⨆`). This is required by `Frame`, `CompleteDistribLattice`, and `CompleteBooleanAlgebra` (`Coframe`, etc., require the dual property). 2. `iInf_iSup_eq : (⨅ i, ⨆ j, f i j) = ⨆ s, ⨅ i, f i (s i)` (infinite `⨅` distributes over infinite `⨆`). This stronger property is called "completely distributive", and is required by `CompletelyDistribLattice` and `CompleteAtomicBooleanAlgebra`. ## Typeclasses * `Order.Frame`: Frame: A complete lattice whose `⊓` distributes over `⨆`. * `Order.Coframe`: Coframe: A complete lattice whose `⊔` distributes over `⨅`. * `CompleteDistribLattice`: Complete distributive lattices: A complete lattice whose `⊓` and `⊔` distribute over `⨆` and `⨅` respectively. * `CompleteBooleanAlgebra`: Complete Boolean algebra: A Boolean algebra whose `⊓` and `⊔` distribute over `⨆` and `⨅` respectively. * `CompletelyDistribLattice`: Completely distributive lattices: A complete lattice whose `⨅` and `⨆` satisfy `iInf_iSup_eq`. * `CompleteBooleanAlgebra`: Complete Boolean algebra: A Boolean algebra whose `⊓` and `⊔` distribute over `⨆` and `⨅` respectively. * `CompleteAtomicBooleanAlgebra`: Complete atomic Boolean algebra: A complete Boolean algebra which is additionally completely distributive. (This implies that it's (co)atom(ist)ic.) A set of opens gives rise to a topological space precisely if it forms a frame. Such a frame is also completely distributive, but not all frames are. `Filter` is a coframe but not a completely distributive lattice. ## References * [Wikipedia, *Complete Heyting algebra*](https://en.wikipedia.org/wiki/Complete_Heyting_algebra) * [Francis Borceux, *Handbook of Categorical Algebra III*][borceux-vol3] -/ open Function Set universe u v w w' variable {α : Type u} {β : Type v} {ι : Sort w} {κ : ι → Sort w'} /-- Structure containing the minimal axioms required to check that an order is a frame. Do NOT use, except for implementing `Order.Frame` via `Order.Frame.ofMinimalAxioms`. This structure omits the `himp`, `compl` fields, which can be recovered using `Order.Frame.ofMinimalAxioms`. -/ class Order.Frame.MinimalAxioms (α : Type u) extends CompleteLattice α where inf_sSup_le_iSup_inf (a : α) (s : Set α) : a ⊓ sSup s ≤ ⨆ b ∈ s, a ⊓ b /-- Structure containing the minimal axioms required to check that an order is a coframe. Do NOT use, except for implementing `Order.Coframe` via `Order.Coframe.ofMinimalAxioms`. This structure omits the `sdiff`, `hnot` fields, which can be recovered using `Order.Coframe.ofMinimalAxioms`. -/ class Order.Coframe.MinimalAxioms (α : Type u) extends CompleteLattice α where iInf_sup_le_sup_sInf (a : α) (s : Set α) : ⨅ b ∈ s, a ⊔ b ≤ a ⊔ sInf s /-- A frame, aka complete Heyting algebra, is a complete lattice whose `⊓` distributes over `⨆`. -/ class Order.Frame (α : Type*) extends CompleteLattice α, HeytingAlgebra α where /-- `⊓` distributes over `⨆`. -/ theorem inf_sSup_eq {α : Type*} [Order.Frame α] {s : Set α} {a : α} : a ⊓ sSup s = ⨆ b ∈ s, a ⊓ b := gc_inf_himp.l_sSup /-- A coframe, aka complete Brouwer algebra or complete co-Heyting algebra, is a complete lattice whose `⊔` distributes over `⨅`. -/ class Order.Coframe (α : Type*) extends CompleteLattice α, CoheytingAlgebra α where /-- `⊔` distributes over `⨅`. -/ theorem sup_sInf_eq {α : Type*} [Order.Coframe α] {s : Set α} {a : α} : a ⊔ sInf s = ⨅ b ∈ s, a ⊔ b := gc_sdiff_sup.u_sInf open Order /-- Structure containing the minimal axioms required to check that an order is a complete distributive lattice. Do NOT use, except for implementing `CompleteDistribLattice` via `CompleteDistribLattice.ofMinimalAxioms`. This structure omits the `himp`, `compl`, `sdiff`, `hnot` fields, which can be recovered using `CompleteDistribLattice.ofMinimalAxioms`. -/ structure CompleteDistribLattice.MinimalAxioms (α : Type u) extends CompleteLattice α, toFrameMinimalAxioms : Frame.MinimalAxioms α, toCoframeMinimalAxioms : Coframe.MinimalAxioms α where -- We give those projections better name further down attribute [nolint docBlame] CompleteDistribLattice.MinimalAxioms.toFrameMinimalAxioms CompleteDistribLattice.MinimalAxioms.toCoframeMinimalAxioms /-- A complete distributive lattice is a complete lattice whose `⊔` and `⊓` respectively distribute over `⨅` and `⨆`. -/ class CompleteDistribLattice (α : Type*) extends Frame α, Coframe α, BiheytingAlgebra α /-- Structure containing the minimal axioms required to check that an order is a completely distributive. Do NOT use, except for implementing `CompletelyDistribLattice` via `CompletelyDistribLattice.ofMinimalAxioms`. This structure omits the `himp`, `compl`, `sdiff`, `hnot` fields, which can be recovered using `CompletelyDistribLattice.ofMinimalAxioms`. -/ structure CompletelyDistribLattice.MinimalAxioms (α : Type u) extends CompleteLattice α where protected iInf_iSup_eq {ι : Type u} {κ : ι → Type u} (f : ∀ a, κ a → α) : (⨅ a, ⨆ b, f a b) = ⨆ g : ∀ a, κ a, ⨅ a, f a (g a) /-- A completely distributive lattice is a complete lattice whose `⨅` and `⨆` distribute over each other. -/ class CompletelyDistribLattice (α : Type u) extends CompleteLattice α, BiheytingAlgebra α where protected iInf_iSup_eq {ι : Type u} {κ : ι → Type u} (f : ∀ a, κ a → α) : (⨅ a, ⨆ b, f a b) = ⨆ g : ∀ a, κ a, ⨅ a, f a (g a) theorem le_iInf_iSup [CompleteLattice α] {f : ∀ a, κ a → α} : (⨆ g : ∀ a, κ a, ⨅ a, f a (g a)) ≤ ⨅ a, ⨆ b, f a b := iSup_le fun _ => le_iInf fun a => le_trans (iInf_le _ a) (le_iSup _ _) lemma iSup_iInf_le [CompleteLattice α] {f : ∀ a, κ a → α} : ⨆ a, ⨅ b, f a b ≤ ⨅ g : ∀ a, κ a, ⨆ a, f a (g a) := le_iInf_iSup (α := αᵒᵈ) namespace Order.Frame.MinimalAxioms variable (minAx : MinimalAxioms α) {s : Set α} {a b : α} lemma inf_sSup_eq : a ⊓ sSup s = ⨆ b ∈ s, a ⊓ b := (minAx.inf_sSup_le_iSup_inf _ _).antisymm iSup_inf_le_inf_sSup lemma sSup_inf_eq : sSup s ⊓ b = ⨆ a ∈ s, a ⊓ b := by simpa only [inf_comm] using @inf_sSup_eq α _ s b lemma iSup_inf_eq (f : ι → α) (a : α) : (⨆ i, f i) ⊓ a = ⨆ i, f i ⊓ a := by rw [iSup, sSup_inf_eq, iSup_range] lemma inf_iSup_eq (a : α) (f : ι → α) : (a ⊓ ⨆ i, f i) = ⨆ i, a ⊓ f i := by simpa only [inf_comm] using minAx.iSup_inf_eq f a lemma inf_iSup₂_eq {f : ∀ i, κ i → α} (a : α) : (a ⊓ ⨆ i, ⨆ j, f i j) = ⨆ i, ⨆ j, a ⊓ f i j := by simp only [inf_iSup_eq] /-- The `Order.Frame.MinimalAxioms` element corresponding to a frame. -/ def of [Frame α] : MinimalAxioms α where __ := ‹Frame α› inf_sSup_le_iSup_inf a s := _root_.inf_sSup_eq.le end MinimalAxioms /-- Construct a frame instance using the minimal amount of work needed. This sets `a ⇨ b := sSup {c | c ⊓ a ≤ b}` and `aᶜ := a ⇨ ⊥`. -/ -- See note [reducible non-instances] abbrev ofMinimalAxioms (minAx : MinimalAxioms α) : Frame α where __ := minAx compl a := sSup {c | c ⊓ a ≤ ⊥} himp a b := sSup {c | c ⊓ a ≤ b} le_himp_iff _ b c := ⟨fun h ↦ (inf_le_inf_right _ h).trans (by simp [minAx.sSup_inf_eq]), fun h ↦ le_sSup h⟩ himp_bot _ := rfl end Order.Frame namespace Order.Coframe.MinimalAxioms variable (minAx : MinimalAxioms α) {s : Set α} {a b : α} lemma sup_sInf_eq : a ⊔ sInf s = ⨅ b ∈ s, a ⊔ b := sup_sInf_le_iInf_sup.antisymm (minAx.iInf_sup_le_sup_sInf _ _) lemma sInf_sup_eq : sInf s ⊔ b = ⨅ a ∈ s, a ⊔ b := by simpa only [sup_comm] using @sup_sInf_eq α _ s b lemma iInf_sup_eq (f : ι → α) (a : α) : (⨅ i, f i) ⊔ a = ⨅ i, f i ⊔ a := by rw [iInf, sInf_sup_eq, iInf_range] lemma sup_iInf_eq (a : α) (f : ι → α) : (a ⊔ ⨅ i, f i) = ⨅ i, a ⊔ f i := by simpa only [sup_comm] using minAx.iInf_sup_eq f a lemma sup_iInf₂_eq {f : ∀ i, κ i → α} (a : α) : (a ⊔ ⨅ i, ⨅ j, f i j) = ⨅ i, ⨅ j, a ⊔ f i j := by simp only [sup_iInf_eq] /-- The `Order.Coframe.MinimalAxioms` element corresponding to a frame. -/ def of [Coframe α] : MinimalAxioms α where __ := ‹Coframe α› iInf_sup_le_sup_sInf a s := _root_.sup_sInf_eq.ge end MinimalAxioms /-- Construct a coframe instance using the minimal amount of work needed. This sets `a \ b := sInf {c | a ≤ b ⊔ c}` and `¬a := ⊤ \ a`. -/ -- See note [reducible non-instances] abbrev ofMinimalAxioms (minAx : MinimalAxioms α) : Coframe α where __ := minAx hnot a := sInf {c | ⊤ ≤ a ⊔ c} sdiff a b := sInf {c | a ≤ b ⊔ c} sdiff_le_iff a b _ := ⟨fun h ↦ (sup_le_sup_left h _).trans' (by simp [minAx.sup_sInf_eq]), fun h ↦ sInf_le h⟩ top_sdiff _ := rfl end Order.Coframe namespace CompleteDistribLattice.MinimalAxioms variable (minAx : MinimalAxioms α) /-- The `CompleteDistribLattice.MinimalAxioms` element corresponding to a complete distrib lattice. -/ def of [CompleteDistribLattice α] : MinimalAxioms α where __ := ‹CompleteDistribLattice α› inf_sSup_le_iSup_inf a s:= inf_sSup_eq.le iInf_sup_le_sup_sInf a s:= sup_sInf_eq.ge /-- Turn minimal axioms for `CompleteDistribLattice` into minimal axioms for `Order.Frame`. -/ abbrev toFrame : Frame.MinimalAxioms α := minAx.toFrameMinimalAxioms /-- Turn minimal axioms for `CompleteDistribLattice` into minimal axioms for `Order.Coframe`. -/ abbrev toCoframe : Coframe.MinimalAxioms α where __ := minAx end MinimalAxioms /-- Construct a complete distrib lattice instance using the minimal amount of work needed. This sets `a ⇨ b := sSup {c | c ⊓ a ≤ b}`, `aᶜ := a ⇨ ⊥`, `a \ b := sInf {c | a ≤ b ⊔ c}` and `¬a := ⊤ \ a`. -/ -- See note [reducible non-instances] abbrev ofMinimalAxioms (minAx : MinimalAxioms α) : CompleteDistribLattice α where __ := Frame.ofMinimalAxioms minAx.toFrame __ := Coframe.ofMinimalAxioms minAx.toCoframe end CompleteDistribLattice namespace CompletelyDistribLattice.MinimalAxioms variable (minAx : MinimalAxioms α) lemma iInf_iSup_eq' (f : ∀ a, κ a → α) : let _ := minAx.toCompleteLattice ⨅ i, ⨆ j, f i j = ⨆ g : ∀ i, κ i, ⨅ i, f i (g i) := by let _ := minAx.toCompleteLattice refine le_antisymm ?_ le_iInf_iSup calc _ = ⨅ a : range (range <| f ·), ⨆ b : a.1, b.1 := by simp_rw [iInf_subtype, iInf_range, iSup_subtype, iSup_range] _ = _ := minAx.iInf_iSup_eq _ _ ≤ _ := iSup_le fun g => by refine le_trans ?_ <| le_iSup _ fun a => Classical.choose (g ⟨_, a, rfl⟩).2 refine le_iInf fun a => le_trans (iInf_le _ ⟨range (f a), a, rfl⟩) ?_ rw [← Classical.choose_spec (g ⟨_, a, rfl⟩).2] lemma iSup_iInf_eq (f : ∀ i, κ i → α) : let _ := minAx.toCompleteLattice ⨆ i, ⨅ j, f i j = ⨅ g : ∀ i, κ i, ⨆ i, f i (g i) := by let _ := minAx.toCompleteLattice refine le_antisymm iSup_iInf_le ?_ rw [minAx.iInf_iSup_eq'] refine iSup_le fun g => ?_ have ⟨a, ha⟩ : ∃ a, ∀ b, ∃ f, ∃ h : a = g f, h ▸ b = f (g f) := by by_contra! h choose h hh using h have := hh _ h rfl contradiction refine le_trans ?_ (le_iSup _ a) refine le_iInf fun b => ?_ obtain ⟨h, rfl, rfl⟩ := ha b exact iInf_le _ _ /-- Turn minimal axioms for `CompletelyDistribLattice` into minimal axioms for `CompleteDistribLattice`. -/ abbrev toCompleteDistribLattice : CompleteDistribLattice.MinimalAxioms α where __ := minAx inf_sSup_le_iSup_inf a s := by let _ := minAx.toCompleteLattice calc _ = ⨅ i : ULift.{u} Bool, ⨆ j : match i with | .up true => PUnit.{u + 1} | .up false => s, match i with | .up true => a | .up false => j := by simp [sSup_eq_iSup', iSup_unique, iInf_bool_eq] _ ≤ _ := by simp only [minAx.iInf_iSup_eq, iInf_ulift, iInf_bool_eq, iSup_le_iff] exact fun x ↦ le_biSup _ (x (.up false)).2 iInf_sup_le_sup_sInf a s := by let _ := minAx.toCompleteLattice calc _ ≤ ⨆ i : ULift.{u} Bool, ⨅ j : match i with | .up true => PUnit.{u + 1} | .up false => s, match i with | .up true => a | .up false => j := by simp only [minAx.iSup_iInf_eq, iSup_ulift, iSup_bool_eq, le_iInf_iff] exact fun x ↦ biInf_le _ (x (.up false)).2 _ = _ := by simp [sInf_eq_iInf', iInf_unique, iSup_bool_eq] /-- The `CompletelyDistribLattice.MinimalAxioms` element corresponding to a frame. -/ def of [CompletelyDistribLattice α] : MinimalAxioms α := { ‹CompletelyDistribLattice α› with } end MinimalAxioms /-- Construct a completely distributive lattice instance using the minimal amount of work needed. This sets `a ⇨ b := sSup {c | c ⊓ a ≤ b}`, `aᶜ := a ⇨ ⊥`, `a \ b := sInf {c | a ≤ b ⊔ c}` and `¬a := ⊤ \ a`. -/ -- See note [reducible non-instances] abbrev ofMinimalAxioms (minAx : MinimalAxioms α) : CompletelyDistribLattice α where __ := minAx __ := CompleteDistribLattice.ofMinimalAxioms minAx.toCompleteDistribLattice end CompletelyDistribLattice theorem iInf_iSup_eq [CompletelyDistribLattice α] {f : ∀ a, κ a → α} : (⨅ a, ⨆ b, f a b) = ⨆ g : ∀ a, κ a, ⨅ a, f a (g a) := CompletelyDistribLattice.MinimalAxioms.of.iInf_iSup_eq' _ theorem iSup_iInf_eq [CompletelyDistribLattice α] {f : ∀ a, κ a → α} : (⨆ a, ⨅ b, f a b) = ⨅ g : ∀ a, κ a, ⨆ a, f a (g a) := CompletelyDistribLattice.MinimalAxioms.of.iSup_iInf_eq _ theorem biSup_iInter_of_pairwise_disjoint [CompletelyDistribLattice α] {ι κ : Type*} [hκ : Nonempty κ] {f : ι → α} (h : Pairwise (Disjoint on f)) (s : κ → Set ι) : (⨆ i ∈ (⋂ j, s j), f i) = ⨅ j, (⨆ i ∈ s j, f i) := by rcases hκ with ⟨j⟩ simp_rw [iInf_iSup_eq, mem_iInter] refine le_antisymm (iSup₂_le fun i hi ↦ le_iSup₂_of_le (fun _ ↦ i) hi (le_iInf fun _ ↦ le_rfl)) (iSup₂_le fun I hI ↦ ?_) by_cases H : ∀ k, I k = I j · exact le_iSup₂_of_le (I j) (fun k ↦ (H k) ▸ (hI k)) (iInf_le _ _) · push_neg at H rcases H with ⟨k, hk⟩ calc ⨅ l, f (I l) _ ≤ f (I k) ⊓ f (I j) := le_inf (iInf_le _ _) (iInf_le _ _) _ = ⊥ := (h hk).eq_bot _ ≤ _ := bot_le instance (priority := 100) CompletelyDistribLattice.toCompleteDistribLattice [CompletelyDistribLattice α] : CompleteDistribLattice α where __ := ‹CompletelyDistribLattice α› -- See note [lower instance priority] instance (priority := 100) CompleteLinearOrder.toCompletelyDistribLattice [CompleteLinearOrder α] : CompletelyDistribLattice α where __ := ‹CompleteLinearOrder α› iInf_iSup_eq {α β} g := by let lhs := ⨅ a, ⨆ b, g a b let rhs := ⨆ h : ∀ a, β a, ⨅ a, g a (h a) suffices lhs ≤ rhs from le_antisymm this le_iInf_iSup if h : ∃ x, rhs < x ∧ x < lhs then rcases h with ⟨x, hr, hl⟩ suffices rhs ≥ x from nomatch not_lt.2 this hr have : ∀ a, ∃ b, x < g a b := fun a => lt_iSup_iff.1 <| lt_of_not_ge fun h => lt_irrefl x (lt_of_lt_of_le hl (le_trans (iInf_le _ a) h)) choose f hf using this refine le_trans ?_ (le_iSup _ f) exact le_iInf fun a => le_of_lt (hf a) else refine le_of_not_gt fun hrl : rhs < lhs => not_le_of_gt hrl ?_ replace h : ∀ x, x ≤ rhs ∨ lhs ≤ x := by simpa only [not_exists, not_and_or, not_or, not_lt] using h have : ∀ a, ∃ b, rhs < g a b := fun a => lt_iSup_iff.1 <| lt_of_lt_of_le hrl (iInf_le _ a) choose f hf using this have : ∀ a, lhs ≤ g a (f a) := fun a => (h (g a (f a))).resolve_left (by simpa using hf a) refine le_trans ?_ (le_iSup _ f) exact le_iInf fun a => this _ section Frame variable [Frame α] {s t : Set α} {a b c d : α} instance OrderDual.instCoframe : Coframe αᵒᵈ where __ := instCompleteLattice __ := instCoheytingAlgebra theorem sSup_inf_eq : sSup s ⊓ b = ⨆ a ∈ s, a ⊓ b := by simpa only [inf_comm] using @inf_sSup_eq α _ s b theorem iSup_inf_eq (f : ι → α) (a : α) : (⨆ i, f i) ⊓ a = ⨆ i, f i ⊓ a := by rw [iSup, sSup_inf_eq, iSup_range] theorem inf_iSup_eq (a : α) (f : ι → α) : (a ⊓ ⨆ i, f i) = ⨆ i, a ⊓ f i := by simpa only [inf_comm] using iSup_inf_eq f a theorem iSup₂_inf_eq {f : ∀ i, κ i → α} (a : α) : (⨆ (i) (j), f i j) ⊓ a = ⨆ (i) (j), f i j ⊓ a := by simp only [iSup_inf_eq] theorem inf_iSup₂_eq {f : ∀ i, κ i → α} (a : α) : (a ⊓ ⨆ (i) (j), f i j) = ⨆ (i) (j), a ⊓ f i j := by simp only [inf_iSup_eq] theorem iSup_inf_iSup {ι ι' : Type*} {f : ι → α} {g : ι' → α} : ((⨆ i, f i) ⊓ ⨆ j, g j) = ⨆ i : ι × ι', f i.1 ⊓ g i.2 := by simp_rw [iSup_inf_eq, inf_iSup_eq, iSup_prod] theorem biSup_inf_biSup {ι ι' : Type*} {f : ι → α} {g : ι' → α} {s : Set ι} {t : Set ι'} : ((⨆ i ∈ s, f i) ⊓ ⨆ j ∈ t, g j) = ⨆ p ∈ s ×ˢ t, f (p : ι × ι').1 ⊓ g p.2 := by simp only [iSup_subtype', iSup_inf_iSup] exact (Equiv.surjective _).iSup_congr (Equiv.Set.prod s t).symm fun x => rfl theorem sSup_inf_sSup : sSup s ⊓ sSup t = ⨆ p ∈ s ×ˢ t, (p : α × α).1 ⊓ p.2 := by simp only [sSup_eq_iSup, biSup_inf_biSup] theorem biSup_inter_of_pairwise_disjoint {ι : Type*} {f : ι → α} (h : Pairwise (Disjoint on f)) (s t : Set ι) : (⨆ i ∈ (s ∩ t), f i) = (⨆ i ∈ s, f i) ⊓ (⨆ i ∈ t, f i) := by rw [biSup_inf_biSup] refine le_antisymm (iSup₂_le fun i ⟨his, hit⟩ ↦ le_iSup₂_of_le ⟨i, i⟩ ⟨his, hit⟩ (le_inf le_rfl le_rfl)) (iSup₂_le fun ⟨i, j⟩ ⟨his, hjs⟩ ↦ ?_) by_cases hij : i = j · exact le_iSup₂_of_le i ⟨his, hij ▸ hjs⟩ inf_le_left · simp [h hij |>.eq_bot] theorem iSup_disjoint_iff {f : ι → α} : Disjoint (⨆ i, f i) a ↔ ∀ i, Disjoint (f i) a := by simp only [disjoint_iff, iSup_inf_eq, iSup_eq_bot] theorem disjoint_iSup_iff {f : ι → α} : Disjoint a (⨆ i, f i) ↔ ∀ i, Disjoint a (f i) := by simpa only [disjoint_comm] using @iSup_disjoint_iff theorem iSup₂_disjoint_iff {f : ∀ i, κ i → α} : Disjoint (⨆ (i) (j), f i j) a ↔ ∀ i j, Disjoint (f i j) a := by simp_rw [iSup_disjoint_iff] theorem disjoint_iSup₂_iff {f : ∀ i, κ i → α} : Disjoint a (⨆ (i) (j), f i j) ↔ ∀ i j, Disjoint a (f i j) := by simp_rw [disjoint_iSup_iff] theorem sSup_disjoint_iff {s : Set α} : Disjoint (sSup s) a ↔ ∀ b ∈ s, Disjoint b a := by simp only [disjoint_iff, sSup_inf_eq, iSup_eq_bot] theorem disjoint_sSup_iff {s : Set α} : Disjoint a (sSup s) ↔ ∀ b ∈ s, Disjoint a b := by simpa only [disjoint_comm] using @sSup_disjoint_iff theorem iSup_inf_of_monotone {ι : Type*} [Preorder ι] [IsDirected ι (· ≤ ·)] {f g : ι → α} (hf : Monotone f) (hg : Monotone g) : ⨆ i, f i ⊓ g i = (⨆ i, f i) ⊓ ⨆ i, g i := by refine (le_iSup_inf_iSup f g).antisymm ?_ rw [iSup_inf_iSup] refine iSup_mono' fun i => ?_ rcases directed_of (· ≤ ·) i.1 i.2 with ⟨j, h₁, h₂⟩ exact ⟨j, inf_le_inf (hf h₁) (hg h₂)⟩ theorem iSup_inf_of_antitone {ι : Type*} [Preorder ι] [IsDirected ι (swap (· ≤ ·))] {f g : ι → α} (hf : Antitone f) (hg : Antitone g) : ⨆ i, f i ⊓ g i = (⨆ i, f i) ⊓ ⨆ i, g i := @iSup_inf_of_monotone α _ ιᵒᵈ _ _ f g hf.dual_left hg.dual_left theorem himp_eq_sSup : a ⇨ b = sSup {w | w ⊓ a ≤ b} := (isGreatest_himp a b).isLUB.sSup_eq.symm theorem compl_eq_sSup_disjoint : aᶜ = sSup {w | Disjoint w a} := (isGreatest_compl a).isLUB.sSup_eq.symm lemma himp_le_iff : a ⇨ b ≤ c ↔ ∀ d, d ⊓ a ≤ b → d ≤ c := by simp [himp_eq_sSup] -- see Note [lower instance priority] instance (priority := 100) Frame.toDistribLattice : DistribLattice α := DistribLattice.ofInfSupLe fun a b c => by rw [← sSup_pair, ← sSup_pair, inf_sSup_eq, ← sSup_image, image_pair] instance Prod.instFrame [Frame α] [Frame β] : Frame (α × β) where __ := instCompleteLattice __ := instHeytingAlgebra instance Pi.instFrame {ι : Type*} {π : ι → Type*} [∀ i, Frame (π i)] : Frame (∀ i, π i) where __ := instCompleteLattice __ := instHeytingAlgebra end Frame section Coframe variable [Coframe α] {s t : Set α} {a b c d : α} instance OrderDual.instFrame : Frame αᵒᵈ where __ := instCompleteLattice __ := instHeytingAlgebra theorem sInf_sup_eq : sInf s ⊔ b = ⨅ a ∈ s, a ⊔ b := @sSup_inf_eq αᵒᵈ _ _ _ theorem iInf_sup_eq (f : ι → α) (a : α) : (⨅ i, f i) ⊔ a = ⨅ i, f i ⊔ a := @iSup_inf_eq αᵒᵈ _ _ _ _ theorem sup_iInf_eq (a : α) (f : ι → α) : (a ⊔ ⨅ i, f i) = ⨅ i, a ⊔ f i := @inf_iSup_eq αᵒᵈ _ _ _ _ theorem iInf₂_sup_eq {f : ∀ i, κ i → α} (a : α) : (⨅ (i) (j), f i j) ⊔ a = ⨅ (i) (j), f i j ⊔ a := @iSup₂_inf_eq αᵒᵈ _ _ _ _ _ theorem sup_iInf₂_eq {f : ∀ i, κ i → α} (a : α) : (a ⊔ ⨅ (i) (j), f i j) = ⨅ (i) (j), a ⊔ f i j := @inf_iSup₂_eq αᵒᵈ _ _ _ _ _ theorem iInf_sup_iInf {ι ι' : Type*} {f : ι → α} {g : ι' → α} : ((⨅ i, f i) ⊔ ⨅ i, g i) = ⨅ i : ι × ι', f i.1 ⊔ g i.2 := @iSup_inf_iSup αᵒᵈ _ _ _ _ _ theorem biInf_sup_biInf {ι ι' : Type*} {f : ι → α} {g : ι' → α} {s : Set ι} {t : Set ι'} : ((⨅ i ∈ s, f i) ⊔ ⨅ j ∈ t, g j) = ⨅ p ∈ s ×ˢ t, f (p : ι × ι').1 ⊔ g p.2 := @biSup_inf_biSup αᵒᵈ _ _ _ _ _ _ _ theorem sInf_sup_sInf : sInf s ⊔ sInf t = ⨅ p ∈ s ×ˢ t, (p : α × α).1 ⊔ p.2 := @sSup_inf_sSup αᵒᵈ _ _ _ theorem iInf_sup_of_monotone {ι : Type*} [Preorder ι] [IsDirected ι (swap (· ≤ ·))] {f g : ι → α} (hf : Monotone f) (hg : Monotone g) : ⨅ i, f i ⊔ g i = (⨅ i, f i) ⊔ ⨅ i, g i := @iSup_inf_of_antitone αᵒᵈ _ _ _ _ _ _ hf.dual_right hg.dual_right theorem iInf_sup_of_antitone {ι : Type*} [Preorder ι] [IsDirected ι (· ≤ ·)] {f g : ι → α} (hf : Antitone f) (hg : Antitone g) : ⨅ i, f i ⊔ g i = (⨅ i, f i) ⊔ ⨅ i, g i := @iSup_inf_of_monotone αᵒᵈ _ _ _ _ _ _ hf.dual_right hg.dual_right theorem sdiff_eq_sInf : a \ b = sInf {w | a ≤ b ⊔ w} := (isLeast_sdiff a b).isGLB.sInf_eq.symm theorem hnot_eq_sInf_codisjoint : ¬a = sInf {w | Codisjoint a w} := (isLeast_hnot a).isGLB.sInf_eq.symm lemma le_sdiff_iff : a ≤ b \ c ↔ ∀ d, b ≤ c ⊔ d → a ≤ d := by simp [sdiff_eq_sInf] -- see Note [lower instance priority] instance (priority := 100) Coframe.toDistribLattice : DistribLattice α where __ := ‹Coframe α› le_sup_inf a b c := by rw [← sInf_pair, ← sInf_pair, sup_sInf_eq, ← sInf_image, image_pair] instance Prod.instCoframe [Coframe β] : Coframe (α × β) where __ := instCompleteLattice __ := instCoheytingAlgebra instance Pi.instCoframe {ι : Type*} {π : ι → Type*} [∀ i, Coframe (π i)] : Coframe (∀ i, π i) where __ := instCompleteLattice __ := instCoheytingAlgebra end Coframe section CompleteDistribLattice variable [CompleteDistribLattice α] instance OrderDual.instCompleteDistribLattice [CompleteDistribLattice α] : CompleteDistribLattice αᵒᵈ where __ := instFrame __ := instCoframe instance Prod.instCompleteDistribLattice [CompleteDistribLattice β] : CompleteDistribLattice (α × β) where __ := instFrame __ := instCoframe instance Pi.instCompleteDistribLattice {ι : Type*} {π : ι → Type*} [∀ i, CompleteDistribLattice (π i)] : CompleteDistribLattice (∀ i, π i) where __ := instFrame __ := instCoframe end CompleteDistribLattice section CompletelyDistribLattice instance OrderDual.instCompletelyDistribLattice [CompletelyDistribLattice α] : CompletelyDistribLattice αᵒᵈ where __ := instFrame __ := instCoframe iInf_iSup_eq _ := iSup_iInf_eq (α := α) instance Prod.instCompletelyDistribLattice [CompletelyDistribLattice α] [CompletelyDistribLattice β] : CompletelyDistribLattice (α × β) where __ := instFrame __ := instCoframe iInf_iSup_eq f := by ext <;> simp [fst_iSup, fst_iInf, snd_iSup, snd_iInf, iInf_iSup_eq] instance Pi.instCompletelyDistribLattice {ι : Type*} {π : ι → Type*} [∀ i, CompletelyDistribLattice (π i)] : CompletelyDistribLattice (∀ i, π i) where __ := instFrame __ := instCoframe iInf_iSup_eq f := by ext i; simp only [iInf_apply, iSup_apply, iInf_iSup_eq] end CompletelyDistribLattice /-- A complete Boolean algebra is a Boolean algebra that is also a complete distributive lattice. It is only completely distributive if it is also atomic. -/ -- We do not directly extend `CompleteDistribLattice` to avoid having the `hnot` field class CompleteBooleanAlgebra (α) extends CompleteLattice α, BooleanAlgebra α -- See note [lower instance priority] instance (priority := 100) CompleteBooleanAlgebra.toCompleteDistribLattice [CompleteBooleanAlgebra α] : CompleteDistribLattice α where __ := ‹CompleteBooleanAlgebra α› __ := BooleanAlgebra.toBiheytingAlgebra instance Prod.instCompleteBooleanAlgebra [CompleteBooleanAlgebra α] [CompleteBooleanAlgebra β] : CompleteBooleanAlgebra (α × β) where __ := instBooleanAlgebra __ := instCompleteDistribLattice instance Pi.instCompleteBooleanAlgebra {ι : Type*} {π : ι → Type*} [∀ i, CompleteBooleanAlgebra (π i)] : CompleteBooleanAlgebra (∀ i, π i) where __ := instBooleanAlgebra __ := instCompleteDistribLattice instance OrderDual.instCompleteBooleanAlgebra [CompleteBooleanAlgebra α] : CompleteBooleanAlgebra αᵒᵈ where __ := instBooleanAlgebra __ := instCompleteDistribLattice section CompleteBooleanAlgebra variable [CompleteBooleanAlgebra α] {s : Set α} {f : ι → α} @[deprecated "use `inf_sSup_eq.le` instead" (since := "2025-06-15")] theorem inf_sSup_le_iSup_inf (a : α) (s : Set α) : a ⊓ sSup s ≤ ⨆ b ∈ s, a ⊓ b := gc_inf_himp.l_sSup.le @[deprecated "use `sup_sInf_eq.ge` instead" (since := "2025-06-15")] theorem iInf_sup_le_sup_sInf (a : α) (s : Set α) : ⨅ b ∈ s, a ⊔ b ≤ a ⊔ sInf s := gc_sdiff_sup.u_sInf.ge theorem compl_iInf : (iInf f)ᶜ = ⨆ i, (f i)ᶜ := le_antisymm (compl_le_of_compl_le <| le_iInf fun i => compl_le_of_compl_le <| le_iSup (HasCompl.compl ∘ f) i) (iSup_le fun _ => compl_le_compl <| iInf_le _ _) theorem compl_iSup : (iSup f)ᶜ = ⨅ i, (f i)ᶜ := compl_injective (by simp [compl_iInf]) theorem compl_sInf : (sInf s)ᶜ = ⨆ i ∈ s, iᶜ := by simp only [sInf_eq_iInf, compl_iInf] theorem compl_sSup : (sSup s)ᶜ = ⨅ i ∈ s, iᶜ := by simp only [sSup_eq_iSup, compl_iSup] theorem compl_sInf' : (sInf s)ᶜ = sSup (HasCompl.compl '' s) := compl_sInf.trans sSup_image.symm theorem compl_sSup' : (sSup s)ᶜ = sInf (HasCompl.compl '' s) := compl_sSup.trans sInf_image.symm open scoped symmDiff in /-- The symmetric difference of two `iSup`s is at most the `iSup` of the symmetric differences. -/ theorem iSup_symmDiff_iSup_le {g : ι → α} : (⨆ i, f i) ∆ (⨆ i, g i) ≤ ⨆ i, ((f i) ∆ (g i)) := by simp_rw [symmDiff_le_iff, ← iSup_sup_eq] exact ⟨iSup_mono fun i ↦ sup_comm (g i) _ ▸ le_symmDiff_sup_right .., iSup_mono fun i ↦ sup_comm (f i) _ ▸ symmDiff_comm (f i) _ ▸ le_symmDiff_sup_right ..⟩ open scoped symmDiff in /-- A `biSup` version of `iSup_symmDiff_iSup_le`. -/ theorem biSup_symmDiff_biSup_le {p : ι → Prop} {f g : (i : ι) → p i → α} : (⨆ i, ⨆ (h : p i), f i h) ∆ (⨆ i, ⨆ (h : p i), g i h) ≤ ⨆ i, ⨆ (h : p i), ((f i h) ∆ (g i h)) := le_trans iSup_symmDiff_iSup_le <| iSup_mono fun _ ↦ iSup_symmDiff_iSup_le end CompleteBooleanAlgebra /-- A complete atomic Boolean algebra is a complete Boolean algebra that is also completely distributive. We take iSup_iInf_eq as the definition here, and prove later on that this implies atomicity. -/ -- We do not directly extend `CompletelyDistribLattice` to avoid having the `hnot` field class CompleteAtomicBooleanAlgebra (α : Type u) extends CompleteBooleanAlgebra α where protected iInf_iSup_eq {ι : Type u} {κ : ι → Type u} (f : ∀ a, κ a → α) : (⨅ a, ⨆ b, f a b) = ⨆ g : ∀ a, κ a, ⨅ a, f a (g a) -- See note [lower instance priority] instance (priority := 100) CompleteAtomicBooleanAlgebra.toCompletelyDistribLattice [CompleteAtomicBooleanAlgebra α] : CompletelyDistribLattice α where __ := ‹CompleteAtomicBooleanAlgebra α› __ := BooleanAlgebra.toBiheytingAlgebra instance Prod.instCompleteAtomicBooleanAlgebra [CompleteAtomicBooleanAlgebra α] [CompleteAtomicBooleanAlgebra β] : CompleteAtomicBooleanAlgebra (α × β) where __ := instBooleanAlgebra __ := instCompletelyDistribLattice instance Pi.instCompleteAtomicBooleanAlgebra {ι : Type*} {π : ι → Type*} [∀ i, CompleteAtomicBooleanAlgebra (π i)] : CompleteAtomicBooleanAlgebra (∀ i, π i) where __ := Pi.instCompleteBooleanAlgebra iInf_iSup_eq f := by ext; rw [iInf_iSup_eq] instance OrderDual.instCompleteAtomicBooleanAlgebra [CompleteAtomicBooleanAlgebra α] : CompleteAtomicBooleanAlgebra αᵒᵈ where __ := instCompleteBooleanAlgebra __ := instCompletelyDistribLattice instance Prop.instCompleteAtomicBooleanAlgebra : CompleteAtomicBooleanAlgebra Prop where __ := Prop.instCompleteLattice __ := Prop.instBooleanAlgebra iInf_iSup_eq f := by simp [Classical.skolem] instance Prop.instCompleteBooleanAlgebra : CompleteBooleanAlgebra Prop := inferInstance section lift -- See note [reducible non-instances] /-- Pullback an `Order.Frame.MinimalAxioms` along an injection. -/ protected abbrev Function.Injective.frameMinimalAxioms [Max α] [Min α] [SupSet α] [InfSet α] [Top α] [Bot α] (minAx : Frame.MinimalAxioms β) (f : α → β) (hf : Injective f) (map_sup : ∀ a b, f (a ⊔ b) = f a ⊔ f b) (map_inf : ∀ a b, f (a ⊓ b) = f a ⊓ f b) (map_sSup : ∀ s, f (sSup s) = ⨆ a ∈ s, f a) (map_sInf : ∀ s, f (sInf s) = ⨅ a ∈ s, f a) (map_top : f ⊤ = ⊤) (map_bot : f ⊥ = ⊥) : Frame.MinimalAxioms α where __ := hf.completeLattice f map_sup map_inf map_sSup map_sInf map_top map_bot inf_sSup_le_iSup_inf a s := by change f (a ⊓ sSup s) ≤ f _ rw [← sSup_image, map_inf, map_sSup s, minAx.inf_iSup₂_eq] simp_rw [← map_inf] exact ((map_sSup _).trans iSup_image).ge -- See note [reducible non-instances] /-- Pullback an `Order.Coframe.MinimalAxioms` along an injection. -/ protected abbrev Function.Injective.coframeMinimalAxioms [Max α] [Min α] [SupSet α] [InfSet α] [Top α] [Bot α] (minAx : Coframe.MinimalAxioms β) (f : α → β) (hf : Injective f) (map_sup : ∀ a b, f (a ⊔ b) = f a ⊔ f b) (map_inf : ∀ a b, f (a ⊓ b) = f a ⊓ f b) (map_sSup : ∀ s, f (sSup s) = ⨆ a ∈ s, f a) (map_sInf : ∀ s, f (sInf s) = ⨅ a ∈ s, f a) (map_top : f ⊤ = ⊤) (map_bot : f ⊥ = ⊥) : Coframe.MinimalAxioms α where __ := hf.completeLattice f map_sup map_inf map_sSup map_sInf map_top map_bot iInf_sup_le_sup_sInf a s := by change f _ ≤ f (a ⊔ sInf s) rw [← sInf_image, map_sup, map_sInf s, minAx.sup_iInf₂_eq] simp_rw [← map_sup] exact ((map_sInf _).trans iInf_image).le -- See note [reducible non-instances] /-- Pullback an `Order.Frame` along an injection. -/ protected abbrev Function.Injective.frame [Max α] [Min α] [SupSet α] [InfSet α] [Top α] [Bot α] [HasCompl α] [HImp α] [Frame β] (f : α → β) (hf : Injective f) (map_sup : ∀ a b, f (a ⊔ b) = f a ⊔ f b) (map_inf : ∀ a b, f (a ⊓ b) = f a ⊓ f b) (map_sSup : ∀ s, f (sSup s) = ⨆ a ∈ s, f a) (map_sInf : ∀ s, f (sInf s) = ⨅ a ∈ s, f a) (map_top : f ⊤ = ⊤) (map_bot : f ⊥ = ⊥) (map_compl : ∀ a, f aᶜ = (f a)ᶜ) (map_himp : ∀ a b, f (a ⇨ b) = f a ⇨ f b) : Frame α where __ := hf.frameMinimalAxioms .of f map_sup map_inf map_sSup map_sInf map_top map_bot __ := hf.heytingAlgebra f map_sup map_inf map_top map_bot map_compl map_himp -- See note [reducible non-instances] /-- Pullback an `Order.Coframe` along an injection. -/ protected abbrev Function.Injective.coframe [Max α] [Min α] [SupSet α] [InfSet α] [Top α] [Bot α] [HNot α] [SDiff α] [Coframe β] (f : α → β) (hf : Injective f) (map_sup : ∀ a b, f (a ⊔ b) = f a ⊔ f b) (map_inf : ∀ a b, f (a ⊓ b) = f a ⊓ f b) (map_sSup : ∀ s, f (sSup s) = ⨆ a ∈ s, f a) (map_sInf : ∀ s, f (sInf s) = ⨅ a ∈ s, f a) (map_top : f ⊤ = ⊤) (map_bot : f ⊥ = ⊥) (map_hnot : ∀ a, f (¬a) = ¬f a) (map_sdiff : ∀ a b, f (a \ b) = f a \ f b) : Coframe α where __ := hf.coframeMinimalAxioms .of f map_sup map_inf map_sSup map_sInf map_top map_bot __ := hf.coheytingAlgebra f map_sup map_inf map_top map_bot map_hnot map_sdiff -- See note [reducible non-instances] /-- Pullback a `CompleteDistribLattice.MinimalAxioms` along an injection. -/ protected abbrev Function.Injective.completeDistribLatticeMinimalAxioms [Max α] [Min α] [SupSet α] [InfSet α] [Top α] [Bot α] (minAx : CompleteDistribLattice.MinimalAxioms β) (f : α → β) (hf : Injective f) (map_sup : let _ := minAx.toCompleteLattice ∀ a b, f (a ⊔ b) = f a ⊔ f b) (map_inf : let _ := minAx.toCompleteLattice ∀ a b, f (a ⊓ b) = f a ⊓ f b) (map_sSup : let _ := minAx.toCompleteLattice ∀ s, f (sSup s) = ⨆ a ∈ s, f a) (map_sInf : let _ := minAx.toCompleteLattice ∀ s, f (sInf s) = ⨅ a ∈ s, f a) (map_top : let _ := minAx.toCompleteLattice f ⊤ = ⊤) (map_bot : let _ := minAx.toCompleteLattice f ⊥ = ⊥) : CompleteDistribLattice.MinimalAxioms α where __ := hf.frameMinimalAxioms minAx.toFrame f map_sup map_inf map_sSup map_sInf map_top map_bot __ := hf.coframeMinimalAxioms minAx.toCoframe f map_sup map_inf map_sSup map_sInf map_top map_bot -- See note [reducible non-instances] /-- Pullback a `CompleteDistribLattice` along an injection. -/ protected abbrev Function.Injective.completeDistribLattice [Max α] [Min α] [SupSet α] [InfSet α] [Top α] [Bot α] [HasCompl α] [HImp α] [HNot α] [SDiff α] [CompleteDistribLattice β] (f : α → β) (hf : Injective f) (map_sup : ∀ a b, f (a ⊔ b) = f a ⊔ f b) (map_inf : ∀ a b, f (a ⊓ b) = f a ⊓ f b) (map_sSup : ∀ s, f (sSup s) = ⨆ a ∈ s, f a) (map_sInf : ∀ s, f (sInf s) = ⨅ a ∈ s, f a) (map_top : f ⊤ = ⊤) (map_bot : f ⊥ = ⊥) (map_compl : ∀ a, f aᶜ = (f a)ᶜ) (map_himp : ∀ a b, f (a ⇨ b) = f a ⇨ f b) (map_hnot : ∀ a, f (¬a) = ¬f a) (map_sdiff : ∀ a b, f (a \ b) = f a \ f b) : CompleteDistribLattice α where __ := hf.frame f map_sup map_inf map_sSup map_sInf map_top map_bot map_compl map_himp __ := hf.coframe f map_sup map_inf map_sSup map_sInf map_top map_bot map_hnot map_sdiff -- See note [reducible non-instances] /-- Pullback a `CompletelyDistribLattice.MinimalAxioms` along an injection. -/ protected abbrev Function.Injective.completelyDistribLatticeMinimalAxioms [Max α] [Min α] [SupSet α] [InfSet α] [Top α] [Bot α] (minAx : CompletelyDistribLattice.MinimalAxioms β) (f : α → β) (hf : Injective f) (map_sup : let _ := minAx.toCompleteLattice ∀ a b, f (a ⊔ b) = f a ⊔ f b) (map_inf : let _ := minAx.toCompleteLattice ∀ a b, f (a ⊓ b) = f a ⊓ f b) (map_sSup : let _ := minAx.toCompleteLattice ∀ s, f (sSup s) = ⨆ a ∈ s, f a) (map_sInf : let _ := minAx.toCompleteLattice ∀ s, f (sInf s) = ⨅ a ∈ s, f a) (map_top : let _ := minAx.toCompleteLattice f ⊤ = ⊤) (map_bot : let _ := minAx.toCompleteLattice f ⊥ = ⊥) : CompletelyDistribLattice.MinimalAxioms α where __ := hf.completeDistribLatticeMinimalAxioms minAx.toCompleteDistribLattice f map_sup map_inf map_sSup map_sInf map_top map_bot iInf_iSup_eq g := hf <| by simp_rw [iInf, map_sInf, iInf_range, iSup, map_sSup, iSup_range, map_sInf, iInf_range, minAx.iInf_iSup_eq'] -- See note [reducible non-instances] /-- Pullback a `CompletelyDistribLattice` along an injection. -/ protected abbrev Function.Injective.completelyDistribLattice [Max α] [Min α] [SupSet α] [InfSet α] [Top α] [Bot α] [HasCompl α] [HImp α] [HNot α] [SDiff α] [CompletelyDistribLattice β] (f : α → β) (hf : Injective f) (map_sup : ∀ a b, f (a ⊔ b) = f a ⊔ f b) (map_inf : ∀ a b, f (a ⊓ b) = f a ⊓ f b) (map_sSup : ∀ s, f (sSup s) = ⨆ a ∈ s, f a) (map_sInf : ∀ s, f (sInf s) = ⨅ a ∈ s, f a) (map_top : f ⊤ = ⊤) (map_bot : f ⊥ = ⊥) (map_compl : ∀ a, f aᶜ = (f a)ᶜ) (map_himp : ∀ a b, f (a ⇨ b) = f a ⇨ f b) (map_hnot : ∀ a, f (¬a) = ¬f a) (map_sdiff : ∀ a b, f (a \ b) = f a \ f b) : CompletelyDistribLattice α where __ := hf.completeLattice f map_sup map_inf map_sSup map_sInf map_top map_bot __ := hf.biheytingAlgebra f map_sup map_inf map_top map_bot map_compl map_hnot map_himp map_sdiff iInf_iSup_eq g := hf <| by simp_rw [iInf, map_sInf, iInf_range, iSup, map_sSup, iSup_range, map_sInf, iInf_range, iInf_iSup_eq] -- See note [reducible non-instances] /-- Pullback a `CompleteBooleanAlgebra` along an injection. -/ protected abbrev Function.Injective.completeBooleanAlgebra [Max α] [Min α] [SupSet α] [InfSet α] [Top α] [Bot α] [HasCompl α] [HImp α] [SDiff α] [CompleteBooleanAlgebra β] (f : α → β) (hf : Injective f) (map_sup : ∀ a b, f (a ⊔ b) = f a ⊔ f b) (map_inf : ∀ a b, f (a ⊓ b) = f a ⊓ f b) (map_sSup : ∀ s, f (sSup s) = ⨆ a ∈ s, f a) (map_sInf : ∀ s, f (sInf s) = ⨅ a ∈ s, f a) (map_top : f ⊤ = ⊤) (map_bot : f ⊥ = ⊥) (map_compl : ∀ a, f aᶜ = (f a)ᶜ) (map_himp : ∀ a b, f (a ⇨ b) = f a ⇨ f b) (map_sdiff : ∀ a b, f (a \ b) = f a \ f b) : CompleteBooleanAlgebra α where __ := hf.completeLattice f map_sup map_inf map_sSup map_sInf map_top map_bot __ := hf.booleanAlgebra f map_sup map_inf map_top map_bot map_compl map_sdiff map_himp -- See note [reducible non-instances] /-- Pullback a `CompleteAtomicBooleanAlgebra` along an injection. -/ protected abbrev Function.Injective.completeAtomicBooleanAlgebra [Max α] [Min α] [SupSet α] [InfSet α] [Top α] [Bot α] [HasCompl α] [HImp α] [HNot α] [SDiff α] [CompleteAtomicBooleanAlgebra β] (f : α → β) (hf : Injective f) (map_sup : ∀ a b, f (a ⊔ b) = f a ⊔ f b) (map_inf : ∀ a b, f (a ⊓ b) = f a ⊓ f b) (map_sSup : ∀ s, f (sSup s) = ⨆ a ∈ s, f a) (map_sInf : ∀ s, f (sInf s) = ⨅ a ∈ s, f a) (map_top : f ⊤ = ⊤) (map_bot : f ⊥ = ⊥) (map_compl : ∀ a, f aᶜ = (f a)ᶜ) (map_himp : ∀ a b, f (a ⇨ b) = f a ⇨ f b) (map_hnot : ∀ a, f (¬a) = ¬f a) (map_sdiff : ∀ a b, f (a \ b) = f a \ f b) : CompleteAtomicBooleanAlgebra α where __ := hf.completelyDistribLattice f map_sup map_inf map_sSup map_sInf map_top map_bot map_compl map_himp map_hnot map_sdiff __ := hf.booleanAlgebra f map_sup map_inf map_top map_bot map_compl map_sdiff map_himp end lift namespace PUnit variable (s : Set PUnit.{u + 1}) instance instCompleteAtomicBooleanAlgebra : CompleteAtomicBooleanAlgebra PUnit where __ := PUnit.instBooleanAlgebra sSup _ := unit sInf _ := unit le_sSup _ _ _ := trivial sSup_le _ _ _ := trivial sInf_le _ _ _ := trivial le_sInf _ _ _ := trivial iInf_iSup_eq _ := rfl instance instCompleteBooleanAlgebra : CompleteBooleanAlgebra PUnit := inferInstance @[simp] theorem sSup_eq : sSup s = unit := rfl @[simp] theorem sInf_eq : sInf s = unit := rfl end PUnit
.lake/packages/mathlib/Mathlib/Order/MinMax.lean
import Mathlib.Logic.OpClass import Mathlib.Order.Lattice /-! # `max` and `min` This file proves basic properties about maxima and minima on a `LinearOrder`. ## Tags min, max -/ universe u v variable {α : Type u} {β : Type v} section variable [LinearOrder α] [LinearOrder β] {f : α → β} {s : Set α} {a b c d : α} -- translate from lattices to linear orders (sup → max, inf → min) theorem le_min_iff : c ≤ min a b ↔ c ≤ a ∧ c ≤ b := le_inf_iff theorem le_max_iff : a ≤ max b c ↔ a ≤ b ∨ a ≤ c := le_sup_iff theorem min_le_iff : min a b ≤ c ↔ a ≤ c ∨ b ≤ c := inf_le_iff theorem max_le_iff : max a b ≤ c ↔ a ≤ c ∧ b ≤ c := sup_le_iff theorem lt_min_iff : a < min b c ↔ a < b ∧ a < c := lt_inf_iff theorem lt_max_iff : a < max b c ↔ a < b ∨ a < c := lt_sup_iff theorem min_lt_iff : min a b < c ↔ a < c ∨ b < c := inf_lt_iff theorem max_lt_iff : max a b < c ↔ a < c ∧ b < c := sup_lt_iff theorem max_le_max : a ≤ c → b ≤ d → max a b ≤ max c d := sup_le_sup theorem max_le_max_left (c) (h : a ≤ b) : max c a ≤ max c b := sup_le_sup_left h c theorem max_le_max_right (c) (h : a ≤ b) : max a c ≤ max b c := sup_le_sup_right h c theorem min_le_min : a ≤ c → b ≤ d → min a b ≤ min c d := inf_le_inf theorem min_le_min_left (c) (h : a ≤ b) : min c a ≤ min c b := inf_le_inf_left c h theorem min_le_min_right (c) (h : a ≤ b) : min a c ≤ min b c := inf_le_inf_right c h theorem le_max_of_le_left : a ≤ b → a ≤ max b c := le_sup_of_le_left theorem le_max_of_le_right : a ≤ c → a ≤ max b c := le_sup_of_le_right theorem lt_max_of_lt_left (h : a < b) : a < max b c := h.trans_le (le_max_left b c) theorem lt_max_of_lt_right (h : a < c) : a < max b c := h.trans_le (le_max_right b c) theorem min_le_of_left_le : a ≤ c → min a b ≤ c := inf_le_of_left_le theorem min_le_of_right_le : b ≤ c → min a b ≤ c := inf_le_of_right_le theorem min_lt_of_left_lt (h : a < c) : min a b < c := (min_le_left a b).trans_lt h theorem min_lt_of_right_lt (h : b < c) : min a b < c := (min_le_right a b).trans_lt h lemma max_min_distrib_left (a b c : α) : max a (min b c) = min (max a b) (max a c) := sup_inf_left _ _ _ lemma max_min_distrib_right (a b c : α) : max (min a b) c = min (max a c) (max b c) := sup_inf_right _ _ _ lemma min_max_distrib_left (a b c : α) : min a (max b c) = max (min a b) (min a c) := inf_sup_left _ _ _ lemma min_max_distrib_right (a b c : α) : min (max a b) c = max (min a c) (min b c) := inf_sup_right _ _ _ theorem min_le_max : min a b ≤ max a b := le_trans (min_le_left a b) (le_max_left a b) theorem min_eq_left_iff : min a b = a ↔ a ≤ b := inf_eq_left theorem min_eq_right_iff : min a b = b ↔ b ≤ a := inf_eq_right theorem max_eq_left_iff : max a b = a ↔ b ≤ a := sup_eq_left theorem max_eq_right_iff : max a b = b ↔ a ≤ b := sup_eq_right /-- For elements `a` and `b` of a linear order, either `min a b = a` and `a ≤ b`, or `min a b = b` and `b < a`. Use cases on this lemma to automate linarith in inequalities -/ theorem min_cases (a b : α) : min a b = a ∧ a ≤ b ∨ min a b = b ∧ b < a := by grind /-- For elements `a` and `b` of a linear order, either `max a b = a` and `b ≤ a`, or `max a b = b` and `a < b`. Use cases on this lemma to automate linarith in inequalities -/ theorem max_cases (a b : α) : max a b = a ∧ b ≤ a ∨ max a b = b ∧ a < b := @min_cases αᵒᵈ _ a b theorem min_eq_iff : min a b = c ↔ a = c ∧ a ≤ b ∨ b = c ∧ b ≤ a := by grind theorem max_eq_iff : max a b = c ↔ a = c ∧ b ≤ a ∨ b = c ∧ a ≤ b := @min_eq_iff αᵒᵈ _ a b c theorem min_lt_min_left_iff : min a c < min b c ↔ a < b ∧ a < c := by grind theorem min_lt_min_right_iff : min a b < min a c ↔ b < c ∧ b < a := by grind theorem max_lt_max_left_iff : max a c < max b c ↔ a < b ∧ c < b := @min_lt_min_left_iff αᵒᵈ _ _ _ _ theorem max_lt_max_right_iff : max a b < max a c ↔ b < c ∧ a < c := @min_lt_min_right_iff αᵒᵈ _ _ _ _ /-- An instance asserting that `max a a = a` -/ instance max_idem : Std.IdempotentOp (α := α) max where idempotent := by simp -- short-circuit type class inference /-- An instance asserting that `min a a = a` -/ instance min_idem : Std.IdempotentOp (α := α) min where idempotent := by simp -- short-circuit type class inference theorem min_lt_max : min a b < max a b ↔ a ≠ b := inf_lt_sup theorem max_lt_max (h₁ : a < c) (h₂ : b < d) : max a b < max c d := max_lt (lt_max_of_lt_left h₁) (lt_max_of_lt_right h₂) theorem min_lt_min (h₁ : a < c) (h₂ : b < d) : min a b < min c d := @max_lt_max αᵒᵈ _ _ _ _ _ h₁ h₂ theorem min_right_comm (a b c : α) : min (min a b) c = min (min a c) b := by grind theorem Max.left_comm (a b c : α) : max a (max b c) = max b (max a c) := by grind theorem Max.right_comm (a b c : α) : max (max a b) c = max (max a c) b := by grind theorem MonotoneOn.map_max (hf : MonotoneOn f s) (ha : a ∈ s) (hb : b ∈ s) : f (max a b) = max (f a) (f b) := by rcases le_total a b with h | h <;> simp only [max_eq_right, max_eq_left, hf ha hb, hf hb ha, h] theorem MonotoneOn.map_min (hf : MonotoneOn f s) (ha : a ∈ s) (hb : b ∈ s) : f (min a b) = min (f a) (f b) := hf.dual.map_max ha hb theorem AntitoneOn.map_max (hf : AntitoneOn f s) (ha : a ∈ s) (hb : b ∈ s) : f (max a b) = min (f a) (f b) := hf.dual_right.map_max ha hb theorem AntitoneOn.map_min (hf : AntitoneOn f s) (ha : a ∈ s) (hb : b ∈ s) : f (min a b) = max (f a) (f b) := hf.dual.map_max ha hb theorem Monotone.map_max (hf : Monotone f) : f (max a b) = max (f a) (f b) := by rcases le_total a b with h | h <;> simp [h, hf h] theorem Monotone.map_min (hf : Monotone f) : f (min a b) = min (f a) (f b) := hf.dual.map_max theorem Antitone.map_max (hf : Antitone f) : f (max a b) = min (f a) (f b) := by rcases le_total a b with h | h <;> simp [h, hf h] theorem Antitone.map_min (hf : Antitone f) : f (min a b) = max (f a) (f b) := hf.dual.map_max theorem min_choice (a b : α) : min a b = a ∨ min a b = b := by cases le_total a b <;> simp [*] theorem max_choice (a b : α) : max a b = a ∨ max a b = b := @min_choice αᵒᵈ _ a b theorem le_of_max_le_left {a b c : α} (h : max a b ≤ c) : a ≤ c := le_trans (le_max_left _ _) h theorem le_of_max_le_right {a b c : α} (h : max a b ≤ c) : b ≤ c := le_trans (le_max_right _ _) h instance instCommutativeMax : Std.Commutative (α := α) max where comm := max_comm instance instAssociativeMax : Std.Associative (α := α) max where assoc := max_assoc instance instCommutativeMin : Std.Commutative (α := α) min where comm := min_comm instance instAssociativeMin : Std.Associative (α := α) min where assoc := min_assoc theorem max_left_commutative : LeftCommutative (max : α → α → α) := ⟨max_left_comm⟩ theorem min_left_commutative : LeftCommutative (min : α → α → α) := ⟨min_left_comm⟩ end
.lake/packages/mathlib/Mathlib/Order/PrimeSeparator.lean
import Mathlib.Order.PrimeIdeal import Mathlib.Order.Zorn /-! # Separating prime filters and ideals In a bounded distributive lattice, if $F$ is a filter, $I$ is an ideal, and $F$ and $I$ are disjoint, then there exists a prime ideal $J$ containing $I$ with $J$ still disjoint from $F$. This theorem is a crucial ingredient to [Stone's][Sto1938] duality for bounded distributive lattices. The construction of the separator relies on Zorn's lemma. ## Tags ideal, filter, prime, distributive lattice ## References * [M. H. Stone, Topological representations of distributive lattices and Brouwerian logics (1938)][Sto1938] -/ universe u variable {α : Type*} open Order Ideal Set variable [DistribLattice α] [BoundedOrder α] variable {F : PFilter α} {I : Ideal α} namespace DistribLattice lemma mem_ideal_sup_principal (a b : α) (J : Ideal α) : b ∈ J ⊔ principal a ↔ ∃ j ∈ J, b ≤ j ⊔ a := ⟨fun ⟨j, ⟨jJ, _, ha', bja'⟩⟩ => ⟨j, jJ, le_trans bja' (sup_le_sup_left ha' j)⟩, fun ⟨j, hj, hbja⟩ => ⟨j, hj, a, le_refl a, hbja⟩⟩ theorem prime_ideal_of_disjoint_filter_ideal (hFI : Disjoint (F : Set α) (I : Set α)) : ∃ J : Ideal α, (IsPrime J) ∧ I ≤ J ∧ Disjoint (F : Set α) J := by -- Let S be the set of ideals containing I and disjoint from F. set S : Set (Set α) := { J : Set α | IsIdeal J ∧ I ≤ J ∧ Disjoint (F : Set α) J } -- Then I is in S... have IinS : ↑I ∈ S := by refine ⟨Order.Ideal.isIdeal I, by trivial⟩ -- ...and S contains upper bounds for any non-empty chains. have chainub : ∀ c ⊆ S, IsChain (· ⊆ ·) c → c.Nonempty → ∃ ub ∈ S, ∀ s ∈ c, s ⊆ ub := by intro c hcS hcC hcNe use sUnion c refine ⟨?_, fun s hs ↦ le_sSup hs⟩ simp only [le_eq_subset, mem_setOf_eq, disjoint_sUnion_right, S] let ⟨J, hJ⟩ := hcNe refine ⟨Order.isIdeal_sUnion_of_isChain (fun _ hJ ↦ (hcS hJ).1) hcC hcNe, ⟨le_trans (hcS hJ).2.1 (le_sSup hJ), fun J hJ ↦ (hcS hJ).2.2⟩⟩ -- Thus, by Zorn's lemma, we can pick a maximal ideal J in S. obtain ⟨Jset, _, hmax⟩ := zorn_subset_nonempty S chainub I IinS obtain ⟨Jidl, IJ, JF⟩ := hmax.prop set J := IsIdeal.toIdeal Jidl use J have IJ' : I ≤ J := IJ clear chainub IinS -- By construction, J contains I and is disjoint from F. It remains to prove that J is prime. refine ⟨?_, ⟨IJ, JF⟩⟩ -- First note that J is proper: ⊤ ∈ F so ⊤ ∉ J because F and J are disjoint. have Jpr : IsProper J := isProper_of_notMem (Set.disjoint_left.1 JF F.top_mem) -- Suppose that a₁ ∉ J, a₂ ∉ J. We need to prove that a₁ ⊔ a₂ ∉ J. rw [isPrime_iff_mem_or_mem] intro a₁ a₂ contrapose! intro ⟨ha₁, ha₂⟩ -- Consider the ideals J₁, J₂ generated by J ∪ {a₁} and J ∪ {a₂}, respectively. let J₁ := J ⊔ principal a₁ let J₂ := J ⊔ principal a₂ -- For each i, Jᵢ is an ideal that contains aᵢ, and is not equal to J. have a₁J₁ : a₁ ∈ J₁ := mem_of_subset_of_mem (le_sup_right : _ ≤ J ⊔ _) mem_principal_self have a₂J₂ : a₂ ∈ J₂ := mem_of_subset_of_mem (le_sup_right : _ ≤ J ⊔ _) mem_principal_self have J₁J : ↑J₁ ≠ Jset := ne_of_mem_of_not_mem' a₁J₁ ha₁ have J₂J : ↑J₂ ≠ Jset := ne_of_mem_of_not_mem' a₂J₂ ha₂ -- Therefore, since J is maximal, we must have Jᵢ ∉ S. have J₁S : ↑J₁ ∉ S := fun h => J₁J (hmax.eq_of_le h (le_sup_left : J ≤ J₁)).symm have J₂S : ↑J₂ ∉ S := fun h => J₂J (hmax.eq_of_le h (le_sup_left : J ≤ J₂)).symm -- Since Jᵢ is an ideal that contains I, we have that Jᵢ is not disjoint from F. have J₁F : ¬ (Disjoint (F : Set α) J₁) := by intro hdis apply J₁S simp only [le_eq_subset, mem_setOf_eq, SetLike.coe_subset_coe, S] exact ⟨J₁.isIdeal, le_trans IJ' le_sup_left, hdis⟩ have J₂F : ¬ (Disjoint (F : Set α) J₂) := by intro hdis apply J₂S simp only [le_eq_subset, mem_setOf_eq, SetLike.coe_subset_coe, S] exact ⟨J₂.isIdeal, le_trans IJ' le_sup_left, hdis⟩ -- Thus, pick cᵢ ∈ F ∩ Jᵢ. let ⟨c₁, ⟨c₁F, c₁J₁⟩⟩ := Set.not_disjoint_iff.1 J₁F let ⟨c₂, ⟨c₂F, c₂J₂⟩⟩ := Set.not_disjoint_iff.1 J₂F -- Using the definition of Jᵢ, we can pick bᵢ ∈ J such that cᵢ ≤ bᵢ ⊔ aᵢ. let ⟨b₁, ⟨b₁J, cba₁⟩⟩ := (mem_ideal_sup_principal a₁ c₁ J).1 c₁J₁ let ⟨b₂, ⟨b₂J, cba₂⟩⟩ := (mem_ideal_sup_principal a₂ c₂ J).1 c₂J₂ -- Since J is an ideal, we have b := b₁ ⊔ b₂ ∈ J. let b := b₁ ⊔ b₂ have bJ : b ∈ J := sup_mem b₁J b₂J -- We now prove a key inequality, using crucially that the lattice is distributive. have ineq : c₁ ⊓ c₂ ≤ b ⊔ (a₁ ⊓ a₂) := calc c₁ ⊓ c₂ ≤ (b₁ ⊔ a₁) ⊓ (b₂ ⊔ a₂) := inf_le_inf cba₁ cba₂ _ ≤ (b ⊔ a₁) ⊓ (b ⊔ a₂) := by gcongr; exacts [le_sup_left, le_sup_right] _ = b ⊔ (a₁ ⊓ a₂) := (sup_inf_left b a₁ a₂).symm -- Note that c₁ ⊓ c₂ ∈ F, since c₁ and c₂ are both in F and F is a filter. -- Since F is an upper set, it now follows that b ⊔ (a₁ ⊓ a₂) ∈ F. have ba₁a₂F : b ⊔ (a₁ ⊓ a₂) ∈ F := PFilter.mem_of_le ineq (PFilter.inf_mem c₁F c₂F) -- Now, if we would have a₁ ⊓ a₂ ∈ J, then, since J is an ideal and b ∈ J, we would also get -- b ⊔ (a₁ ⊓ a₂) ∈ J. But this contradicts that J is disjoint from F. contrapose! JF with ha₁a₂ rw [Set.not_disjoint_iff] use b ⊔ (a₁ ⊓ a₂) exact ⟨ba₁a₂F, sup_mem bJ ha₁a₂⟩ -- TODO: Define prime filters in Mathlib so that the following corollary can be stated and proved. -- theorem prime_filter_of_disjoint_filter_ideal (hFI : Disjoint (F : Set α) (I : Set α)) : -- ∃ G : PFilter α, (IsPrime G) ∧ F ≤ G ∧ Disjoint (G : Set α) I := by sorry end DistribLattice
.lake/packages/mathlib/Mathlib/Order/Atoms.lean
import Mathlib.Data.Set.Lattice import Mathlib.Data.SetLike.Basic import Mathlib.Order.ModularLattice import Mathlib.Order.SuccPred.Basic import Mathlib.Order.WellFounded import Mathlib.Tactic.Nontriviality import Mathlib.Order.ConditionallyCompleteLattice.Indexed /-! # Atoms, Coatoms, and Simple Lattices This module defines atoms, which are minimal non-`⊥` elements in bounded lattices, simple lattices, which are lattices with only two elements, and related ideas. ## Main definitions ### Atoms and Coatoms * `IsAtom a` indicates that the only element below `a` is `⊥`. * `IsCoatom a` indicates that the only element above `a` is `⊤`. ### Atomic and Atomistic Lattices * `IsAtomic` indicates that every element other than `⊥` is above an atom. * `IsCoatomic` indicates that every element other than `⊤` is below a coatom. * `IsAtomistic` indicates that every element is the `sSup` of a set of atoms. * `IsCoatomistic` indicates that every element is the `sInf` of a set of coatoms. * `IsStronglyAtomic` indicates that for all `a < b`, there is some `x` with `a ⋖ x ≤ b`. * `IsStronglyCoatomic` indicates that for all `a < b`, there is some `x` with `a ≤ x ⋖ b`. ### Simple Lattices * `IsSimpleOrder` indicates that an order has only two unique elements, `⊥` and `⊤`. * `IsSimpleOrder.boundedOrder` * `IsSimpleOrder.distribLattice` * Given an instance of `IsSimpleOrder`, we provide the following definitions. These are not made global instances as they contain data : * `IsSimpleOrder.booleanAlgebra` * `IsSimpleOrder.completeLattice` * `IsSimpleOrder.completeBooleanAlgebra` ## Main results * `isAtom_dual_iff_isCoatom` and `isCoatom_dual_iff_isAtom` express the (definitional) duality of `IsAtom` and `IsCoatom`. * `isSimpleOrder_iff_isAtom_top` and `isSimpleOrder_iff_isCoatom_bot` express the connection between atoms, coatoms, and simple lattices * `IsCompl.isAtom_iff_isCoatom` and `IsCompl.isCoatom_if_isAtom`: In a modular bounded lattice, a complement of an atom is a coatom and vice versa. * `isAtomic_iff_isCoatomic`: A modular complemented lattice is atomic iff it is coatomic. -/ open Order variable {ι : Sort*} {α β : Type*} section Atoms section IsAtom section Preorder variable [Preorder α] [OrderBot α] {a b x : α} /-- An atom of an `OrderBot` is an element with no other element between it and `⊥`, which is not `⊥`. -/ def IsAtom (a : α) : Prop := a ≠ ⊥ ∧ ∀ b, b < a → b = ⊥ theorem IsAtom.Iic (ha : IsAtom a) (hax : a ≤ x) : IsAtom (⟨a, hax⟩ : Set.Iic x) := ⟨fun con => ha.1 (Subtype.mk_eq_mk.1 con), fun ⟨b, _⟩ hba => Subtype.mk_eq_mk.2 (ha.2 b hba)⟩ theorem IsAtom.of_isAtom_coe_Iic {a : Set.Iic x} (ha : IsAtom a) : IsAtom (a : α) := ⟨fun con => ha.1 (Subtype.ext con), fun b hba => Subtype.mk_eq_mk.1 (ha.2 ⟨b, hba.le.trans a.prop⟩ hba)⟩ theorem isAtom_iff_le_of_ge : IsAtom a ↔ a ≠ ⊥ ∧ ∀ b ≠ ⊥, b ≤ a → a ≤ b := and_congr Iff.rfl <| forall_congr' fun b => by simp only [Ne, @not_imp_comm (b = ⊥), Classical.not_imp, lt_iff_le_not_ge] lemma IsAtom.ne_bot (ha : IsAtom a) : a ≠ ⊥ := ha.1 end Preorder section PartialOrder variable [PartialOrder α] [OrderBot α] {a b x : α} theorem IsAtom.lt_iff (h : IsAtom a) : x < a ↔ x = ⊥ := ⟨h.2 x, fun hx => hx.symm ▸ h.1.bot_lt⟩ theorem IsAtom.le_iff (h : IsAtom a) : x ≤ a ↔ x = ⊥ ∨ x = a := by rw [le_iff_lt_or_eq, h.lt_iff] lemma IsAtom.bot_lt (h : IsAtom a) : ⊥ < a := h.lt_iff.mpr rfl lemma IsAtom.le_iff_eq (ha : IsAtom a) (hb : b ≠ ⊥) : b ≤ a ↔ b = a := ha.le_iff.trans <| or_iff_right hb lemma IsAtom.ne_iff_eq_bot (ha : IsAtom a) (hba : b ≤ a) : b ≠ a ↔ b = ⊥ where mp := (ha.le_iff.1 hba).resolve_right mpr := by rintro rfl; exact ha.ne_bot.symm lemma IsAtom.ne_bot_iff_eq (ha : IsAtom a) (hba : b ≤ a) : b ≠ ⊥ ↔ b = a := (ha.ne_iff_eq_bot hba).not_right.symm theorem IsAtom.Iic_eq (h : IsAtom a) : Set.Iic a = {⊥, a} := Set.ext fun _ => h.le_iff @[simp] theorem bot_covBy_iff : ⊥ ⋖ a ↔ IsAtom a := by simp only [CovBy, bot_lt_iff_ne_bot, IsAtom, not_imp_not] alias ⟨CovBy.is_atom, IsAtom.bot_covBy⟩ := bot_covBy_iff end PartialOrder section Frame variable [Frame α] {f : ι → α} {s : Set α} {a : α} protected lemma IsAtom.le_iSup (ha : IsAtom a) : a ≤ iSup f ↔ ∃ i, a ≤ f i := by refine ⟨?_, fun ⟨i, hi⟩ => le_trans hi (le_iSup _ _)⟩ change (a ≤ ⨆ i, f i) → _ refine fun h => of_not_not fun ha' => ?_ push_neg at ha' have ha'' : Disjoint a (⨆ i, f i) := disjoint_iSup_iff.2 fun i => fun x hxa hxf => le_bot_iff.2 <| of_not_not fun hx => have hxa : x < a := (le_iff_eq_or_lt.1 hxa).resolve_left (by rintro rfl; exact ha' _ hxf) hx (ha.2 _ hxa) obtain rfl := le_bot_iff.1 (ha'' le_rfl h) exact ha.1 rfl @[deprecated (since := "2025-07-11")] alias atom_le_iSup := IsAtom.le_iSup protected lemma IsAtom.le_sSup (ha : IsAtom a) : a ≤ sSup s ↔ ∃ b ∈ s, a ≤ b := by simp [sSup_eq_iSup', ha.le_iSup] end Frame end IsAtom section IsCoatom section Preorder variable [Preorder α] /-- A coatom of an `OrderTop` is an element with no other element between it and `⊤`, which is not `⊤`. -/ def IsCoatom [OrderTop α] (a : α) : Prop := a ≠ ⊤ ∧ ∀ b, a < b → b = ⊤ @[simp] theorem isCoatom_dual_iff_isAtom [OrderBot α] {a : α} : IsCoatom (OrderDual.toDual a) ↔ IsAtom a := Iff.rfl @[simp] theorem isAtom_dual_iff_isCoatom [OrderTop α] {a : α} : IsAtom (OrderDual.toDual a) ↔ IsCoatom a := Iff.rfl alias ⟨_, IsAtom.dual⟩ := isCoatom_dual_iff_isAtom alias ⟨_, IsCoatom.dual⟩ := isAtom_dual_iff_isCoatom variable [OrderTop α] {a x : α} theorem IsCoatom.Ici (ha : IsCoatom a) (hax : x ≤ a) : IsCoatom (⟨a, hax⟩ : Set.Ici x) := ha.dual.Iic hax theorem IsCoatom.of_isCoatom_coe_Ici {a : Set.Ici x} (ha : IsCoatom a) : IsCoatom (a : α) := @IsAtom.of_isAtom_coe_Iic αᵒᵈ _ _ x a ha theorem isCoatom_iff_ge_of_le : IsCoatom a ↔ a ≠ ⊤ ∧ ∀ b ≠ ⊤, a ≤ b → b ≤ a := isAtom_iff_le_of_ge (α := αᵒᵈ) lemma IsCoatom.ne_top (ha : IsCoatom a) : a ≠ ⊤ := ha.1 end Preorder section PartialOrder variable [PartialOrder α] [OrderTop α] {a b x : α} theorem IsCoatom.lt_iff (h : IsCoatom a) : a < x ↔ x = ⊤ := h.dual.lt_iff theorem IsCoatom.le_iff (h : IsCoatom a) : a ≤ x ↔ x = ⊤ ∨ x = a := h.dual.le_iff lemma IsCoatom.lt_top (h : IsCoatom a) : a < ⊤ := h.lt_iff.mpr rfl lemma IsCoatom.le_iff_eq (ha : IsCoatom a) (hb : b ≠ ⊤) : a ≤ b ↔ b = a := ha.dual.le_iff_eq hb lemma IsCoatom.ne_iff_eq_top (ha : IsCoatom a) (hab : a ≤ b) : b ≠ a ↔ b = ⊤ where mp := (ha.le_iff.1 hab).resolve_right mpr := by rintro rfl; exact ha.ne_top.symm lemma IsCoatom.ne_top_iff_eq (ha : IsCoatom a) (hab : a ≤ b) : b ≠ ⊤ ↔ b = a := (ha.ne_iff_eq_top hab).not_right.symm theorem IsCoatom.Ici_eq (h : IsCoatom a) : Set.Ici a = {⊤, a} := h.dual.Iic_eq @[simp] theorem covBy_top_iff : a ⋖ ⊤ ↔ IsCoatom a := toDual_covBy_toDual_iff.symm.trans bot_covBy_iff alias ⟨CovBy.isCoatom, IsCoatom.covBy_top⟩ := covBy_top_iff namespace SetLike variable {A B : Type*} [SetLike A B] theorem isAtom_iff [OrderBot A] {K : A} : IsAtom K ↔ K ≠ ⊥ ∧ ∀ H g, H ≤ K → g ∉ H → g ∈ K → H = ⊥ := by simp_rw [IsAtom, lt_iff_le_not_ge, SetLike.not_le_iff_exists, and_comm (a := _ ≤ _), and_imp, exists_imp, ← and_imp, and_comm] theorem isCoatom_iff [OrderTop A] {K : A} : IsCoatom K ↔ K ≠ ⊤ ∧ ∀ H g, K ≤ H → g ∉ K → g ∈ H → H = ⊤ := by simp_rw [IsCoatom, lt_iff_le_not_ge, SetLike.not_le_iff_exists, and_comm (a := _ ≤ _), and_imp, exists_imp, ← and_imp, and_comm] theorem covBy_iff {K L : A} : K ⋖ L ↔ K < L ∧ ∀ H g, K ≤ H → H ≤ L → g ∉ K → g ∈ H → H = L := by refine and_congr_right fun _ ↦ forall_congr' fun H ↦ not_iff_not.mp ?_ push_neg rw [lt_iff_le_not_ge, lt_iff_le_and_ne, and_and_and_comm] simp_rw [exists_and_left, and_assoc, and_congr_right_iff, ← and_assoc, and_comm, exists_and_left, SetLike.not_le_iff_exists, and_comm, implies_true] /-- Dual variant of `SetLike.covBy_iff` -/ theorem covBy_iff' {K L : A} : K ⋖ L ↔ K < L ∧ ∀ H g, K ≤ H → H ≤ L → g ∉ H → g ∈ L → H = K := by refine and_congr_right fun _ ↦ forall_congr' fun H ↦ not_iff_not.mp ?_ push_neg rw [lt_iff_le_and_ne, lt_iff_le_not_ge, and_and_and_comm] simp_rw [exists_and_left, and_assoc, and_congr_right_iff, ← and_assoc, and_comm, exists_and_left, SetLike.not_le_iff_exists, ne_comm, implies_true] end SetLike end PartialOrder section Coframe variable [Coframe α] {f : ι → α} {s : Set α} {a : α} protected lemma IsCoatom.iInf_le (ha : IsCoatom a) : iInf f ≤ a ↔ ∃ i, f i ≤ a := IsAtom.le_iSup (α := αᵒᵈ) ha @[deprecated (since := "2025-07-11")] alias iInf_le_coatom := IsCoatom.iInf_le protected lemma IsCoatom.sInf_le (ha : IsCoatom a) : sInf s ≤ a ↔ ∃ b ∈ s, b ≤ a := by simp [sInf_eq_iInf', ha.iInf_le] end Coframe end IsCoatom section PartialOrder variable [PartialOrder α] {a b : α} @[simp] theorem Set.Ici.isAtom_iff {b : Set.Ici a} : IsAtom b ↔ a ⋖ b := by rw [← bot_covBy_iff] refine (Set.OrdConnected.apply_covBy_apply_iff (OrderEmbedding.subtype fun c => a ≤ c) ?_).symm simpa only [OrderEmbedding.coe_subtype, Subtype.range_coe_subtype] using Set.ordConnected_Ici @[simp] theorem Set.Iic.isCoatom_iff {a : Set.Iic b} : IsCoatom a ↔ ↑a ⋖ b := by rw [← covBy_top_iff] refine (Set.OrdConnected.apply_covBy_apply_iff (OrderEmbedding.subtype fun c => c ≤ b) ?_).symm simpa only [OrderEmbedding.coe_subtype, Subtype.range_coe_subtype] using Set.ordConnected_Iic theorem covBy_iff_atom_Ici (h : a ≤ b) : a ⋖ b ↔ IsAtom (⟨b, h⟩ : Set.Ici a) := by simp theorem covBy_iff_coatom_Iic (h : a ≤ b) : a ⋖ b ↔ IsCoatom (⟨a, h⟩ : Set.Iic b) := by simp end PartialOrder section SemilatticeInf variable [SemilatticeInf α] [OrderBot α] {a b : α} lemma IsAtom.not_disjoint_iff_le (ha : IsAtom a) : ¬ Disjoint a b ↔ a ≤ b := by rw [disjoint_iff, ← inf_eq_left]; exact ha.ne_bot_iff_eq inf_le_left lemma IsAtom.not_le_iff_disjoint (ha : IsAtom a) : ¬ a ≤ b ↔ Disjoint a b := ha.not_disjoint_iff_le.not_right.symm lemma IsAtom.disjoint_of_ne (ha : IsAtom a) (hb : IsAtom b) (hab : a ≠ b) : Disjoint a b := by simp [← ha.not_le_iff_disjoint, hb.le_iff, hab, ha.ne_bot] @[deprecated disjoint_of_ne (since := "2025-07-11")] theorem IsAtom.inf_eq_bot_of_ne (ha : IsAtom a) (hb : IsAtom b) (hab : a ≠ b) : a ⊓ b = ⊥ := hab.not_le_or_not_ge.elim (ha.lt_iff.1 ∘ inf_lt_left.2) (hb.lt_iff.1 ∘ inf_lt_right.2) @[deprecated not_le_iff_disjoint (since := "2025-07-11")] theorem IsAtom.inf_eq_bot_iff (ha : IsAtom a) : a ⊓ b = ⊥ ↔ ¬ a ≤ b := by by_cases hb : b = ⊥ · simpa [hb] using ha.1 · exact ⟨fun h ↦ inf_lt_left.mp (h ▸ bot_lt ha), fun h ↦ ha.2 _ (inf_lt_left.mpr h)⟩ end SemilatticeInf section SemilatticeSup variable [SemilatticeSup α] [OrderTop α] {a b : α} lemma IsCoatom.not_codisjoint_iff_le (ha : IsCoatom a) : ¬ Codisjoint a b ↔ b ≤ a := by rw [codisjoint_iff, ← sup_eq_left]; exact ha.ne_top_iff_eq le_sup_left lemma IsCoatom.not_le_iff_codisjoint (ha : IsCoatom a) : ¬ b ≤ a ↔ Codisjoint a b := ha.not_codisjoint_iff_le.not_right.symm lemma IsCoatom.codisjoint_of_ne (ha : IsCoatom a) (hb : IsCoatom b) (hab : a ≠ b) : Codisjoint a b := by simp [← ha.not_le_iff_codisjoint, hb.le_iff, hab, ha.ne_top] theorem IsCoatom.sup_eq_top_of_ne (ha : IsCoatom a) (hb : IsCoatom b) (hab : a ≠ b) : a ⊔ b = ⊤ := codisjoint_iff.1 <| ha.codisjoint_of_ne hb hab set_option linter.deprecated false in @[deprecated not_le_iff_codisjoint (since := "2025-07-11")] theorem IsCoatom.sup_eq_top_iff (ha : IsCoatom a) : a ⊔ b = ⊤ ↔ ¬ b ≤ a := ha.dual.inf_eq_bot_iff end SemilatticeSup end Atoms section Atomic variable [PartialOrder α] (α) /-- A lattice is atomic iff every element other than `⊥` has an atom below it. -/ @[mk_iff] class IsAtomic [OrderBot α] : Prop where /-- Every element other than `⊥` has an atom below it. -/ eq_bot_or_exists_atom_le : ∀ b : α, b = ⊥ ∨ ∃ a : α, IsAtom a ∧ a ≤ b /-- A lattice is coatomic iff every element other than `⊤` has a coatom above it. -/ @[mk_iff] class IsCoatomic [OrderTop α] : Prop where /-- Every element other than `⊤` has an atom above it. -/ eq_top_or_exists_le_coatom : ∀ b : α, b = ⊤ ∨ ∃ a : α, IsCoatom a ∧ b ≤ a export IsAtomic (eq_bot_or_exists_atom_le) export IsCoatomic (eq_top_or_exists_le_coatom) lemma IsAtomic.exists_atom [OrderBot α] [Nontrivial α] [IsAtomic α] : ∃ a : α, IsAtom a := have ⟨b, hb⟩ := exists_ne (⊥ : α) have ⟨a, ha⟩ := (eq_bot_or_exists_atom_le b).resolve_left hb ⟨a, ha.1⟩ lemma IsCoatomic.exists_coatom [OrderTop α] [Nontrivial α] [IsCoatomic α] : ∃ a : α, IsCoatom a := have ⟨b, hb⟩ := exists_ne (⊤ : α) have ⟨a, ha⟩ := (eq_top_or_exists_le_coatom b).resolve_left hb ⟨a, ha.1⟩ variable {α} @[simp] theorem isCoatomic_dual_iff_isAtomic [OrderBot α] : IsCoatomic αᵒᵈ ↔ IsAtomic α := ⟨fun h => ⟨fun b => by apply h.eq_top_or_exists_le_coatom⟩, fun h => ⟨fun b => by apply h.eq_bot_or_exists_atom_le⟩⟩ @[simp] theorem isAtomic_dual_iff_isCoatomic [OrderTop α] : IsAtomic αᵒᵈ ↔ IsCoatomic α := ⟨fun h => ⟨fun b => by apply h.eq_bot_or_exists_atom_le⟩, fun h => ⟨fun b => by apply h.eq_top_or_exists_le_coatom⟩⟩ namespace IsAtomic variable [OrderBot α] [IsAtomic α] instance _root_.OrderDual.instIsCoatomic : IsCoatomic αᵒᵈ := isCoatomic_dual_iff_isAtomic.2 ‹IsAtomic α› instance Set.Iic.isAtomic {x : α} : IsAtomic (Set.Iic x) := ⟨fun ⟨y, hy⟩ => (eq_bot_or_exists_atom_le y).imp Subtype.mk_eq_mk.2 fun ⟨a, ha, hay⟩ => ⟨⟨a, hay.trans hy⟩, ha.Iic (hay.trans hy), hay⟩⟩ end IsAtomic namespace IsCoatomic variable [OrderTop α] [IsCoatomic α] instance _root_.OrderDual.instIsAtomic : IsAtomic αᵒᵈ := isAtomic_dual_iff_isCoatomic.2 ‹IsCoatomic α› instance Set.Ici.isCoatomic {x : α} : IsCoatomic (Set.Ici x) := ⟨fun ⟨y, hy⟩ => (eq_top_or_exists_le_coatom y).imp Subtype.mk_eq_mk.2 fun ⟨a, ha, hay⟩ => ⟨⟨a, le_trans hy hay⟩, ha.Ici (le_trans hy hay), hay⟩⟩ end IsCoatomic theorem isAtomic_iff_forall_isAtomic_Iic [OrderBot α] : IsAtomic α ↔ ∀ x : α, IsAtomic (Set.Iic x) := ⟨@IsAtomic.Set.Iic.isAtomic _ _ _, fun h => ⟨fun x => ((@eq_bot_or_exists_atom_le _ _ _ (h x)) (⊤ : Set.Iic x)).imp Subtype.mk_eq_mk.1 (Exists.imp' (↑) fun ⟨_, _⟩ => And.imp_left IsAtom.of_isAtom_coe_Iic)⟩⟩ theorem isCoatomic_iff_forall_isCoatomic_Ici [OrderTop α] : IsCoatomic α ↔ ∀ x : α, IsCoatomic (Set.Ici x) := isAtomic_dual_iff_isCoatomic.symm.trans <| isAtomic_iff_forall_isAtomic_Iic.trans <| forall_congr' fun _ => isCoatomic_dual_iff_isAtomic.symm.trans Iff.rfl section StronglyAtomic variable {α : Type*} {a b : α} [Preorder α] /-- An order is strongly atomic if every nontrivial interval `[a, b]` contains an element covering `a`. -/ @[mk_iff] class IsStronglyAtomic (α : Type*) [Preorder α] : Prop where exists_covBy_le_of_lt : ∀ (a b : α), a < b → ∃ x, a ⋖ x ∧ x ≤ b theorem exists_covBy_le_of_lt [IsStronglyAtomic α] (h : a < b) : ∃ x, a ⋖ x ∧ x ≤ b := IsStronglyAtomic.exists_covBy_le_of_lt a b h alias LT.lt.exists_covby_le := exists_covBy_le_of_lt /-- An order is strongly coatomic if every nontrivial interval `[a, b]` contains an element covered by `b`. -/ @[mk_iff] class IsStronglyCoatomic (α : Type*) [Preorder α] : Prop where (exists_le_covBy_of_lt : ∀ (a b : α), a < b → ∃ x, a ≤ x ∧ x ⋖ b) theorem exists_le_covBy_of_lt [IsStronglyCoatomic α] (h : a < b) : ∃ x, a ≤ x ∧ x ⋖ b := IsStronglyCoatomic.exists_le_covBy_of_lt a b h alias LT.lt.exists_le_covby := exists_le_covBy_of_lt theorem isStronglyAtomic_dual_iff_is_stronglyCoatomic : IsStronglyAtomic αᵒᵈ ↔ IsStronglyCoatomic α := by simpa [isStronglyAtomic_iff, OrderDual.exists, OrderDual.forall, OrderDual.toDual_le_toDual, and_comm, isStronglyCoatomic_iff] using forall_comm @[simp] theorem isStronglyCoatomic_dual_iff_is_stronglyAtomic : IsStronglyCoatomic αᵒᵈ ↔ IsStronglyAtomic α := by rw [← isStronglyAtomic_dual_iff_is_stronglyCoatomic]; rfl instance OrderDual.instIsStronglyCoatomic [IsStronglyAtomic α] : IsStronglyCoatomic αᵒᵈ := by rwa [isStronglyCoatomic_dual_iff_is_stronglyAtomic] instance [IsStronglyCoatomic α] : IsStronglyAtomic αᵒᵈ := by rwa [isStronglyAtomic_dual_iff_is_stronglyCoatomic] instance IsStronglyAtomic.isAtomic (α : Type*) [PartialOrder α] [OrderBot α] [IsStronglyAtomic α] : IsAtomic α where eq_bot_or_exists_atom_le a := by rw [or_iff_not_imp_left, ← Ne, ← bot_lt_iff_ne_bot] refine fun hlt ↦ ?_ obtain ⟨x, hx, hxa⟩ := hlt.exists_covby_le exact ⟨x, bot_covBy_iff.1 hx, hxa⟩ instance IsStronglyCoatomic.toIsCoatomic (α : Type*) [PartialOrder α] [OrderTop α] [IsStronglyCoatomic α] : IsCoatomic α := isAtomic_dual_iff_isCoatomic.1 <| IsStronglyAtomic.isAtomic (α := αᵒᵈ) theorem Set.OrdConnected.isStronglyAtomic [IsStronglyAtomic α] {s : Set α} (h : Set.OrdConnected s) : IsStronglyAtomic s where exists_covBy_le_of_lt := by rintro ⟨c, hc⟩ ⟨d, hd⟩ hcd obtain ⟨x, hcx, hxd⟩ := (Subtype.mk_lt_mk.1 hcd).exists_covby_le exact ⟨⟨x, h.out' hc hd ⟨hcx.le, hxd⟩⟩, ⟨by simpa using hcx.lt, fun y hy hy' ↦ hcx.2 (by simpa using hy) (by simpa using hy')⟩, hxd⟩ theorem Set.OrdConnected.isStronglyCoatomic [IsStronglyCoatomic α] {s : Set α} (h : Set.OrdConnected s) : IsStronglyCoatomic s := isStronglyAtomic_dual_iff_is_stronglyCoatomic.1 h.dual.isStronglyAtomic instance [IsStronglyAtomic α] {s : Set α} [Set.OrdConnected s] : IsStronglyAtomic s := Set.OrdConnected.isStronglyAtomic <| by assumption instance [IsStronglyCoatomic α] {s : Set α} [h : Set.OrdConnected s] : IsStronglyCoatomic s := Set.OrdConnected.isStronglyCoatomic <| by assumption instance SuccOrder.toIsStronglyAtomic [SuccOrder α] : IsStronglyAtomic α where exists_covBy_le_of_lt a _ hab := ⟨SuccOrder.succ a, Order.covBy_succ_of_not_isMax fun ha ↦ ha.not_lt hab, SuccOrder.succ_le_of_lt hab⟩ instance [PredOrder α] : IsStronglyCoatomic α := by rw [← isStronglyAtomic_dual_iff_is_stronglyCoatomic]; infer_instance end StronglyAtomic section WellFounded theorem IsStronglyAtomic.of_wellFounded_lt (h : WellFounded ((· < ·) : α → α → Prop)) : IsStronglyAtomic α where exists_covBy_le_of_lt a b hab := by refine ⟨WellFounded.min h (Set.Ioc a b) ⟨b, hab,rfl.le⟩, ?_⟩ have hmem := (WellFounded.min_mem h (Set.Ioc a b) ⟨b, hab,rfl.le⟩) exact ⟨⟨hmem.1,fun c hac hlt ↦ WellFounded.not_lt_min h (Set.Ioc a b) ⟨b, hab,rfl.le⟩ ⟨hac, hlt.le.trans hmem.2⟩ hlt ⟩, hmem.2⟩ theorem IsStronglyCoatomic.of_wellFounded_gt (h : WellFounded ((· > ·) : α → α → Prop)) : IsStronglyCoatomic α := isStronglyAtomic_dual_iff_is_stronglyCoatomic.1 <| IsStronglyAtomic.of_wellFounded_lt (α := αᵒᵈ) h instance [WellFoundedLT α] : IsStronglyAtomic α := IsStronglyAtomic.of_wellFounded_lt wellFounded_lt instance [WellFoundedGT α] : IsStronglyCoatomic α := IsStronglyCoatomic.of_wellFounded_gt wellFounded_gt theorem isAtomic_of_orderBot_wellFounded_lt [OrderBot α] (h : WellFounded ((· < ·) : α → α → Prop)) : IsAtomic α := (IsStronglyAtomic.of_wellFounded_lt h).isAtomic theorem isCoatomic_of_orderTop_gt_wellFounded [OrderTop α] (h : WellFounded ((· > ·) : α → α → Prop)) : IsCoatomic α := isAtomic_dual_iff_isCoatomic.1 (@isAtomic_of_orderBot_wellFounded_lt αᵒᵈ _ _ h) end WellFounded namespace BooleanAlgebra theorem le_iff_atom_le_imp {α} [BooleanAlgebra α] [IsAtomic α] {x y : α} : x ≤ y ↔ ∀ a, IsAtom a → a ≤ x → a ≤ y := by refine ⟨fun h a _ => (le_trans · h), fun h => ?_⟩ have : x ⊓ yᶜ = ⊥ := of_not_not fun hbot => have ⟨a, ha, hle⟩ := (eq_bot_or_exists_atom_le _).resolve_left hbot have ⟨hx, hy'⟩ := le_inf_iff.1 hle have hy := h a ha hx have : a ≤ y ⊓ yᶜ := le_inf_iff.2 ⟨hy, hy'⟩ ha.1 (by simpa using this) exact (eq_compl_iff_isCompl.1 (by simp)).inf_right_eq_bot_iff.1 this theorem eq_iff_atom_le_iff {α} [BooleanAlgebra α] [IsAtomic α] {x y : α} : x = y ↔ ∀ a, IsAtom a → (a ≤ x ↔ a ≤ y) := by refine ⟨fun h => h ▸ by simp, fun h => ?_⟩ exact le_antisymm (le_iff_atom_le_imp.2 fun a ha hx => (h a ha).1 hx) (le_iff_atom_le_imp.2 fun a ha hy => (h a ha).2 hy) end BooleanAlgebra namespace CompleteBooleanAlgebra /-- Every atomic complete Boolean algebra is completely atomic. This is not made an instance to avoid typeclass loops. -/ -- See note [reducible non-instances] abbrev toCompleteAtomicBooleanAlgebra {α} [CompleteBooleanAlgebra α] [IsAtomic α] : CompleteAtomicBooleanAlgebra α where __ := ‹CompleteBooleanAlgebra α› iInf_iSup_eq f := BooleanAlgebra.eq_iff_atom_le_iff.2 fun a ha => by simp only [le_iInf_iff, ha.le_iSup, Classical.skolem] end CompleteBooleanAlgebra end Atomic section Atomistic variable (α) [PartialOrder α] /-- A lattice is atomistic iff every element is a `sSup` of a set of atoms. -/ @[mk_iff] class IsAtomistic [OrderBot α] : Prop where /-- Every element is a `sSup` of a set of atoms. -/ isLUB_atoms : ∀ b : α, ∃ s : Set α, IsLUB s b ∧ ∀ a, a ∈ s → IsAtom a /-- A lattice is coatomistic iff every element is an `sInf` of a set of coatoms. -/ @[mk_iff] class IsCoatomistic [OrderTop α] : Prop where /-- Every element is a `sInf` of a set of coatoms. -/ isGLB_coatoms : ∀ b : α, ∃ s : Set α, IsGLB s b ∧ ∀ a, a ∈ s → IsCoatom a export IsAtomistic (isLUB_atoms) export IsCoatomistic (isGLB_coatoms) variable {α} @[simp] theorem isCoatomistic_dual_iff_isAtomistic [OrderBot α] : IsCoatomistic αᵒᵈ ↔ IsAtomistic α := ⟨fun h => ⟨fun b => by apply h.isGLB_coatoms⟩, fun h => ⟨fun b => by apply h.isLUB_atoms⟩⟩ @[simp] theorem isAtomistic_dual_iff_isCoatomistic [OrderTop α] : IsAtomistic αᵒᵈ ↔ IsCoatomistic α := ⟨fun h => ⟨fun b => by apply h.isLUB_atoms⟩, fun h => ⟨fun b => by apply h.isGLB_coatoms⟩⟩ namespace IsAtomistic instance _root_.OrderDual.instIsCoatomistic [OrderBot α] [h : IsAtomistic α] : IsCoatomistic αᵒᵈ := isCoatomistic_dual_iff_isAtomistic.2 h variable [OrderBot α] [IsAtomistic α] instance (priority := 100) : IsAtomic α := ⟨fun b => by rcases isLUB_atoms b with ⟨s, hsb, hs⟩ rcases s.eq_empty_or_nonempty with rfl | ⟨a, ha⟩ · simp_all · exact Or.inr ⟨a, hs _ ha, hsb.1 ha⟩⟩ end IsAtomistic section IsAtomistic variable [OrderBot α] [IsAtomistic α] theorem isLUB_atoms_le (b : α) : IsLUB { a : α | IsAtom a ∧ a ≤ b } b := by rcases isLUB_atoms b with ⟨s, hsb, hs⟩ exact ⟨fun c hc ↦ hc.2, fun c hc ↦ hsb.2 fun i hi ↦ hc ⟨hs _ hi, hsb.1 hi⟩⟩ theorem isLUB_atoms_top [OrderTop α] : IsLUB { a : α | IsAtom a } ⊤ := by simpa using isLUB_atoms_le (⊤ : α) theorem le_iff_atom_le_imp {a b : α} : a ≤ b ↔ ∀ c : α, IsAtom c → c ≤ a → c ≤ b := ⟨fun hab _ _ hca ↦ hca.trans hab, fun h ↦ (isLUB_atoms_le a).mono (isLUB_atoms_le b) fun _ ⟨h₁, h₂⟩ ↦ ⟨h₁, h _ h₁ h₂⟩⟩ theorem eq_iff_atom_le_iff {a b : α} : a = b ↔ ∀ c, IsAtom c → (c ≤ a ↔ c ≤ b) := by refine ⟨fun h => by simp [h], fun h => ?_⟩ rw [le_antisymm_iff, le_iff_atom_le_imp, le_iff_atom_le_imp] simp_all end IsAtomistic namespace IsCoatomistic variable [OrderTop α] instance _root_.OrderDual.instIsAtomistic [h : IsCoatomistic α] : IsAtomistic αᵒᵈ := isAtomistic_dual_iff_isCoatomistic.2 h variable [IsCoatomistic α] instance (priority := 100) : IsCoatomic α := ⟨fun b => by rcases isGLB_coatoms b with ⟨s, hsb, hs⟩ rcases s.eq_empty_or_nonempty with rfl | ⟨a, ha⟩ · simp_all · exact Or.inr ⟨a, hs _ ha, hsb.1 ha⟩⟩ end IsCoatomistic section CompleteLattice @[simp] theorem sSup_atoms_le_eq {α} [CompleteLattice α] [IsAtomistic α] (b : α) : sSup { a : α | IsAtom a ∧ a ≤ b } = b := (isLUB_atoms_le b).sSup_eq @[simp] theorem sSup_atoms_eq_top {α} [CompleteLattice α] [IsAtomistic α] : sSup { a : α | IsAtom a } = ⊤ := isLUB_atoms_top.sSup_eq nonrec lemma CompleteLattice.isAtomistic_iff {α} [CompleteLattice α] : IsAtomistic α ↔ ∀ b : α, ∃ s : Set α, b = sSup s ∧ ∀ a ∈ s, IsAtom a := by simp_rw [isAtomistic_iff, isLUB_iff_sSup_eq, eq_comm] lemma eq_sSup_atoms {α} [CompleteLattice α] [IsAtomistic α] (b : α) : ∃ s : Set α, b = sSup s ∧ ∀ a ∈ s, IsAtom a := CompleteLattice.isAtomistic_iff.1 ‹_› b nonrec lemma CompleteLattice.isCoatomistic_iff {α} [CompleteLattice α] : IsCoatomistic α ↔ ∀ b : α, ∃ s : Set α, b = sInf s ∧ ∀ a ∈ s, IsCoatom a := by simp_rw [isCoatomistic_iff, isGLB_iff_sInf_eq, eq_comm] lemma eq_sInf_coatoms {α} [CompleteLattice α] [IsCoatomistic α] (b : α) : ∃ s : Set α, b = sInf s ∧ ∀ a ∈ s, IsCoatom a := CompleteLattice.isCoatomistic_iff.1 ‹_› b end CompleteLattice namespace CompleteAtomicBooleanAlgebra instance {α} [CompleteAtomicBooleanAlgebra α] : IsAtomistic α := CompleteLattice.isAtomistic_iff.2 fun b ↦ by inhabit α refine ⟨{ a | IsAtom a ∧ a ≤ b }, ?_, fun a ha => ha.1⟩ refine le_antisymm ?_ (sSup_le fun c hc => hc.2) have : (⨅ c : α, ⨆ x, b ⊓ cond x c (cᶜ)) = b := by simp [iSup_bool_eq] rw [← this]; clear this simp_rw [iInf_iSup_eq, iSup_le_iff]; intro g if h : (⨅ a, b ⊓ cond (g a) a (aᶜ)) = ⊥ then simp [h] else refine le_sSup ⟨⟨h, fun c hc => ?_⟩, le_trans (by rfl) (le_iSup _ g)⟩; clear h have := lt_of_lt_of_le hc (le_trans (iInf_le _ c) inf_le_right) revert this nontriviality α cases g c <;> simp instance {α} [CompleteAtomicBooleanAlgebra α] : IsCoatomistic α := isAtomistic_dual_iff_isCoatomistic.1 inferInstance end CompleteAtomicBooleanAlgebra end Atomistic /-- An order is simple iff it has exactly two elements, `⊥` and `⊤`. -/ @[mk_iff] class IsSimpleOrder (α : Type*) [LE α] [BoundedOrder α] : Prop extends Nontrivial α where /-- Every element is either `⊥` or `⊤` -/ eq_bot_or_eq_top : ∀ a : α, a = ⊥ ∨ a = ⊤ export IsSimpleOrder (eq_bot_or_eq_top) lemma IsSimpleOrder.of_forall_eq_top {α : Type*} [LE α] [BoundedOrder α] [Nontrivial α] (h : ∀ a : α, a ≠ ⊥ → a = ⊤) : IsSimpleOrder α where eq_bot_or_eq_top a := or_iff_not_imp_left.mpr <| h a theorem isSimpleOrder_iff_isSimpleOrder_orderDual [LE α] [BoundedOrder α] : IsSimpleOrder α ↔ IsSimpleOrder αᵒᵈ := by constructor <;> intro i · exact { eq_bot_or_eq_top := fun a => Or.symm (eq_bot_or_eq_top (OrderDual.ofDual a) : _ ∨ _) } · exact { exists_pair_ne := @exists_pair_ne αᵒᵈ _ eq_bot_or_eq_top := fun a => Or.symm (eq_bot_or_eq_top (OrderDual.toDual a)) } theorem IsSimpleOrder.bot_ne_top [LE α] [BoundedOrder α] [IsSimpleOrder α] : (⊥ : α) ≠ (⊤ : α) := by obtain ⟨a, b, h⟩ := exists_pair_ne α rcases eq_bot_or_eq_top a with (rfl | rfl) <;> rcases eq_bot_or_eq_top b with (rfl | rfl) <;> first | simpa | simpa using h.symm section IsSimpleOrder variable [PartialOrder α] [BoundedOrder α] [IsSimpleOrder α] instance OrderDual.instIsSimpleOrder {α} [LE α] [BoundedOrder α] [IsSimpleOrder α] : IsSimpleOrder αᵒᵈ := isSimpleOrder_iff_isSimpleOrder_orderDual.1 (by infer_instance) /-- A simple `BoundedOrder` induces a preorder. This is not an instance to prevent loops. -/ protected def IsSimpleOrder.preorder {α} [LE α] [BoundedOrder α] [IsSimpleOrder α] : Preorder α where le_refl a := by rcases eq_bot_or_eq_top a with (rfl | rfl) <;> simp le_trans a b c := by rcases eq_bot_or_eq_top a with (rfl | rfl) · simp · rcases eq_bot_or_eq_top b with (rfl | rfl) · rcases eq_bot_or_eq_top c with (rfl | rfl) <;> simp · simp /-- A simple partial ordered `BoundedOrder` induces a linear order. This is not an instance to prevent loops. -/ protected def IsSimpleOrder.linearOrder [DecidableEq α] : LinearOrder α := { (inferInstance : PartialOrder α) with le_total := fun a b => by rcases eq_bot_or_eq_top a with (rfl | rfl) <;> simp -- Note from https://github.com/leanprover-community/mathlib4/issues/23976: do we want this inlined or should this be a separate definition? toDecidableLE := fun a b => if ha : a = ⊥ then isTrue (ha.le.trans bot_le) else if hb : b = ⊤ then isTrue (le_top.trans hb.ge) else isFalse fun H => hb (top_unique (le_trans (top_le_iff.mpr (Or.resolve_left (eq_bot_or_eq_top a) ha)) H)) toDecidableEq := ‹_› } theorem isAtom_top : IsAtom (⊤ : α) := ⟨top_ne_bot, fun a ha => Or.resolve_right (eq_bot_or_eq_top a) (ne_of_lt ha)⟩ @[simp] theorem isAtom_iff_eq_top {a : α} : IsAtom a ↔ a = ⊤ := ⟨fun h ↦ (eq_bot_or_eq_top a).resolve_left h.1, (· ▸ isAtom_top)⟩ theorem isCoatom_bot : IsCoatom (⊥ : α) := isAtom_dual_iff_isCoatom.1 isAtom_top @[simp] theorem isCoatom_iff_eq_bot {a : α} : IsCoatom a ↔ a = ⊥ := ⟨fun h ↦ (eq_bot_or_eq_top a).resolve_right h.1, (· ▸ isCoatom_bot)⟩ theorem bot_covBy_top : (⊥ : α) ⋖ ⊤ := isAtom_top.bot_covBy end IsSimpleOrder namespace IsSimpleOrder section Preorder variable [Preorder α] [BoundedOrder α] [IsSimpleOrder α] {a b : α} (h : a < b) include h theorem eq_bot_of_lt : a = ⊥ := (IsSimpleOrder.eq_bot_or_eq_top _).resolve_right h.ne_top theorem eq_top_of_lt : b = ⊤ := (IsSimpleOrder.eq_bot_or_eq_top _).resolve_left h.ne_bot alias _root_.LT.lt.eq_bot := eq_bot_of_lt alias _root_.LT.lt.eq_top := eq_top_of_lt end Preorder section BoundedOrder variable [Lattice α] [BoundedOrder α] [IsSimpleOrder α] /-- A simple partial ordered `BoundedOrder` induces a lattice. This is not an instance to prevent loops -/ protected def lattice {α} [DecidableEq α] [PartialOrder α] [BoundedOrder α] [IsSimpleOrder α] : Lattice α := @LinearOrder.toLattice α IsSimpleOrder.linearOrder /-- A lattice that is a `BoundedOrder` is a distributive lattice. This is not an instance to prevent loops -/ protected def distribLattice : DistribLattice α := { (inferInstance : Lattice α) with le_sup_inf := fun x y z => by rcases eq_bot_or_eq_top x with (rfl | rfl) <;> simp } -- see Note [lower instance priority] instance (priority := 100) : IsAtomic α := ⟨fun b => (eq_bot_or_eq_top b).imp_right fun h => ⟨⊤, ⟨isAtom_top, ge_of_eq h⟩⟩⟩ -- see Note [lower instance priority] instance (priority := 100) : IsCoatomic α := isAtomic_dual_iff_isCoatomic.1 (by infer_instance) end BoundedOrder -- It is important that in this section `IsSimpleOrder` is the last type-class argument. section DecidableEq variable [DecidableEq α] [PartialOrder α] [BoundedOrder α] [IsSimpleOrder α] /-- Every simple lattice is isomorphic to `Bool`, regardless of order. -/ @[simps] def equivBool {α} [DecidableEq α] [LE α] [BoundedOrder α] [IsSimpleOrder α] : α ≃ Bool where toFun x := x = ⊤ invFun x := x.casesOn ⊥ ⊤ left_inv x := by rcases eq_bot_or_eq_top x with (rfl | rfl) <;> simp [bot_ne_top] right_inv x := by cases x <;> simp [bot_ne_top] /-- Every simple lattice over a partial order is order-isomorphic to `Bool`. -/ def orderIsoBool : α ≃o Bool := { equivBool with map_rel_iff' := @fun a b => by rcases eq_bot_or_eq_top a with (rfl | rfl) · simp · rcases eq_bot_or_eq_top b with (rfl | rfl) · simp [bot_ne_top.symm, Bool.false_lt_true] · simp } /-- A simple `BoundedOrder` is also a `BooleanAlgebra`. -/ protected def booleanAlgebra {α} [DecidableEq α] [Lattice α] [BoundedOrder α] [IsSimpleOrder α] : BooleanAlgebra α := { inferInstanceAs (BoundedOrder α), IsSimpleOrder.distribLattice with compl := fun x => if x = ⊥ then ⊤ else ⊥ sdiff := fun x y => if x = ⊤ ∧ y = ⊥ then ⊤ else ⊥ sdiff_eq := fun x y => by rcases eq_bot_or_eq_top x with (rfl | rfl) <;> simp inf_compl_le_bot := fun x => by rcases eq_bot_or_eq_top x with (rfl | rfl) · simp · simp top_le_sup_compl := fun x => by rcases eq_bot_or_eq_top x with (rfl | rfl) <;> simp } end DecidableEq variable [Lattice α] [BoundedOrder α] [IsSimpleOrder α] open Classical in /-- A simple `BoundedOrder` is also complete. -/ protected noncomputable def completeLattice : CompleteLattice α := { (inferInstance : Lattice α), (inferInstance : BoundedOrder α) with sSup := fun s => if ⊤ ∈ s then ⊤ else ⊥ sInf := fun s => if ⊥ ∈ s then ⊥ else ⊤ le_sSup := fun s x h => by rcases eq_bot_or_eq_top x with (rfl | rfl) · exact bot_le · rw [if_pos h] sSup_le := fun s x h => by rcases eq_bot_or_eq_top x with (rfl | rfl) · rw [if_neg] intro con exact bot_ne_top (eq_top_iff.2 (h ⊤ con)) · exact le_top sInf_le := fun s x h => by rcases eq_bot_or_eq_top x with (rfl | rfl) · rw [if_pos h] · exact le_top le_sInf := fun s x h => by rcases eq_bot_or_eq_top x with (rfl | rfl) · exact bot_le · rw [if_neg] intro con exact top_ne_bot (eq_bot_iff.2 (h ⊥ con)) } open Classical in /-- A simple `BoundedOrder` is also a `CompleteBooleanAlgebra`. -/ protected noncomputable def completeBooleanAlgebra : CompleteBooleanAlgebra α := { __ := IsSimpleOrder.completeLattice __ := IsSimpleOrder.booleanAlgebra } instance : ComplementedLattice α := letI := IsSimpleOrder.completeBooleanAlgebra (α := α); inferInstance end IsSimpleOrder namespace IsSimpleOrder variable [PartialOrder α] [BoundedOrder α] [IsSimpleOrder α] instance (priority := 100) : IsAtomistic α where isLUB_atoms b := (eq_bot_or_eq_top b).elim (fun h ↦ ⟨∅, by simp [h]⟩) (fun h ↦ ⟨{⊤}, by simp [h]⟩) instance (priority := 100) : IsCoatomistic α := isAtomistic_dual_iff_isCoatomistic.1 (by infer_instance) @[simp] lemma bot_lt_iff_eq_top {a : α} : ⊥ < a ↔ a = ⊤ := ⟨eq_top_of_lt, fun h ↦ h ▸ bot_lt_top⟩ @[simp] lemma lt_top_iff_eq_bot {a : α} : a < ⊤ ↔ a = ⊥ := ⟨eq_bot_of_lt, fun h ↦ h ▸ bot_lt_top⟩ end IsSimpleOrder theorem isSimpleOrder_iff_isAtom_top [PartialOrder α] [BoundedOrder α] : IsSimpleOrder α ↔ IsAtom (⊤ : α) := ⟨fun h => @isAtom_top _ _ _ h, fun h => { exists_pair_ne := ⟨⊤, ⊥, h.1⟩ eq_bot_or_eq_top := fun a => ((eq_or_lt_of_le le_top).imp_right (h.2 a)).symm }⟩ theorem isSimpleOrder_iff_isCoatom_bot [PartialOrder α] [BoundedOrder α] : IsSimpleOrder α ↔ IsCoatom (⊥ : α) := isSimpleOrder_iff_isSimpleOrder_orderDual.trans isSimpleOrder_iff_isAtom_top namespace Set theorem isSimpleOrder_Iic_iff_isAtom [PartialOrder α] [OrderBot α] {a : α} : IsSimpleOrder (Iic a) ↔ IsAtom a := isSimpleOrder_iff_isAtom_top.trans <| and_congr (not_congr Subtype.mk_eq_mk) ⟨fun h b ab => Subtype.mk_eq_mk.1 (h ⟨b, le_of_lt ab⟩ ab), fun h ⟨b, _⟩ hbotb => Subtype.mk_eq_mk.2 (h b (Subtype.mk_lt_mk.1 hbotb))⟩ theorem isSimpleOrder_Ici_iff_isCoatom [PartialOrder α] [OrderTop α] {a : α} : IsSimpleOrder (Ici a) ↔ IsCoatom a := isSimpleOrder_iff_isCoatom_bot.trans <| and_congr (not_congr Subtype.mk_eq_mk) ⟨fun h b ab => Subtype.mk_eq_mk.1 (h ⟨b, le_of_lt ab⟩ ab), fun h ⟨b, _⟩ hbotb => Subtype.mk_eq_mk.2 (h b (Subtype.mk_lt_mk.1 hbotb))⟩ end Set namespace OrderEmbedding variable [PartialOrder α] [PartialOrder β] theorem isAtom_of_map_bot_of_image [OrderBot α] [OrderBot β] (f : β ↪o α) (hbot : f ⊥ = ⊥) {b : β} (hb : IsAtom (f b)) : IsAtom b := by simp only [← bot_covBy_iff] at hb ⊢ exact CovBy.of_image f (hbot.symm ▸ hb) theorem isCoatom_of_map_top_of_image [OrderTop α] [OrderTop β] (f : β ↪o α) (htop : f ⊤ = ⊤) {b : β} (hb : IsCoatom (f b)) : IsCoatom b := f.dual.isAtom_of_map_bot_of_image htop hb end OrderEmbedding namespace GaloisInsertion variable [PartialOrder α] [PartialOrder β] theorem isAtom_of_u_bot [OrderBot α] [OrderBot β] {l : α → β} {u : β → α} (gi : GaloisInsertion l u) (hbot : u ⊥ = ⊥) {b : β} (hb : IsAtom (u b)) : IsAtom b := OrderEmbedding.isAtom_of_map_bot_of_image ⟨⟨u, gi.u_injective⟩, @GaloisInsertion.u_le_u_iff _ _ _ _ _ _ gi⟩ hbot hb theorem isAtom_iff [OrderBot α] [IsAtomic α] [OrderBot β] {l : α → β} {u : β → α} (gi : GaloisInsertion l u) (hbot : u ⊥ = ⊥) (h_atom : ∀ a, IsAtom a → u (l a) = a) (a : α) : IsAtom (l a) ↔ IsAtom a := by refine ⟨fun hla => ?_, fun ha => gi.isAtom_of_u_bot hbot ((h_atom a ha).symm ▸ ha)⟩ obtain ⟨a', ha', hab'⟩ := (eq_bot_or_exists_atom_le (u (l a))).resolve_left (hbot ▸ fun h => hla.1 (gi.u_injective h)) have := (hla.le_iff.mp <| (gi.l_u_eq (l a) ▸ gi.gc.monotone_l hab' : l a' ≤ l a)).resolve_left fun h => ha'.1 (hbot ▸ h_atom a' ha' ▸ congr_arg u h) have haa' : a = a' := (ha'.le_iff.mp <| (gi.gc.le_u_l a).trans_eq (h_atom a' ha' ▸ congr_arg u this.symm)).resolve_left (mt (congr_arg l) (gi.gc.l_bot.symm ▸ hla.1)) exact haa'.symm ▸ ha' theorem isAtom_iff' [OrderBot α] [IsAtomic α] [OrderBot β] {l : α → β} {u : β → α} (gi : GaloisInsertion l u) (hbot : u ⊥ = ⊥) (h_atom : ∀ a, IsAtom a → u (l a) = a) (b : β) : IsAtom (u b) ↔ IsAtom b := by rw [← gi.isAtom_iff hbot h_atom, gi.l_u_eq] theorem isCoatom_of_image [OrderTop α] [OrderTop β] {l : α → β} {u : β → α} (gi : GaloisInsertion l u) {b : β} (hb : IsCoatom (u b)) : IsCoatom b := OrderEmbedding.isCoatom_of_map_top_of_image ⟨⟨u, gi.u_injective⟩, @GaloisInsertion.u_le_u_iff _ _ _ _ _ _ gi⟩ gi.gc.u_top hb theorem isCoatom_iff [OrderTop α] [IsCoatomic α] [OrderTop β] {l : α → β} {u : β → α} (gi : GaloisInsertion l u) (h_coatom : ∀ a : α, IsCoatom a → u (l a) = a) (b : β) : IsCoatom (u b) ↔ IsCoatom b := by refine ⟨fun hb => gi.isCoatom_of_image hb, fun hb => ?_⟩ obtain ⟨a, ha, hab⟩ := (eq_top_or_exists_le_coatom (u b)).resolve_left fun h => hb.1 <| (gi.gc.u_top ▸ gi.l_u_eq ⊤ : l ⊤ = ⊤) ▸ gi.l_u_eq b ▸ congr_arg l h have : l a = b := (hb.le_iff.mp (gi.l_u_eq b ▸ gi.gc.monotone_l hab : b ≤ l a)).resolve_left fun hla => ha.1 (gi.gc.u_top ▸ h_coatom a ha ▸ congr_arg u hla) exact this ▸ (h_coatom a ha).symm ▸ ha end GaloisInsertion namespace GaloisCoinsertion variable [PartialOrder α] [PartialOrder β] theorem isCoatom_of_l_top [OrderTop α] [OrderTop β] {l : α → β} {u : β → α} (gi : GaloisCoinsertion l u) (hbot : l ⊤ = ⊤) {a : α} (hb : IsCoatom (l a)) : IsCoatom a := gi.dual.isAtom_of_u_bot hbot hb.dual theorem isCoatom_iff [OrderTop α] [OrderTop β] [IsCoatomic β] {l : α → β} {u : β → α} (gi : GaloisCoinsertion l u) (htop : l ⊤ = ⊤) (h_coatom : ∀ b, IsCoatom b → l (u b) = b) (b : β) : IsCoatom (u b) ↔ IsCoatom b := gi.dual.isAtom_iff htop h_coatom b theorem isCoatom_iff' [OrderTop α] [OrderTop β] [IsCoatomic β] {l : α → β} {u : β → α} (gi : GaloisCoinsertion l u) (htop : l ⊤ = ⊤) (h_coatom : ∀ b, IsCoatom b → l (u b) = b) (a : α) : IsCoatom (l a) ↔ IsCoatom a := gi.dual.isAtom_iff' htop h_coatom a theorem isAtom_of_image [OrderBot α] [OrderBot β] {l : α → β} {u : β → α} (gi : GaloisCoinsertion l u) {a : α} (hb : IsAtom (l a)) : IsAtom a := gi.dual.isCoatom_of_image hb.dual theorem isAtom_iff [OrderBot α] [OrderBot β] [IsAtomic β] {l : α → β} {u : β → α} (gi : GaloisCoinsertion l u) (h_atom : ∀ b, IsAtom b → l (u b) = b) (a : α) : IsAtom (l a) ↔ IsAtom a := gi.dual.isCoatom_iff h_atom a end GaloisCoinsertion namespace OrderIso variable [PartialOrder α] [PartialOrder β] @[simp] theorem isAtom_iff [OrderBot α] [OrderBot β] (f : α ≃o β) (a : α) : IsAtom (f a) ↔ IsAtom a := ⟨f.toGaloisCoinsertion.isAtom_of_image, fun ha => f.toGaloisInsertion.isAtom_of_u_bot (map_bot f.symm) <| (f.symm_apply_apply a).symm ▸ ha⟩ @[simp] theorem isCoatom_iff [OrderTop α] [OrderTop β] (f : α ≃o β) (a : α) : IsCoatom (f a) ↔ IsCoatom a := f.dual.isAtom_iff a theorem isSimpleOrder_iff [BoundedOrder α] [BoundedOrder β] (f : α ≃o β) : IsSimpleOrder α ↔ IsSimpleOrder β := by rw [isSimpleOrder_iff_isAtom_top, isSimpleOrder_iff_isAtom_top, ← f.isAtom_iff ⊤, f.map_top] theorem isSimpleOrder [BoundedOrder α] [BoundedOrder β] [h : IsSimpleOrder β] (f : α ≃o β) : IsSimpleOrder α := f.isSimpleOrder_iff.mpr h protected theorem isAtomic_iff [OrderBot α] [OrderBot β] (f : α ≃o β) : IsAtomic α ↔ IsAtomic β := by simp only [isAtomic_iff, f.surjective.forall, f.surjective.exists, ← map_bot f, f.eq_iff_eq, f.le_iff_le, f.isAtom_iff] protected theorem isCoatomic_iff [OrderTop α] [OrderTop β] (f : α ≃o β) : IsCoatomic α ↔ IsCoatomic β := by simp only [← isAtomic_dual_iff_isCoatomic, f.dual.isAtomic_iff] end OrderIso section Lattice variable [Lattice α] /-- An upper-modular lattice that is atomistic is strongly atomic. Not an instance to prevent loops. -/ theorem Lattice.isStronglyAtomic [OrderBot α] [IsUpperModularLattice α] [IsAtomistic α] : IsStronglyAtomic α where exists_covBy_le_of_lt a b hab := by obtain ⟨s, hsb, h⟩ := isLUB_atoms b refine by_contra fun hcon ↦ hab.not_ge <| (isLUB_le_iff hsb).2 fun x hx ↦ ?_ simp_rw [not_exists, and_comm (b := _ ≤ _), not_and] at hcon specialize hcon (x ⊔ a) (sup_le (hsb.1 hx) hab.le) obtain (hbot | h_inf) := (h x hx).bot_covBy.eq_or_eq (c := x ⊓ a) (by simp) (by simp) · exact False.elim <| hcon <| (hbot ▸ IsUpperModularLattice.covBy_sup_of_inf_covBy) (h x hx).bot_covBy rwa [inf_eq_left] at h_inf /-- A lower-modular lattice that is coatomistic is strongly coatomic. Not an instance to prevent loops. -/ theorem Lattice.isStronglyCoatomic [OrderTop α] [IsLowerModularLattice α] [IsCoatomistic α] : IsStronglyCoatomic α := by rw [← isStronglyAtomic_dual_iff_is_stronglyCoatomic] exact Lattice.isStronglyAtomic end Lattice section IsModularLattice variable [Lattice α] [BoundedOrder α] [IsModularLattice α] namespace IsCompl variable {a b : α} (hc : IsCompl a b) include hc theorem isAtom_iff_isCoatom : IsAtom a ↔ IsCoatom b := Set.isSimpleOrder_Iic_iff_isAtom.symm.trans <| hc.IicOrderIsoIci.isSimpleOrder_iff.trans Set.isSimpleOrder_Ici_iff_isCoatom theorem isCoatom_iff_isAtom : IsCoatom a ↔ IsAtom b := hc.symm.isAtom_iff_isCoatom.symm end IsCompl variable [ComplementedLattice α] theorem isCoatomic_of_isAtomic_of_complementedLattice_of_isModular [IsAtomic α] : IsCoatomic α := ⟨fun x => by rcases exists_isCompl x with ⟨y, xy⟩ apply (eq_bot_or_exists_atom_le y).imp _ _ · rintro rfl exact eq_top_of_isCompl_bot xy · rintro ⟨a, ha, ay⟩ rcases exists_isCompl (xy.symm.IicOrderIsoIci ⟨a, ay⟩) with ⟨⟨b, xb⟩, hb⟩ refine ⟨↑(⟨b, xb⟩ : Set.Ici x), IsCoatom.of_isCoatom_coe_Ici ?_, xb⟩ rw [← hb.isAtom_iff_isCoatom, OrderIso.isAtom_iff] apply ha.Iic⟩ theorem isAtomic_of_isCoatomic_of_complementedLattice_of_isModular [IsCoatomic α] : IsAtomic α := isCoatomic_dual_iff_isAtomic.1 isCoatomic_of_isAtomic_of_complementedLattice_of_isModular theorem isAtomic_iff_isCoatomic : IsAtomic α ↔ IsCoatomic α := ⟨fun _ => isCoatomic_of_isAtomic_of_complementedLattice_of_isModular, fun _ => isAtomic_of_isCoatomic_of_complementedLattice_of_isModular⟩ /-- A complemented modular atomic lattice is strongly atomic. Not an instance to prevent loops. -/ theorem ComplementedLattice.isStronglyAtomic [IsAtomic α] : IsStronglyAtomic α where exists_covBy_le_of_lt a b hab := by obtain ⟨⟨a', ha'b : a' ≤ b⟩, ha'⟩ := exists_isCompl (α := Set.Iic b) ⟨a, hab.le⟩ obtain (rfl | ⟨d, hd⟩) := eq_bot_or_exists_atom_le a' · obtain rfl : a = b := by simpa [codisjoint_bot, ← Subtype.coe_inj] using ha'.codisjoint exact False.elim <| hab.ne rfl refine ⟨d ⊔ a, IsUpperModularLattice.covBy_sup_of_inf_covBy ?_, sup_le (hd.2.trans ha'b) hab.le⟩ convert hd.1.bot_covBy rw [← le_bot_iff, ← show a ⊓ a' = ⊥ by simpa using Subtype.coe_inj.2 ha'.inf_eq_bot, inf_comm] exact inf_le_inf_left _ hd.2 /-- A complemented modular coatomic lattice is strongly coatomic. Not an instance to prevent loops. -/ theorem ComplementedLattice.isStronglyCoatomic [IsCoatomic α] : IsStronglyCoatomic α := isStronglyAtomic_dual_iff_is_stronglyCoatomic.1 <| ComplementedLattice.isStronglyAtomic /-- A complemented modular atomic lattice is strongly coatomic. Not an instance to prevent loops. -/ theorem ComplementedLattice.isStronglyAtomic' [h : IsAtomic α] : IsStronglyCoatomic α := by rw [isAtomic_iff_isCoatomic] at h exact isStronglyCoatomic /-- A complemented modular coatomic lattice is strongly atomic. Not an instance to prevent loops. -/ theorem ComplementedLattice.isStronglyCoatomic' [h : IsCoatomic α] : IsStronglyAtomic α := by rw [← isAtomic_iff_isCoatomic] at h exact isStronglyAtomic end IsModularLattice namespace «Prop» instance : IsSimpleOrder Prop where eq_bot_or_eq_top p := by simp [em'] theorem isAtom_iff {p : Prop} : IsAtom p ↔ p := by simp theorem isCoatom_iff {p : Prop} : IsCoatom p ↔ ¬ p := by simp end «Prop» namespace Pi universe u variable {ι : Type*} {π : ι → Type u} protected theorem eq_bot_iff [∀ i, Bot (π i)] {f : ∀ i, π i} : f = ⊥ ↔ ∀ i, f i = ⊥ := funext_iff theorem isAtom_iff {f : ∀ i, π i} [∀ i, PartialOrder (π i)] [∀ i, OrderBot (π i)] : IsAtom f ↔ ∃ i, IsAtom (f i) ∧ ∀ j, j ≠ i → f j = ⊥ := by simp only [← bot_covBy_iff, Pi.covBy_iff, bot_apply, eq_comm] theorem isAtom_single {i : ι} [DecidableEq ι] [∀ i, PartialOrder (π i)] [∀ i, OrderBot (π i)] {a : π i} (h : IsAtom a) : IsAtom (Function.update (⊥ : ∀ i, π i) i a) := isAtom_iff.2 ⟨i, by simpa, fun _ hji => Function.update_of_ne hji ..⟩ theorem isAtom_iff_eq_single [DecidableEq ι] [∀ i, PartialOrder (π i)] [∀ i, OrderBot (π i)] {f : ∀ i, π i} : IsAtom f ↔ ∃ i a, IsAtom a ∧ f = Function.update ⊥ i a := by simp [← bot_covBy_iff, covBy_iff_exists_right_eq] instance isAtomic [∀ i, PartialOrder (π i)] [∀ i, OrderBot (π i)] [∀ i, IsAtomic (π i)] : IsAtomic (∀ i, π i) where eq_bot_or_exists_atom_le b := or_iff_not_imp_left.2 fun h => have ⟨i, hi⟩ : ∃ i, b i ≠ ⊥ := not_forall.1 (h.imp Pi.eq_bot_iff.2) have ⟨a, ha, hab⟩ := (eq_bot_or_exists_atom_le (b i)).resolve_left hi by classical exact ⟨Function.update ⊥ i a, isAtom_single ha, update_le_iff.2 ⟨hab, by simp⟩⟩ instance isCoatomic [∀ i, PartialOrder (π i)] [∀ i, OrderTop (π i)] [∀ i, IsCoatomic (π i)] : IsCoatomic (∀ i, π i) := isAtomic_dual_iff_isCoatomic.1 <| show IsAtomic (∀ i, (π i)ᵒᵈ) from inferInstance instance isAtomistic [∀ i, PartialOrder (π i)] [∀ i, OrderBot (π i)] [∀ i, IsAtomistic (π i)] : IsAtomistic (∀ i, π i) where isLUB_atoms s := by classical refine ⟨{f | IsAtom f ∧ f ≤ s}, ?_, by simp +contextual⟩ rw [isLUB_pi] intro i simp_rw [isAtom_iff_eq_single] refine ⟨?_, ?_⟩ · rintro _ ⟨_, ⟨⟨_, _, _, rfl⟩, hs⟩, rfl⟩ exact hs i · refine fun j hj ↦ (isLUB_atoms_le (s i)).2 fun x ⟨hx₁, hx₂⟩ ↦ ?_ exact hj ⟨Function.update ⊥ i x, ⟨⟨_, x, hx₁, rfl⟩, by simp [update_le_iff, hx₂]⟩, by simp⟩ instance isCoatomistic [∀ i, CompleteLattice (π i)] [∀ i, IsCoatomistic (π i)] : IsCoatomistic (∀ i, π i) := isAtomistic_dual_iff_isCoatomistic.1 <| show IsAtomistic (∀ i, (π i)ᵒᵈ) from inferInstance end Pi section BooleanAlgebra variable [BooleanAlgebra α] {a b : α} @[simp] lemma isAtom_compl : IsAtom aᶜ ↔ IsCoatom a := isCompl_compl.symm.isAtom_iff_isCoatom @[simp] lemma isCoatom_compl : IsCoatom aᶜ ↔ IsAtom a := isCompl_compl.symm.isCoatom_iff_isAtom protected alias ⟨IsAtom.of_compl, IsCoatom.compl⟩ := isAtom_compl protected alias ⟨IsCoatom.of_compl, IsAtom.compl⟩ := isCoatom_compl end BooleanAlgebra namespace Set theorem isAtom_singleton (x : α) : IsAtom ({x} : Set α) := ⟨singleton_ne_empty _, fun _ hs => ssubset_singleton_iff.mp hs⟩ theorem isAtom_iff {s : Set α} : IsAtom s ↔ ∃ x, s = {x} := by refine ⟨?_, by rintro ⟨x, rfl⟩ exact isAtom_singleton x⟩ rw [isAtom_iff_le_of_ge, bot_eq_empty, ← nonempty_iff_ne_empty] rintro ⟨⟨x, hx⟩, hs⟩ exact ⟨x, eq_singleton_iff_unique_mem.2 ⟨hx, fun y hy => (hs {y} (singleton_ne_empty _) (singleton_subset_iff.2 hy) hx).symm⟩⟩ theorem isCoatom_iff (s : Set α) : IsCoatom s ↔ ∃ x, s = {x}ᶜ := by rw [isCompl_compl.isCoatom_iff_isAtom, isAtom_iff] simp_rw [@eq_comm _ s, compl_eq_comm] theorem isCoatom_singleton_compl (x : α) : IsCoatom ({x}ᶜ : Set α) := (isCoatom_iff {x}ᶜ).mpr ⟨x, rfl⟩ instance : IsAtomistic (Set α) := inferInstance instance : IsCoatomistic (Set α) := inferInstance end Set
.lake/packages/mathlib/Mathlib/Order/Disjointed.lean
import Mathlib.Order.PartialSups import Mathlib.Order.Interval.Finset.Fin /-! # Making a sequence disjoint This file defines the way to make a sequence of sets - or, more generally, a map from a partially ordered type `ι` into a (generalized) Boolean algebra `α` - into a *pairwise disjoint* sequence with the same partial sups. For a sequence `f : ℕ → α`, this new sequence will be `f 0`, `f 1 \ f 0`, `f 2 \ (f 0 ⊔ f 1) ⋯`. It is actually unique, as `disjointed_unique` shows. ## Main declarations * `disjointed f`: The map sending `i` to `f i \ (⨆ j < i, f j)`. We require the index type to be a `LocallyFiniteOrderBot` to ensure that the supremum is well defined. * `partialSups_disjointed`: `disjointed f` has the same partial sups as `f`. * `disjoint_disjointed`: The elements of `disjointed f` are pairwise disjoint. * `disjointed_unique`: `disjointed f` is the only pairwise disjoint sequence having the same partial sups as `f`. * `Fintype.sup_disjointed` (for finite `ι`) or `iSup_disjointed` (for complete `α`): `disjointed f` has the same supremum as `f`. Limiting case of `partialSups_disjointed`. * `Fintype.exists_disjointed_le`: for any finite family `f : ι → α`, there exists a pairwise disjoint family `g : ι → α` which is bounded above by `f` and has the same supremum. This is an analogue of `disjointed` for arbitrary finite index types (but without any uniqueness). We also provide set notation variants of some lemmas. -/ assert_not_exists SuccAddOrder open Finset Order variable {α ι : Type*} open scoped Function -- required for scoped `on` notation section GeneralizedBooleanAlgebra variable [GeneralizedBooleanAlgebra α] section Preorder -- the *index type* is a preorder variable [Preorder ι] [LocallyFiniteOrderBot ι] /-- The function mapping `i` to `f i \ (⨆ j < i, f j)`. When `ι` is a partial order, this is the unique function `g` having the same `partialSups` as `f` and such that `g i` and `g j` are disjoint whenever `i < j`. -/ def disjointed (f : ι → α) (i : ι) : α := f i \ (Iio i).sup f lemma disjointed_apply (f : ι → α) (i : ι) : disjointed f i = f i \ (Iio i).sup f := rfl lemma disjointed_of_isMin (f : ι → α) {i : ι} (hn : IsMin i) : disjointed f i = f i := by have : Iio i = ∅ := by rwa [← Finset.coe_eq_empty, coe_Iio, Set.Iio_eq_empty_iff] simp only [disjointed_apply, this, sup_empty, sdiff_bot] @[simp] lemma disjointed_bot [OrderBot ι] (f : ι → α) : disjointed f ⊥ = f ⊥ := disjointed_of_isMin _ isMin_bot theorem disjointed_le_id : disjointed ≤ (id : (ι → α) → ι → α) := fun _ _ ↦ sdiff_le theorem disjointed_le (f : ι → α) : disjointed f ≤ f := disjointed_le_id f theorem disjoint_disjointed_of_lt (f : ι → α) {i j : ι} (h : i < j) : Disjoint (disjointed f i) (disjointed f j) := (disjoint_sdiff_self_right.mono_left <| le_sup (mem_Iio.mpr h)).mono_left (disjointed_le f i) lemma disjointed_eq_self {f : ι → α} {i : ι} (hf : ∀ j < i, Disjoint (f j) (f i)) : disjointed f i = f i := by rw [disjointed_apply, sdiff_eq_left, disjoint_iff, sup_inf_distrib_left, sup_congr rfl <| fun j hj ↦ disjoint_iff.mp <| (hf _ (mem_Iio.mp hj)).symm] exact sup_bot _ /- NB: The original statement for `ι = ℕ` was a `def` and worked for `p : α → Sort*`. I couldn't prove the `Sort*` version for general `ι`, but all instances of `disjointedRec` in the library are for Prop anyway. -/ /-- An induction principle for `disjointed`. To prove something about `disjointed f i`, it's enough to prove it for `f i` and being able to extend through diffs. -/ lemma disjointedRec {f : ι → α} {p : α → Prop} (hdiff : ∀ ⦃t i⦄, p t → p (t \ f i)) : ∀ ⦃i⦄, p (f i) → p (disjointed f i) := by classical intro i hpi rw [disjointed] suffices ∀ (s : Finset ι), p (f i \ s.sup f) from this _ intro s induction s using Finset.induction with | empty => simpa only [sup_empty, sdiff_bot] using hpi | insert _ _ ht IH => rw [sup_insert, sup_comm, ← sdiff_sdiff] exact hdiff IH end Preorder section PartialOrder -- the index type is a partial order variable [PartialOrder ι] [LocallyFiniteOrderBot ι] @[simp] theorem partialSups_disjointed (f : ι → α) : partialSups (disjointed f) = partialSups f := by -- This seems to be much more awkward than the case of linear orders, because the supremum -- in the definition of `disjointed` can involve multiple "paths" through the poset. classical -- We argue by induction on the size of `Iio i`. suffices ∀ r i (hi : #(Iio i) ≤ r), partialSups (disjointed f) i = partialSups f i from OrderHom.ext _ _ (funext fun i ↦ this _ i le_rfl) intro r i hi induction r generalizing i with | zero => -- Base case: `n` is minimal, so `partialSups f i = partialSups (disjointed f) n = f i`. simp only [Nat.le_zero, card_eq_zero] at hi simp only [partialSups_apply, Iic_eq_cons_Iio, hi, disjointed_apply, sup'_eq_sup, sup_cons, sup_empty, sdiff_bot] | succ n ih => -- Induction step: first WLOG arrange that `#(Iio i) = r + 1` rcases lt_or_eq_of_le hi with hn | hn · exact ih _ <| Nat.le_of_lt_succ hn simp only [partialSups_apply (disjointed f), Iic_eq_cons_Iio, sup'_eq_sup, sup_cons] -- Key claim: we can write `Iio i` as a union of (finitely many) `Ici` intervals. have hun : (Iio i).biUnion Iic = Iio i := by ext r; simpa using ⟨fun ⟨a, ha⟩ ↦ ha.2.trans_lt ha.1, fun hr ↦ ⟨r, hr, le_rfl⟩⟩ -- Use claim and `sup_biUnion` to rewrite the supremum in the definition of `disjointed f` -- in terms of suprema over `Iic`'s. Then the RHS is a `sup` over `partialSups`, which we -- can rewrite via the induction hypothesis. rw [← hun, sup_biUnion, sup_congr rfl (g := partialSups f)] · simp only [funext (partialSups_apply f), sup'_eq_sup, ← sup_biUnion, hun] simp only [disjointed, sdiff_sup_self, Iic_eq_cons_Iio, sup_cons] · simp only [partialSups, sup'_eq_sup, OrderHom.coe_mk] at ih ⊢ refine fun x hx ↦ ih x ?_ -- Remains to show `∀ x in Iio i, #(Iio x) ≤ r`. rw [← Nat.lt_add_one_iff, ← hn] apply lt_of_lt_of_le (b := #(Iic x)) · simpa only [Iic_eq_cons_Iio, card_cons] using Nat.lt_succ_self _ · refine card_le_card (fun r hr ↦ ?_) simp only [mem_Iic, mem_Iio] at hx hr ⊢ exact hr.trans_lt hx lemma Fintype.sup_disjointed [Fintype ι] (f : ι → α) : univ.sup (disjointed f) = univ.sup f := by classical have hun : univ.biUnion Iic = (univ : Finset ι) := by ext r; simpa only [mem_biUnion, mem_univ, mem_Iic, true_and, iff_true] using ⟨r, le_rfl⟩ rw [← hun, sup_biUnion, sup_biUnion, sup_congr rfl (fun i _ ↦ ?_)] rw [← sup'_eq_sup nonempty_Iic, ← sup'_eq_sup nonempty_Iic, ← partialSups_apply, ← partialSups_apply, partialSups_disjointed] lemma disjointed_partialSups (f : ι → α) : disjointed (partialSups f) = disjointed f := by classical ext i have step1 : f i \ (Iio i).sup f = partialSups f i \ (Iio i).sup f := by rw [sdiff_eq_symm (sdiff_le.trans (le_partialSups f i))] simp only [funext (partialSups_apply f), sup'_eq_sup] rw [sdiff_sdiff_eq_sdiff_sup (sup_mono Iio_subset_Iic_self), sup_eq_right] simp only [Iic_eq_cons_Iio, sup_cons, sup_sdiff_left_self, sdiff_le_iff, le_sup_right] simp only [disjointed_apply, step1, funext (partialSups_apply f), sup'_eq_sup, ← sup_biUnion] congr 2 with r simpa only [mem_biUnion, mem_Iio, mem_Iic] using ⟨fun ⟨a, ha⟩ ↦ ha.2.trans_lt ha.1, fun hr ↦ ⟨r, hr, le_rfl⟩⟩ /-- `disjointed f` is the unique map `d : ι → α` such that `d` has the same partial sups as `f`, and `d i` and `d j` are disjoint whenever `i < j`. -/ theorem disjointed_unique {f d : ι → α} (hdisj : ∀ {i j : ι} (_ : i < j), Disjoint (d i) (d j)) (hsups : partialSups d = partialSups f) : d = disjointed f := by rw [← disjointed_partialSups, ← hsups, disjointed_partialSups] exact funext fun _ ↦ (disjointed_eq_self (fun _ hj ↦ hdisj hj)).symm end PartialOrder section LinearOrder -- the index type is a linear order /-! ### Linear orders -/ variable [LinearOrder ι] [LocallyFiniteOrderBot ι] theorem disjoint_disjointed (f : ι → α) : Pairwise (Disjoint on disjointed f) := (pairwise_disjoint_on _).mpr fun _ _ ↦ disjoint_disjointed_of_lt f /-- `disjointed f` is the unique sequence that is pairwise disjoint and has the same partial sups as `f`. -/ theorem disjointed_unique' {f d : ι → α} (hdisj : Pairwise (Disjoint on d)) (hsups : partialSups d = partialSups f) : d = disjointed f := disjointed_unique (fun hij ↦ hdisj hij.ne) hsups omit [GeneralizedBooleanAlgebra α] in lemma Finset.disjiUnion_Iic_disjointed [DecidableEq α] (n : ι) (t : ι → Finset α) : (Iic n).disjiUnion (disjointed t) ((disjoint_disjointed t).set_pairwise _) = partialSups t n := by rw [← partialSups_disjointed, partialSups_apply, Finset.sup'_eq_sup, Finset.sup_eq_biUnion, disjiUnion_eq_biUnion] section SuccOrder variable [SuccOrder ι] lemma disjointed_succ (f : ι → α) {i : ι} (hi : ¬IsMax i) : disjointed f (succ i) = f (succ i) \ partialSups f i := by rw [disjointed_apply, partialSups_apply, sup'_eq_sup] congr 2 with m simpa only [mem_Iio, mem_Iic] using lt_succ_iff_of_not_isMax hi protected lemma Monotone.disjointed_succ {f : ι → α} (hf : Monotone f) {i : ι} (hn : ¬IsMax i) : disjointed f (succ i) = f (succ i) \ f i := by rwa [disjointed_succ, hf.partialSups_eq] /-- Note this lemma does not require `¬IsMax i`, unlike `disjointed_succ`. -/ lemma Monotone.disjointed_succ_sup {f : ι → α} (hf : Monotone f) (i : ι) : disjointed f (succ i) ⊔ f i = f (succ i) := by by_cases h : IsMax i · simpa only [succ_eq_iff_isMax.mpr h, sup_eq_right] using disjointed_le f i · rw [disjointed_apply] have : Iio (succ i) = Iic i := by ext simp only [mem_Iio, lt_succ_iff_eq_or_lt_of_not_isMax h, mem_Iic, le_iff_lt_or_eq, Or.comm] rw [this, ← sup'_eq_sup nonempty_Iic, ← partialSups_apply, hf.partialSups_eq, sdiff_sup_cancel <| hf <| le_succ i] end SuccOrder end LinearOrder /-! ### Functions on an arbitrary fintype -/ /-- For any finite family of elements `f : ι → α`, we can find a pairwise-disjoint family `g` bounded above by `f` and having the same supremum. This is non-canonical, depending on an arbitrary choice of ordering of `ι`. -/ lemma Fintype.exists_disjointed_le {ι : Type*} [Fintype ι] (f : ι → α) : ∃ g, g ≤ f ∧ univ.sup g = univ.sup f ∧ Pairwise (Disjoint on g) := by rcases isEmpty_or_nonempty ι with hι | hι · -- do `ι = ∅` separately since `⊤ : Fin n` isn't defined for `n = 0` exact ⟨f, le_rfl, rfl, Subsingleton.pairwise⟩ let R : ι ≃ Fin _ := equivFin ι let f' : Fin _ → α := f ∘ R.symm have hf' : f = f' ∘ R := by ext; simp only [Function.comp_apply, Equiv.symm_apply_apply, f'] refine ⟨disjointed f' ∘ R, ?_, ?_, ?_⟩ · intro n simpa only [hf'] using disjointed_le f' (R n) · simpa only [← sup_image, image_univ_equiv, hf'] using sup_disjointed f' · exact fun i j hij ↦ disjoint_disjointed f' (R.injective.ne hij) end GeneralizedBooleanAlgebra section CompleteBooleanAlgebra /-! ### Complete Boolean algebras -/ variable [CompleteBooleanAlgebra α] theorem iSup_disjointed [PartialOrder ι] [LocallyFiniteOrderBot ι] (f : ι → α) : ⨆ i, disjointed f i = ⨆ i, f i := iSup_eq_iSup_of_partialSups_eq_partialSups (partialSups_disjointed f) theorem disjointed_eq_inf_compl [Preorder ι] [LocallyFiniteOrderBot ι] (f : ι → α) (i : ι) : disjointed f i = f i ⊓ ⨅ j < i, (f j)ᶜ := by simp only [disjointed_apply, Finset.sup_eq_iSup, mem_Iio, sdiff_eq, compl_iSup] end CompleteBooleanAlgebra section Set /-! ### Lemmas specific to set-valued functions -/ theorem disjointed_subset [Preorder ι] [LocallyFiniteOrderBot ι] (f : ι → Set α) (i : ι) : disjointed f i ⊆ f i := disjointed_le f i theorem iUnion_disjointed [PartialOrder ι] [LocallyFiniteOrderBot ι] {f : ι → Set α} : ⋃ i, disjointed f i = ⋃ i, f i := iSup_disjointed f theorem disjointed_eq_inter_compl [Preorder ι] [LocallyFiniteOrderBot ι] (f : ι → Set α) (i : ι) : disjointed f i = f i ∩ ⋂ j < i, (f j)ᶜ := disjointed_eq_inf_compl f i theorem preimage_find_eq_disjointed (s : ℕ → Set α) (H : ∀ x, ∃ n, x ∈ s n) [∀ x n, Decidable (x ∈ s n)] (n : ℕ) : (fun x => Nat.find (H x)) ⁻¹' {n} = disjointed s n := by ext x simp [Nat.find_eq_iff, disjointed_eq_inter_compl] end Set section Nat /-! ### Functions on `ℕ` (See also `Mathlib/Algebra/Order/Disjointed.lean` for results with more algebra pre-requisites.) -/ variable [GeneralizedBooleanAlgebra α] @[simp] theorem disjointed_zero (f : ℕ → α) : disjointed f 0 = f 0 := disjointed_bot f end Nat
.lake/packages/mathlib/Mathlib/Order/TeichmullerTukey.lean
import Mathlib.Data.Set.Finite.Range import Mathlib.Data.Set.Finite.Lattice import Mathlib.Order.Zorn /-! # Teichmuller-Tukey This file defines the notion of being of finite character for a family of sets and proves the Teichmuller-Tukey lemma. ## Main definitions - `IsOfFiniteCharacter` : A family of sets $F$ is of finite character iff for every set $X$, $X ∈ F$ iff every finite subset of $X$ is in $F$. ## Main results - `IsOfFiniteCharacter.exists_maximal` : Teichmuller-Tukey lemma, saying that every nonempty family of finite character has a maximal element. ## References - <https://en.wikipedia.org/wiki/Teichm%C3%BCller%E2%80%93Tukey_lemma> -/ open Set Finite variable {α : Type*} (F : Set (Set α)) namespace Order /-- A family of sets $F$ is of finite character iff for every set $X$, $X ∈ F$ iff every finite subset of $X$ is in $F$ -/ def IsOfFiniteCharacter := ∀ x, x ∈ F ↔ ∀ y ⊆ x, y.Finite → y ∈ F /-- **Teichmuller-Tukey lemma**. Every nonempty family of finite character has a maximal element. -/ theorem IsOfFiniteCharacter.exists_maximal {F} (hF : IsOfFiniteCharacter F) {x : Set α} (xF : x ∈ F) : ∃ m, x ⊆ m ∧ Maximal (· ∈ F) m := by /- Apply Zorn's lemma. Take the union of the elements of a chain as its upper bound. -/ refine zorn_subset_nonempty F (fun c cF cch cne ↦ ⟨sUnion c, ?_, fun s sc ↦ subset_sUnion_of_mem sc⟩) x xF /- Prove that the union belongs to `F`. -/ refine (hF (sUnion c)).mpr fun s sc sfin ↦ ?_ /- Use the finite character property and the fact that any finite subset of the union is also a subset of some element of the chain. -/ obtain ⟨t, tc, st⟩ := cch.directedOn.exists_mem_subset_of_finite_of_subset_sUnion cne sfin sc exact (hF t).mp (cF tc) s st sfin end Order
.lake/packages/mathlib/Mathlib/Order/DirectedInverseSystem.lean
import Mathlib.Order.SuccPred.Limit import Mathlib.Order.UpperLower.Basic /-! # Definition of direct systems, inverse systems, and cardinalities in specific inverse systems The first part of this file concerns directed systems: `DirectLimit` is defined as the quotient of the disjoint union (`Sigma` type) by an equivalence relation (`Setoid`): compare `CategoryTheory.Limits.Types.Quot`, which is a quotient by a plain relation. Recursion and induction principles for constructing functions from and to `DirectLimit` and proving things about elements in `DirectLimit`. In the second part we compute the cardinality of each node in an inverse system `F i` indexed by a well-order in which every map between successive nodes has constant fiber `X i`, and every limit node is the `limit` of the inverse subsystem formed by all previous nodes. (To avoid importing `Cardinal`, we in fact construct a bijection rather than stating the result in terms of `Cardinal.mk`.) The most tricky part of the whole argument happens at limit nodes: if `i : ι` is a limit, what we have in hand is a family of bijections `F j ≃ ∀ l : Iio j, X l` for every `j < i`, which we would like to "glue" up to a bijection `F i ≃ ∀ l : Iio i, X l`. We denote `∀ l : Iio i, X l` by `PiLT X i`, and they form an inverse system just like the `F i`. Observe that at a limit node `i`, `PiLT X i` is actually the inverse limit of `PiLT X j` over all `j < i` (`piLTLim`). If the family of bijections `F j ≃ PiLT X j` is natural (`IsNatEquiv`), we immediately obtain a bijection between the limits `limit F i ≃ PiLT X i` (`invLimEquiv`), and we just need an additional bijection `F i ≃ limit F i` to obtain the desired extension `F i ≃ PiLT X i` to the limit node `i`. (We do have such a bijection, for example, when we consider a directed system of algebraic structures (say fields) `K i`, and `F` is the inverse system of homomorphisms `K i ⟶ K` into a specific field `K`.) Now our task reduces to the recursive construction of a *natural* family of bijections for each `i`. We can prove that a natural family over all `l ≤ i` (`Iic i`) extends to a natural family over `Iic i⁺` (where `i⁺ = succ i`), but at a limit node, recursion stops working: we have natural families over all `Iic j` for each `j < i`, but we need to know that they glue together to form a natural family over all `l < i` (`Iio i`). This intricacy did not occur to the author when he thought he had a proof and set out to formalize it. Fortunately he was able to figure out an additional `compat` condition (compatibility with the bijections `F i⁺ ≃ F i × X i` in the `X` component) that guarantees uniqueness (`unique_pEquivOn`) and hence gluability (well-definedness): see `pEquivOnGlue`. Instead of just a family of natural families, we actually construct a family of the stronger `PEquivOn`s that bundles the `compat` condition, in order for the inductive argument to work. It is possible to circumvent the introduction of the `compat` condition using Zorn's lemma; if there is a chain of natural families (i.e. for any two families in the chain, one is an extension of the other) over lower sets (which are all of the form `Iic`, `Iio`, or `univ`), we can clearly take the union to get a natural family that extends them all. If a maximal natural family has domain `Iic i` or `Iio i` (`i` a limit), we already know how to extend it one step further to `Iic i⁺` or `Iic i` respectively, so it must be the case that the domain is everything. However, the author chose the `compat` approach in the end because it constructs the distinguished bijection that is compatible with the projections to all `X i`. -/ open Order Set variable {ι : Type*} [Preorder ι] {F₁ F₂ F X : ι → Type*} variable (F) in /-- A directed system is a functor from a category (directed poset) to another category. -/ class DirectedSystem (f : ∀ ⦃i j⦄, i ≤ j → F i → F j) : Prop where map_self ⦃i⦄ (x : F i) : f le_rfl x = x map_map ⦃k j i⦄ (hij : i ≤ j) (hjk : j ≤ k) (x : F i) : f hjk (f hij x) = f (hij.trans hjk) x section DirectedSystem variable {T₁ : ∀ ⦃i j : ι⦄, i ≤ j → Sort*} (f₁ : ∀ i j (h : i ≤ j), T₁ h) variable [∀ ⦃i j⦄ (h : i ≤ j), FunLike (T₁ h) (F₁ i) (F₁ j)] [DirectedSystem F₁ (f₁ · · ·)] variable {T₂ : ∀ ⦃i j : ι⦄, i ≤ j → Sort*} (f₂ : ∀ i j (h : i ≤ j), T₂ h) variable [∀ ⦃i j⦄ (h : i ≤ j), FunLike (T₂ h) (F₂ i) (F₂ j)] [DirectedSystem F₂ (f₂ · · ·)] variable {T : ∀ ⦃i j : ι⦄, i ≤ j → Sort*} (f : ∀ i j (h : i ≤ j), T h) variable [∀ ⦃i j⦄ (h : i ≤ j), FunLike (T h) (F i) (F j)] [DirectedSystem F (f · · ·)] /-- A copy of `DirectedSystem.map_self` specialized to FunLike, as otherwise the `fun i j h ↦ f i j h` can confuse the simplifier. -/ theorem DirectedSystem.map_self' ⦃i⦄ (x) : f i i le_rfl x = x := DirectedSystem.map_self (f := (f · · ·)) x /-- A copy of `DirectedSystem.map_map` specialized to FunLike, as otherwise the `fun i j h ↦ f i j h` can confuse the simplifier. -/ theorem DirectedSystem.map_map' ⦃i j k⦄ (hij hjk x) : f j k hjk (f i j hij x) = f i k (hij.trans hjk) x := DirectedSystem.map_map (f := (f · · ·)) hij hjk x namespace DirectLimit open DirectedSystem variable [IsDirected ι (· ≤ ·)] /-- The setoid on the sigma type defining the direct limit. -/ def setoid : Setoid (Σ i, F i) where r x y := ∃ᵉ (i) (hx : x.1 ≤ i) (hy : y.1 ≤ i), f _ _ hx x.2 = f _ _ hy y.2 iseqv := ⟨fun x ↦ ⟨x.1, le_rfl, le_rfl, rfl⟩, fun ⟨i, hx, hy, eq⟩ ↦ ⟨i, hy, hx, eq.symm⟩, fun ⟨j, hx, _, jeq⟩ ⟨k, _, hz, keq⟩ ↦ have ⟨i, hji, hki⟩ := exists_ge_ge j k ⟨i, hx.trans hji, hz.trans hki, by rw [← map_map' _ hx hji, ← map_map' _ hz hki, jeq, ← keq, map_map', map_map']⟩⟩ theorem r_of_le (x : Σ i, F i) (i : ι) (h : x.1 ≤ i) : (setoid f).r x ⟨i, f _ _ h x.2⟩ := ⟨i, h, le_rfl, (map_map' _ _ _ _).symm⟩ variable (F) in /-- The direct limit of a directed system. -/ abbrev _root_.DirectLimit : Type _ := Quotient (setoid f) variable {f} in theorem eq_of_le (x : Σ i, F i) (i : ι) (h : x.1 ≤ i) : (⟦x⟧ : DirectLimit F f) = ⟦⟨i, f _ _ h x.2⟩⟧ := Quotient.sound (r_of_le _ x i h) @[elab_as_elim] protected theorem induction {C : DirectLimit F f → Prop} (ih : ∀ i x, C ⟦⟨i, x⟩⟧) (x : DirectLimit F f) : C x := Quotient.ind (fun _ ↦ ih _ _) x theorem exists_eq_mk (z : DirectLimit F f) : ∃ i x, z = ⟦⟨i, x⟩⟧ := by rcases z; exact ⟨_, _, rfl⟩ theorem exists_eq_mk₂ (z w : DirectLimit F f) : ∃ i x y, z = ⟦⟨i, x⟩⟧ ∧ w = ⟦⟨i, y⟩⟧ := z.inductionOn₂ w fun x y ↦ have ⟨i, hxi, hyi⟩ := exists_ge_ge x.1 y.1 ⟨i, _, _, eq_of_le x i hxi, eq_of_le y i hyi⟩ theorem exists_eq_mk₃ (w u v : DirectLimit F f) : ∃ i x y z, w = ⟦⟨i, x⟩⟧ ∧ u = ⟦⟨i, y⟩⟧ ∧ v = ⟦⟨i, z⟩⟧ := w.inductionOn₃ u v fun x y z ↦ have ⟨i, hxi, hyi, hzi⟩ := directed_of₃ (· ≤ ·) x.1 y.1 z.1 ⟨i, _, _, _, eq_of_le x i hxi, eq_of_le y i hyi, eq_of_le z i hzi⟩ @[elab_as_elim] protected theorem induction₂ {C : DirectLimit F f → DirectLimit F f → Prop} (ih : ∀ i x y, C ⟦⟨i, x⟩⟧ ⟦⟨i, y⟩⟧) (x y : DirectLimit F f) : C x y := by obtain ⟨_, _, _, rfl, rfl⟩ := exists_eq_mk₂ f x y; apply ih @[elab_as_elim] protected theorem induction₃ {C : DirectLimit F f → DirectLimit F f → DirectLimit F f → Prop} (ih : ∀ i x y z, C ⟦⟨i, x⟩⟧ ⟦⟨i, y⟩⟧ ⟦⟨i, z⟩⟧) (x y z : DirectLimit F f) : C x y z := by obtain ⟨_, _, _, _, rfl, rfl, rfl⟩ := exists_eq_mk₃ f x y z; apply ih theorem mk_injective (h : ∀ i j hij, Function.Injective (f i j hij)) (i) : Function.Injective fun x ↦ (⟦⟨i, x⟩⟧ : DirectLimit F f) := fun _ _ eq ↦ have ⟨_, _, _, eq⟩ := Quotient.eq.mp eq; h _ _ _ eq section map₀ variable [Nonempty ι] (ih : ∀ i, F i) /-- "Nullary map" to construct an element in the direct limit. -/ noncomputable def map₀ : DirectLimit F f := ⟦⟨Classical.arbitrary ι, ih _⟩⟧ theorem map₀_def (compat : ∀ i j h, f i j h (ih i) = ih j) (i) : map₀ f ih = ⟦⟨i, ih i⟩⟧ := have ⟨j, hcj, hij⟩ := exists_ge_ge (Classical.arbitrary ι) i Quotient.sound ⟨j, hcj, hij, (compat ..).trans (compat ..).symm⟩ end map₀ section lift variable {C : Sort*} (ih : ∀ i, F i → C) (compat : ∀ i j h x, ih i x = ih j (f i j h x)) /-- To define a function from the direct limit, it suffices to provide one function from each component subject to a compatibility condition. -/ protected def lift (z : DirectLimit F f) : C := z.recOn (fun x ↦ ih x.1 x.2) fun x y ⟨k, hxk, hyk, eq⟩ ↦ by simp_rw [eq_rec_constant, compat _ _ hxk, compat _ _ hyk, eq] theorem lift_def (x) : DirectLimit.lift f ih compat ⟦x⟧ = ih x.1 x.2 := rfl theorem lift_injective (h : ∀ i, Function.Injective (ih i)) : Function.Injective (DirectLimit.lift f ih compat) := DirectLimit.induction₂ _ fun i x y eq ↦ by simp_rw [lift_def] at eq; rw [h i eq] end lift section map variable (ih : ∀ i, F₁ i → F₂ i) (compat : ∀ i j h x, f₂ i j h (ih i x) = ih j (f₁ i j h x)) /-- To define a function from the direct limit, it suffices to provide one function from each component subject to a compatibility condition. -/ def map (z : DirectLimit F₁ f₁) : DirectLimit F₂ f₂ := z.lift _ (fun i x ↦ ⟦⟨i, ih i x⟩⟧) fun j k h x ↦ Quotient.sound <| have ⟨i, hji, hki⟩ := exists_ge_ge j k ⟨i, hji, hki, by simp_rw [compat, map_map']⟩ theorem map_def (x) : map f₁ f₂ ih compat ⟦x⟧ = ⟦⟨x.1, ih x.1 x.2⟩⟧ := rfl end map section lift₂ variable {C : Sort*} (ih : ∀ i, F₁ i → F₂ i → C) (compat : ∀ i j h x y, ih i x y = ih j (f₁ i j h x) (f₂ i j h y)) private noncomputable def lift₂Aux (z : Σ i, F₁ i) (w : Σ i, F₂ i) : {x : C // ∀ i (hzi : z.1 ≤ i) (hwi : w.1 ≤ i), x = ih i (f₁ _ _ hzi z.2) (f₂ _ _ hwi w.2)} := by choose j hzj hwj using exists_ge_ge z.1 w.1 refine ⟨ih j (f₁ _ _ hzj z.2) (f₂ _ _ hwj w.2), fun k hzk hwk ↦ ?_⟩ have ⟨i, hji, hki⟩ := exists_ge_ge j k simp_rw [compat _ _ hji, compat _ _ hki, map_map'] /-- To define a binary function from the direct limit, it suffices to provide one binary function from each component subject to a compatibility condition. -/ protected noncomputable def lift₂ (z : DirectLimit F₁ f₁) (w : DirectLimit F₂ f₂) : C := z.hrecOn₂ w (φ := fun _ _ ↦ C) (lift₂Aux f₁ f₂ ih compat · ·) fun _ _ _ _ ⟨j, hx, hyj, jeq⟩ ⟨k, hyk, hz, keq⟩ ↦ heq_of_eq <| by have ⟨i, hji, hki⟩ := exists_ge_ge j k simp_rw [(lift₂Aux ..).2 _ (hx.trans hji) (hyk.trans hki), (lift₂Aux ..).2 _ (hyj.trans hji) (hz.trans hki), ← map_map' _ hx hji, jeq, ← map_map' _ hz hki, ← keq, map_map'] theorem lift₂_def₂ (x : Σ i, F₁ i) (y : Σ i, F₂ i) (i) (hxi : x.1 ≤ i) (hyi : y.1 ≤ i) : DirectLimit.lift₂ f₁ f₂ ih compat ⟦x⟧ ⟦y⟧ = ih i (f₁ _ _ hxi x.2) (f₂ _ _ hyi y.2) := (lift₂Aux _ _ _ compat _ _).2 .. theorem lift₂_def (i x y) : DirectLimit.lift₂ f₁ f₂ ih compat ⟦⟨i, x⟩⟧ ⟦⟨i, y⟩⟧ = ih i x y := by rw [lift₂_def₂ _ _ _ _ _ _ i le_rfl le_rfl, map_self', map_self'] end lift₂ section map₂ variable (ih : ∀ i, F₁ i → F₂ i → F i) (compat : ∀ i j h x y, f i j h (ih i x y) = ih j (f₁ i j h x) (f₂ i j h y)) /-- To define a function from the direct limit, it suffices to provide one function from each component subject to a compatibility condition. -/ noncomputable def map₂ : DirectLimit F₁ f₁ → DirectLimit F₂ f₂ → DirectLimit F f := DirectLimit.lift₂ f₁ f₂ (fun i x y ↦ ⟦⟨i, ih i x y⟩⟧) fun j k h x y ↦ Quotient.sound <| have ⟨i, hji, hki⟩ := exists_ge_ge j k ⟨i, hji, hki, by simp_rw [compat, map_map']⟩ theorem map₂_def₂ (x y) (i) (hxi : x.1 ≤ i) (hyi : y.1 ≤ i) : map₂ f₁ f₂ f ih compat ⟦x⟧ ⟦y⟧ = ⟦⟨i, ih i (f₁ _ _ hxi x.2) (f₂ _ _ hyi y.2)⟩⟧ := lift₂_def₂ .. theorem map₂_def (i x y) : map₂ f₁ f₂ f ih compat ⟦⟨i, x⟩⟧ ⟦⟨i, y⟩⟧ = ⟦⟨i, ih i x y⟩⟧ := lift₂_def .. end map₂ end DirectLimit end DirectedSystem variable (f : ∀ ⦃i j : ι⦄, i ≤ j → F j → F i) ⦃i j : ι⦄ (h : i ≤ j) /-- A inverse system indexed by a preorder is a contravariant functor from the preorder to another category. It is dual to `DirectedSystem`. -/ class InverseSystem : Prop where map_self ⦃i : ι⦄ (x : F i) : f le_rfl x = x map_map ⦃k j i : ι⦄ (hkj : k ≤ j) (hji : j ≤ i) (x : F i) : f hkj (f hji x) = f (hkj.trans hji) x namespace InverseSystem section proj /-- The inverse limit of an inverse system of types. -/ def limit (i : ι) : Set (∀ l : Iio i, F l) := {F | ∀ ⦃j k⦄ (h : j.1 ≤ k.1), f h (F k) = F j} /-- For a family of types `X` indexed by an preorder `ι` and an element `i : ι`, `piLT X i` is the product of all the types indexed by elements below `i`. -/ abbrev piLT (X : ι → Type*) (i : ι) := ∀ l : Iio i, X l /-- The projection from a Pi type to the Pi type over an initial segment of its indexing type. -/ abbrev piLTProj (f : piLT X j) : piLT X i := fun l ↦ f ⟨l, l.2.trans_le h⟩ theorem piLTProj_intro {l : Iio j} {f : piLT X j} (hl : l < i) : f l = piLTProj h f ⟨l, hl⟩ := rfl /-- The predicate that says a family of equivalences between `F j` and `piLT X j` is a natural transformation. -/ def IsNatEquiv {s : Set ι} (equiv : ∀ j : s, F j ≃ piLT X j) : Prop := ∀ ⦃j k⦄ (hj : j ∈ s) (hk : k ∈ s) (h : k ≤ j) (x : F j), equiv ⟨k, hk⟩ (f h x) = piLTProj h (equiv ⟨j, hj⟩ x) variable {ι : Type*} [LinearOrder ι] {X : ι → Type*} {i : ι} (hi : IsSuccPrelimit i) /-- If `i` is a limit in a well-ordered type indexing a family of types, then `piLT X i` is the limit of all `piLT X j` for `j < i`. -/ @[simps apply] noncomputable def piLTLim : piLT X i ≃ limit (piLTProj (X := X)) i where toFun f := ⟨fun j ↦ piLTProj j.2.le f, fun _ _ _ ↦ rfl⟩ invFun f l := let k := hi.mid l.2; f.1 ⟨k, k.2.2⟩ ⟨l, k.2.1⟩ right_inv f := by ext j l set k := hi.mid (l.2.trans j.2) obtain le | le := le_total j ⟨k, k.2.2⟩ exacts [congr_fun (f.2 le) l, (congr_fun (f.2 le) ⟨l, _⟩).symm] theorem piLTLim_symm_apply {f} (k : Iio i) {l : Iio i} (hl : l.1 < k.1) : (piLTLim (X := X) hi).symm f l = f.1 k ⟨l, hl⟩ := by conv_rhs => rw [← (piLTLim hi).right_inv f] rfl end proj variable {ι : Type*} {F X : ι → Type*} {i : ι} section variable [PartialOrder ι] [DecidableEq ι] /-- Splitting off the `X i` factor from the Pi type over `{j | j ≤ i}`. -/ def piSplitLE : piLT X i × X i ≃ ∀ j : Iic i, X j where toFun f j := if h : j = i then h.symm ▸ f.2 else f.1 ⟨j, j.2.lt_of_ne h⟩ invFun f := (fun j ↦ f ⟨j, j.2.le⟩, f ⟨i, le_rfl⟩) left_inv f := by ext j; exacts [dif_neg j.2.ne, dif_pos rfl] right_inv f := by grind @[simp] theorem piSplitLE_eq {f : piLT X i × X i} : piSplitLE f ⟨i, le_rfl⟩ = f.2 := by simp [piSplitLE] theorem piSplitLE_lt {f : piLT X i × X i} {j} (hj : j < i) : piSplitLE f ⟨j, hj.le⟩ = f.1 ⟨j, hj⟩ := dif_neg hj.ne end variable [LinearOrder ι] {f : ∀ ⦃i j : ι⦄, i ≤ j → F j → F i} local postfix:max "⁺" => succ -- Note: conflicts with `PosPart` notation section Succ variable [SuccOrder ι] variable (equiv : ∀ j : Iic i, F j ≃ piLT X j) (e : F i⁺ ≃ F i × X i) (hi : ¬ IsMax i) /-- Extend a family of bijections to `piLT` by one step. -/ def piEquivSucc : ∀ j : Iic i⁺, F j ≃ piLT X j := piSplitLE (X := fun i ↦ F i ≃ piLT X i) (fun j ↦ equiv ⟨j, (lt_succ_iff_of_not_isMax hi).mp j.2⟩, e.trans <| ((equiv ⟨i, le_rfl⟩).prodCongr <| Equiv.refl _).trans <| piSplitLE.trans <| Equiv.piCongrSet <| Set.ext fun _ ↦ (lt_succ_iff_of_not_isMax hi).symm) theorem piEquivSucc_self {x} : piEquivSucc equiv e hi ⟨_, le_rfl⟩ x ⟨i, lt_succ_of_not_isMax hi⟩ = (e x).2 := by simp [piEquivSucc] variable {equiv e} theorem isNatEquiv_piEquivSucc [InverseSystem f] (H : ∀ x, (e x).1 = f (le_succ i) x) (nat : IsNatEquiv f equiv) : IsNatEquiv f (piEquivSucc equiv e hi) := fun j k hj hk h x ↦ by have lt_succ {j} := (lt_succ_iff_of_not_isMax (b := j) hi).mpr obtain rfl | hj := le_succ_iff_eq_or_le.mp hj · obtain rfl | hk := le_succ_iff_eq_or_le.mp hk · simp [InverseSystem.map_self] · funext l rw [piEquivSucc, piSplitLE_lt (lt_succ hk), ← InverseSystem.map_map (f := f) hk (le_succ i), ← H, piLTProj, nat le_rfl] simp [piSplitLE_lt (l.2.trans_le hk)] · rw [piEquivSucc, piSplitLE_lt (h.trans_lt <| lt_succ hj), nat hj, piSplitLE_lt (lt_succ hj)] end Succ section Lim variable {equiv : ∀ j : Iio i, F j ≃ piLT X j} (nat : IsNatEquiv f equiv) /-- A natural family of bijections below a limit ordinal induces a bijection at the limit ordinal. -/ @[simps] def invLimEquiv : limit f i ≃ limit (piLTProj (X := X)) i where toFun t := ⟨fun l ↦ equiv l (t.1 l), fun _ _ h ↦ Eq.symm <| by simp_rw [← t.2 h]; apply nat⟩ invFun t := ⟨fun l ↦ (equiv l).symm (t.1 l), fun _ _ h ↦ (Equiv.eq_symm_apply _).mpr <| by rw [nat, ← t.2 h] <;> simp⟩ left_inv t := by ext; apply Equiv.left_inv right_inv t := by ext1; ext1; apply Equiv.right_inv variable (equivLim : F i ≃ limit f i) (hi : IsSuccPrelimit i) /-- Extend a natural family of bijections to a limit ordinal. -/ noncomputable def piEquivLim : ∀ j : Iic i, F j ≃ piLT X j := piSplitLE (X := fun j ↦ F j ≃ piLT X j) (equiv, equivLim.trans <| (invLimEquiv nat).trans (piLTLim hi).symm) variable {equivLim} theorem isNatEquiv_piEquivLim [InverseSystem f] (H : ∀ x l, (equivLim x).1 l = f l.2.le x) : IsNatEquiv f (piEquivLim nat equivLim hi) := fun j k hj hk h t ↦ by obtain rfl | hj := hj.eq_or_lt · obtain rfl | hk := hk.eq_or_lt · simp [InverseSystem.map_self] · funext l simp_rw [piEquivLim, piSplitLE_lt hk, piSplitLE_eq, Equiv.trans_apply] rw [piLTProj, piLTLim_symm_apply hi ⟨k, hk⟩ (by exact l.2), invLimEquiv_apply_coe, H] · rw [piEquivLim, piSplitLE_lt (h.trans_lt hj), piSplitLE_lt hj]; apply nat end Lim section Unique variable [SuccOrder ι] (f) (equivSucc : ∀ ⦃i⦄, ¬IsMax i → F i⁺ ≃ F i × X i) /-- A natural partial family of bijections to `piLT` satisfying a compatibility condition. -/ @[ext] structure PEquivOn (s : Set ι) where /-- A partial family of bijections between `F` and `piLT X` defined on some set in `ι`. -/ equiv (i : s) : F i ≃ piLT X i /-- It is a natural family of bijections. -/ nat : IsNatEquiv f equiv /-- It is compatible with a family of bijections relating `F i⁺` to `F i`. -/ compat {i : ι} (hsi : (i⁺ : ι) ∈ s) (hi : ¬IsMax i) (x) : equiv ⟨i⁺, hsi⟩ x ⟨i, lt_succ_of_not_isMax hi⟩ = (equivSucc hi x).2 variable {s t : Set ι} {f equivSucc} [WellFoundedLT ι] /-- Restrict a partial family of bijections to a smaller set. -/ @[simps] def PEquivOn.restrict (e : PEquivOn f equivSucc t) (h : s ⊆ t) : PEquivOn f equivSucc s where equiv i := e.equiv ⟨i, h i.2⟩ nat _ _ _ _ := e.nat _ _ compat _ := e.compat _ theorem unique_pEquivOn (hs : IsLowerSet s) {e₁ e₂ : PEquivOn f equivSucc s} : e₁ = e₂ := by obtain ⟨e₁, nat₁, compat₁⟩ := e₁ obtain ⟨e₂, nat₂, compat₂⟩ := e₂ ext1; ext1 i; dsimp only refine SuccOrder.prelimitRecOn i.1 (motive := fun i ↦ ∀ h : i ∈ s, e₁ ⟨i, h⟩ = e₂ ⟨i, h⟩) (fun i nmax ih hi ↦ ?_) (fun i lim ih hi ↦ ?_) i.2 · ext x ⟨j, hj⟩ obtain rfl | hj := ((lt_succ_iff_of_not_isMax nmax).mp hj).eq_or_lt · exact (compat₁ _ nmax x).trans (compat₂ _ nmax x).symm have hi : i ∈ s := hs (le_succ i) hi rw [piLTProj_intro (f := e₁ _ x) (le_succ i) (by exact hj), ← nat₁ _ hi (by exact le_succ i), ih, nat₂ _ hi (by exact le_succ i)] · ext x j have ⟨k, hjk, hki⟩ := lim.mid j.2 have hk : k ∈ s := hs hki.le hi rw [piLTProj_intro (f := e₁ _ x) hki.le hjk, piLTProj_intro (f := e₂ _ x) hki.le hjk, ← nat₁ _ hk, ← nat₂ _ hk, ih _ hki] theorem pEquivOn_apply_eq (h : IsLowerSet (s ∩ t)) {e₁ : PEquivOn f equivSucc s} {e₂ : PEquivOn f equivSucc t} {i} {his : i ∈ s} {hit : i ∈ t} : e₁.equiv ⟨i, his⟩ = e₂.equiv ⟨i, hit⟩ := show (e₁.restrict inter_subset_left).equiv ⟨i, his, hit⟩ = (e₂.restrict inter_subset_right).equiv ⟨i, his, hit⟩ from congr_fun (congr_arg _ <| unique_pEquivOn h) _ /-- Extend a partial family of bijections by one step. -/ def pEquivOnSucc [InverseSystem f] (hi : ¬IsMax i) (e : PEquivOn f equivSucc (Iic i)) (H : ∀ ⦃i⦄ (hi : ¬ IsMax i) x, (equivSucc hi x).1 = f (le_succ i) x) : PEquivOn f equivSucc (Iic i⁺) where equiv := piEquivSucc e.equiv (equivSucc hi) hi nat := isNatEquiv_piEquivSucc hi (H hi) e.nat compat hsj hj x := by obtain eq | lt := hsj.eq_or_lt · cases (succ_eq_succ_iff_of_not_isMax hj hi).mp eq; simp [piEquivSucc] · rwa [piEquivSucc, piSplitLE_lt, e.compat] variable (hi : IsSuccPrelimit i) (e : ∀ j : Iio i, PEquivOn f equivSucc (Iic j)) /-- Glue partial families of bijections at a limit ordinal, obtaining a partial family over a right-open interval. -/ noncomputable def pEquivOnGlue : PEquivOn f equivSucc (Iio i) where equiv := (piLTLim (X := fun j ↦ F j ≃ piLT X j) hi).symm ⟨fun j ↦ ((e j).restrict fun _ h ↦ h.le).equiv, fun _ _ h ↦ funext fun _ ↦ pEquivOn_apply_eq ((isLowerSet_Iio _).inter <| isLowerSet_Iio _)⟩ nat j k hj hk h := by rw [piLTLim_symm_apply]; exacts [(e _).nat _ _ _, h.trans_lt (hi.mid _).2.1] compat hj := have k := hi.mid hj by rw [piLTLim_symm_apply hi ⟨_, k.2.2⟩ (by exact k.2.1)]; apply (e _).compat /-- Extend `pEquivOnGlue` by one step, obtaining a partial family over a right-closed interval. -/ noncomputable def pEquivOnLim [InverseSystem f] (equivLim : F i ≃ limit f i) (H : ∀ x l, (equivLim x).1 l = f l.2.le x) : PEquivOn f equivSucc (Iic i) where equiv := piEquivLim (pEquivOnGlue hi e).nat equivLim hi nat := isNatEquiv_piEquivLim (pEquivOnGlue hi e).nat hi H compat hsj hj x := by rw [piEquivLim, piSplitLE_lt (hi.succ_lt <| (succ_le_iff_of_not_isMax hj).mp hsj)] apply (pEquivOnGlue hi e).compat end Unique variable [WellFoundedLT ι] [SuccOrder ι] [InverseSystem f] (equivSucc : ∀ i, ¬IsMax i → {e : F i⁺ ≃ F i × X i // ∀ x, (e x).1 = f (le_succ i) x}) (equivLim : ∀ i, IsSuccPrelimit i → {e : F i ≃ limit f i // ∀ x l, (e x).1 l = f l.2.le x}) private noncomputable def globalEquivAux (i : ι) : PEquivOn f (fun i hi ↦ (equivSucc i hi).1) (Iic i) := SuccOrder.prelimitRecOn i (fun _ hi e ↦ pEquivOnSucc hi e fun i hi ↦ (equivSucc i hi).2) fun i hi e ↦ pEquivOnLim hi (fun j ↦ e j j.2) (equivLim i hi).1 (equivLim i hi).2 /-- Over a well-ordered type, construct a family of bijections by transfinite recursion. -/ noncomputable def globalEquiv (i : ι) : F i ≃ piLT X i := (globalEquivAux equivSucc equivLim i).equiv ⟨i, le_rfl⟩ theorem globalEquiv_naturality ⦃i j⦄ (h : i ≤ j) (x : F j) : letI e := globalEquiv equivSucc equivLim e i (f h x) = piLTProj h (e j x) := by refine (DFunLike.congr_fun ?_ _).trans ((globalEquivAux equivSucc equivLim j).nat le_rfl h h x) exact pEquivOn_apply_eq ((isLowerSet_Iic _).inter <| isLowerSet_Iic _) theorem globalEquiv_compatibility ⦃i⦄ (hi : ¬IsMax i) (x) : globalEquiv equivSucc equivLim i⁺ x ⟨i, lt_succ_of_not_isMax hi⟩ = ((equivSucc i hi).1 x).2 := (globalEquivAux equivSucc equivLim i⁺).compat le_rfl hi x end InverseSystem
.lake/packages/mathlib/Mathlib/Order/RelSeries.lean
import Mathlib.Algebra.GroupWithZero.Nat import Mathlib.Algebra.Order.Group.Nat import Mathlib.Algebra.Order.Monoid.NatCast import Mathlib.Data.Fin.VecNotation import Mathlib.Data.Fintype.Pi import Mathlib.Data.Fintype.Pigeonhole import Mathlib.Data.Fintype.Sigma import Mathlib.Data.Rel import Mathlib.Order.OrderIsoNat /-! # Series of a relation If `r` is a relation on `α` then a relation series of length `n` is a series `a_0, a_1, ..., a_n` such that `r a_i a_{i+1}` for all `i < n` -/ open scoped SetRel variable {α : Type*} (r : SetRel α α) variable {β : Type*} (s : SetRel β β) /-- Let `r` be a relation on `α`, a relation series of `r` of length `n` is a series `a_0, a_1, ..., a_n` such that `r a_i a_{i+1}` for all `i < n` -/ structure RelSeries where /-- The number of inequalities in the series -/ length : ℕ /-- The underlying function of a relation series -/ toFun : Fin (length + 1) → α /-- Adjacent elements are related -/ step : ∀ (i : Fin length), toFun (Fin.castSucc i) ~[r] toFun i.succ namespace RelSeries instance : CoeFun (RelSeries r) (fun x ↦ Fin (x.length + 1) → α) := { coe := RelSeries.toFun } /-- For any type `α`, each term of `α` gives a relation series with the right most index to be 0. -/ @[simps!] def singleton (a : α) : RelSeries r where length := 0 toFun _ := a step := Fin.elim0 instance [IsEmpty α] : IsEmpty (RelSeries r) where false x := IsEmpty.false (x 0) instance [Inhabited α] : Inhabited (RelSeries r) where default := singleton r default instance [Nonempty α] : Nonempty (RelSeries r) := Nonempty.map (singleton r) inferInstance variable {r} @[ext (iff := false)] lemma ext {x y : RelSeries r} (length_eq : x.length = y.length) (toFun_eq : x.toFun = y.toFun ∘ Fin.cast (by rw [length_eq])) : x = y := by rcases x with ⟨nx, fx⟩ dsimp only at length_eq subst length_eq simp_all lemma rel_of_lt [r.IsTrans] (x : RelSeries r) {i j : Fin (x.length + 1)} (h : i < j) : x i ~[r] x j := (Fin.liftFun_iff_succ (· ~[r] ·)).mpr x.step h lemma rel_or_eq_of_le [r.IsTrans] (x : RelSeries r) {i j : Fin (x.length + 1)} (h : i ≤ j) : x i ~[r] x j ∨ x i = x j := (Fin.lt_or_eq_of_le h).imp (x.rel_of_lt ·) (by rw [·]) /-- Given two relations `r, s` on `α` such that `r ≤ s`, any relation series of `r` induces a relation series of `s` -/ @[simps!] def ofLE (x : RelSeries r) {s : SetRel α α} (h : r ≤ s) : RelSeries s where length := x.length toFun := x step _ := h <| x.step _ lemma coe_ofLE (x : RelSeries r) {s : SetRel α α} (h : r ≤ s) : (x.ofLE h : _ → _) = x := rfl /-- Every relation series gives a list -/ def toList (x : RelSeries r) : List α := List.ofFn x @[simp] lemma length_toList (x : RelSeries r) : x.toList.length = x.length + 1 := List.length_ofFn @[simp] lemma toList_singleton (x : α) : (singleton r x).toList = [x] := rfl lemma isChain_toList (x : RelSeries r) : x.toList.IsChain (· ~[r] ·) := by rw [List.isChain_iff_get] intro i h convert x.step ⟨i, by simpa [toList] using h⟩ <;> apply List.get_ofFn @[deprecated (since := "2025-09-24")] alias toList_chain' := isChain_toList lemma toList_ne_nil (x : RelSeries r) : x.toList ≠ [] := fun m => List.eq_nil_iff_forall_not_mem.mp m (x 0) <| List.mem_ofFn.mpr ⟨_, rfl⟩ /-- Every nonempty list satisfying the chain condition gives a relation series -/ @[simps] def fromListIsChain (x : List α) (x_ne_nil : x ≠ []) (hx : x.IsChain (· ~[r] ·)) : RelSeries r where length := x.length - 1 toFun i := x[Fin.cast (Nat.succ_pred_eq_of_pos <| List.length_pos_iff.mpr x_ne_nil) i] step i := List.isChain_iff_get.mp hx i _ @[deprecated (since := "2025-09-24")] alias fromListChain' := fromListIsChain /-- Relation series of `r` and nonempty list of `α` satisfying `r`-chain condition bijectively corresponds to each other. -/ protected def Equiv : RelSeries r ≃ {x : List α | x ≠ [] ∧ x.IsChain (· ~[r] ·)} where toFun x := ⟨_, x.toList_ne_nil, x.isChain_toList⟩ invFun x := fromListIsChain _ x.2.1 x.2.2 left_inv x := ext (by simp [toList]) <| by ext; dsimp; apply List.get_ofFn right_inv x := by refine Subtype.ext (List.ext_get ?_ fun n hn1 _ => by dsimp; apply List.get_ofFn) have := Nat.succ_pred_eq_of_pos <| List.length_pos_iff.mpr x.2.1 simp_all [toList] lemma toList_injective : Function.Injective (RelSeries.toList (r := r)) := fun _ _ h ↦ (RelSeries.Equiv).injective <| Subtype.ext h -- TODO : build a similar bijection between `RelSeries α` and `Quiver.Path` end RelSeries namespace SetRel /-- A relation `r` is said to be finite dimensional iff there is a relation series of `r` with the maximum length. -/ @[mk_iff] class FiniteDimensional : Prop where /-- A relation `r` is said to be finite dimensional iff there is a relation series of `r` with the maximum length. -/ exists_longest_relSeries : ∃ x : RelSeries r, ∀ y : RelSeries r, y.length ≤ x.length /-- A relation `r` is said to be infinite dimensional iff there exists relation series of arbitrary length. -/ @[mk_iff] class InfiniteDimensional : Prop where /-- A relation `r` is said to be infinite dimensional iff there exists relation series of arbitrary length. -/ exists_relSeries_with_length : ∀ n : ℕ, ∃ x : RelSeries r, x.length = n end SetRel namespace RelSeries /-- The longest relational series when a relation is finite dimensional -/ protected noncomputable def longestOf [r.FiniteDimensional] : RelSeries r := SetRel.FiniteDimensional.exists_longest_relSeries.choose lemma length_le_length_longestOf [r.FiniteDimensional] (x : RelSeries r) : x.length ≤ (RelSeries.longestOf r).length := SetRel.FiniteDimensional.exists_longest_relSeries.choose_spec _ /-- A relation series with length `n` if the relation is infinite dimensional -/ protected noncomputable def withLength [r.InfiniteDimensional] (n : ℕ) : RelSeries r := (SetRel.InfiniteDimensional.exists_relSeries_with_length n).choose @[simp] lemma length_withLength [r.InfiniteDimensional] (n : ℕ) : (RelSeries.withLength r n).length = n := (SetRel.InfiniteDimensional.exists_relSeries_with_length n).choose_spec section variable {r} {s : RelSeries r} {x : α} /-- If a relation on `α` is infinite dimensional, then `α` is nonempty. -/ lemma nonempty_of_infiniteDimensional [r.InfiniteDimensional] : Nonempty α := ⟨RelSeries.withLength r 0 0⟩ lemma nonempty_of_finiteDimensional [r.FiniteDimensional] : Nonempty α := by obtain ⟨p, _⟩ := (r.finiteDimensional_iff).mp ‹_› exact ⟨p 0⟩ instance membership : Membership α (RelSeries r) := ⟨Function.swap (· ∈ Set.range ·)⟩ theorem mem_def : x ∈ s ↔ x ∈ Set.range s := Iff.rfl @[simp] theorem mem_toList : x ∈ s.toList ↔ x ∈ s := by rw [RelSeries.toList, List.mem_ofFn', RelSeries.mem_def] theorem subsingleton_of_length_eq_zero (hs : s.length = 0) : {x | x ∈ s}.Subsingleton := by rintro - ⟨i, rfl⟩ - ⟨j, rfl⟩ congr! exact finCongr (by rw [hs, zero_add]) |>.injective <| Subsingleton.elim (α := Fin 1) _ _ theorem length_ne_zero_of_nontrivial (h : {x | x ∈ s}.Nontrivial) : s.length ≠ 0 := fun hs ↦ h.not_subsingleton <| subsingleton_of_length_eq_zero hs theorem length_pos_of_nontrivial (h : {x | x ∈ s}.Nontrivial) : 0 < s.length := Nat.pos_iff_ne_zero.mpr <| length_ne_zero_of_nontrivial h theorem length_ne_zero [r.IsIrrefl] : s.length ≠ 0 ↔ {x | x ∈ s}.Nontrivial := by refine ⟨fun h ↦ ⟨s 0, by simp [mem_def], s 1, by simp [mem_def], fun rid ↦ r.irrefl (s 0) ?_⟩, length_ne_zero_of_nontrivial⟩ nth_rw 2 [rid] convert s.step ⟨0, by cutsat⟩ ext simpa [Nat.pos_iff_ne_zero] theorem length_pos [r.IsIrrefl] : 0 < s.length ↔ {x | x ∈ s}.Nontrivial := Nat.pos_iff_ne_zero.trans length_ne_zero lemma length_eq_zero [r.IsIrrefl] : s.length = 0 ↔ {x | x ∈ s}.Subsingleton := by rw [← not_ne_iff, length_ne_zero, Set.not_nontrivial_iff] /-- Start of a series, i.e. for `a₀ -r→ a₁ -r→ ... -r→ aₙ`, its head is `a₀`. Since a relation series is assumed to be non-empty, this is well defined. -/ def head (x : RelSeries r) : α := x 0 /-- End of a series, i.e. for `a₀ -r→ a₁ -r→ ... -r→ aₙ`, its last element is `aₙ`. Since a relation series is assumed to be non-empty, this is well defined. -/ def last (x : RelSeries r) : α := x <| Fin.last _ lemma apply_zero (p : RelSeries r) : p 0 = p.head := rfl lemma apply_last (x : RelSeries r) : x (Fin.last <| x.length) = x.last := rfl lemma head_mem (x : RelSeries r) : x.head ∈ x := ⟨_, rfl⟩ lemma last_mem (x : RelSeries r) : x.last ∈ x := ⟨_, rfl⟩ @[simp] lemma head_singleton {r : SetRel α α} (x : α) : (singleton r x).head = x := by simp [singleton, head] @[simp] lemma last_singleton {r : SetRel α α} (x : α) : (singleton r x).last = x := by simp [singleton, last] @[simp] lemma head_toList (p : RelSeries r) : p.toList.head p.toList_ne_nil = p.head := by simp [toList, apply_zero] @[simp] lemma toList_getElem_eq_apply (p : RelSeries r) (i : Fin (p.length + 1)) : p.toList[(i : ℕ)] = p i := by simp only [toList, List.getElem_ofFn] lemma toList_getElem_eq_apply_of_lt_length {p : RelSeries r} {i : ℕ} (hi : i < p.length + 1) : p.toList[i]'(by simpa using hi) = p ⟨i, hi⟩ := p.toList_getElem_eq_apply ⟨i, hi⟩ @[simp] lemma toList_getElem_zero_eq_head (p : RelSeries r) : p.toList[0] = p.head := p.toList_getElem_eq_apply_of_lt_length (by simp) @[simp] lemma toList_fromListIsChain (l : List α) (l_ne_nil : l ≠ []) (hl : l.IsChain (· ~[r] ·)) : (fromListIsChain l l_ne_nil hl).toList = l := Subtype.ext_iff.mp <| RelSeries.Equiv.right_inv ⟨l, ⟨l_ne_nil, hl⟩⟩ @[simp] lemma head_fromListIsChain (l : List α) (l_ne_nil : l ≠ []) (hl : l.IsChain (· ~[r] ·)) : (fromListIsChain l l_ne_nil hl).head = l.head l_ne_nil := by simp [← apply_zero, List.getElem_zero_eq_head] @[deprecated (since := "2025-09-24")] alias toList_fromListChain' := toList_fromListIsChain @[deprecated (since := "2025-09-24")] alias head_fromListChain' := head_fromListIsChain @[simp] lemma getLast_toList (p : RelSeries r) : p.toList.getLast (by simp [toList]) = p.last := by simp [last, ← toList_getElem_eq_apply, List.getLast_eq_getElem] end variable {r s} /-- If `a₀ -r→ a₁ -r→ ... -r→ aₙ` and `b₀ -r→ b₁ -r→ ... -r→ bₘ` are two strict series such that `r aₙ b₀`, then there is a chain of length `n + m + 1` given by `a₀ -r→ a₁ -r→ ... -r→ aₙ -r→ b₀ -r→ b₁ -r→ ... -r→ bₘ`. -/ @[simps length] def append (p q : RelSeries r) (connect : p.last ~[r] q.head) : RelSeries r where length := p.length + q.length + 1 toFun := Fin.append p q ∘ Fin.cast (by omega) step i := by obtain hi | rfl | hi := lt_trichotomy i (Fin.castLE (by omega) (Fin.last _ : Fin (p.length + 1))) · convert p.step ⟨i.1, hi⟩ <;> convert Fin.append_left p q _ <;> rfl · convert connect · convert Fin.append_left p q _ · convert Fin.append_right p q _; rfl · set x := _; set y := _ change Fin.append p q x ~[r] Fin.append p q y have hx : x = Fin.natAdd _ ⟨i - (p.length + 1), Nat.sub_lt_left_of_lt_add hi <| i.2.trans <| by omega⟩ := by ext; dsimp [x, y]; rw [Nat.add_sub_cancel']; exact hi have hy : y = Fin.natAdd _ ⟨i - p.length, Nat.sub_lt_left_of_lt_add (le_of_lt hi) (by exact i.2)⟩ := by ext dsimp conv_rhs => rw [Nat.add_comm p.length 1, add_assoc, Nat.add_sub_cancel' <| le_of_lt (show p.length < i.1 from hi), add_comm] rfl rw [hx, Fin.append_right, hy, Fin.append_right] convert q.step ⟨i - (p.length + 1), Nat.sub_lt_left_of_lt_add hi <| by omega⟩ rw [Fin.succ_mk, Nat.sub_eq_iff_eq_add (le_of_lt hi : p.length ≤ i), Nat.add_assoc _ 1, add_comm 1, Nat.sub_add_cancel] exact hi lemma append_apply_left (p q : RelSeries r) (connect : p.last ~[r] q.head) (i : Fin (p.length + 1)) : p.append q connect ((i.castAdd (q.length + 1)).cast (by dsimp; cutsat) : Fin ((p.append q connect).length + 1)) = p i := by delta append simp only [Function.comp_apply] convert Fin.append_left _ _ _ lemma append_apply_right (p q : RelSeries r) (connect : p.last ~[r] q.head) (i : Fin (q.length + 1)) : p.append q connect ((i.natAdd (p.length + 1)).cast (by dsimp; cutsat) : Fin ((p.append q connect).length + 1)) = q i := Fin.append_right _ _ _ @[simp] lemma head_append (p q : RelSeries r) (connect : p.last ~[r] q.head) : (p.append q connect).head = p.head := append_apply_left p q connect 0 @[simp] lemma last_append (p q : RelSeries r) (connect : p.last ~[r] q.head) : (p.append q connect).last = q.last := by delta last convert append_apply_right p q connect (Fin.last _) ext1 dsimp omega lemma append_assoc (p q w : RelSeries r) (hpq : p.last ~[r] q.head) (hqw : q.last ~[r] w.head) : (p.append q hpq).append w (by simpa) = p.append (q.append w hqw) (by simpa) := by ext · simp only [append_length, Nat.add_left_inj] cutsat · simp [append, Fin.append_assoc] @[simp] lemma toList_append (p q : RelSeries r) (connect : p.last ~[r] q.head) : (p.append q connect).toList = p.toList ++ q.toList := by apply List.ext_getElem · simp cutsat · intro i h1 h2 have h3' : i < p.length + 1 + (q.length + 1) := by simp_all rw [toList_getElem_eq_apply_of_lt_length (by simp; cutsat)] · simp only [append, Function.comp_apply, Fin.cast_mk, List.getElem_append] split · have : Fin.mk i h3' = Fin.castAdd _ ⟨i, by simp_all⟩ := rfl rw [this, Fin.append_left, toList_getElem_eq_apply_of_lt_length] · simp_all only [length_toList] have : Fin.mk i h3' = Fin.natAdd _ ⟨i - p.length - 1, by omega⟩ := by simp_all; cutsat rw [this, Fin.append_right, toList_getElem_eq_apply_of_lt_length] rfl /-- For two types `α, β` and relation on them `r, s`, if `f : α → β` preserves relation `r`, then an `r`-series can be pushed out to an `s`-series by `a₀ -r→ a₁ -r→ ... -r→ aₙ ↦ f a₀ -s→ f a₁ -s→ ... -s→ f aₙ` -/ @[simps length] def map (p : RelSeries r) (f : r.Hom s) : RelSeries s where length := p.length toFun := f.1.comp p step := (f.2 <| p.step ·) @[simp] lemma map_apply (p : RelSeries r) (f : r.Hom s) (i : Fin (p.length + 1)) : p.map f i = f (p i) := rfl @[simp] lemma head_map (p : RelSeries r) (f : r.Hom s) : (p.map f).head = f p.head := rfl @[simp] lemma last_map (p : RelSeries r) (f : r.Hom s) : (p.map f).last = f p.last := rfl /-- If `a₀ -r→ a₁ -r→ ... -r→ aₙ` is an `r`-series and `a` is such that `aᵢ -r→ a -r→ a_ᵢ₊₁`, then `a₀ -r→ a₁ -r→ ... -r→ aᵢ -r→ a -r→ aᵢ₊₁ -r→ ... -r→ aₙ` is another `r`-series -/ @[simps] def insertNth (p : RelSeries r) (i : Fin p.length) (a : α) (prev_connect : p (Fin.castSucc i) ~[r] a) (connect_next : a ~[r] p i.succ) : RelSeries r where length := p.length + 1 toFun := (Fin.castSucc i.succ).insertNth a p step m := by set x := _; set y := _; change x ~[r] y obtain hm | hm | hm := lt_trichotomy m.1 i.1 · convert p.step ⟨m, hm.trans i.2⟩ · change Fin.insertNth _ _ _ _ = _ rw [Fin.insertNth_apply_below] pick_goal 2 · exact hm.trans (lt_add_one _) simp · change Fin.insertNth _ _ _ _ = _ rw [Fin.insertNth_apply_below] pick_goal 2 · change m.1 + 1 < i.1 + 1; rwa [add_lt_add_iff_right] simp; rfl · rw [show x = p m from show Fin.insertNth _ _ _ _ = _ by rw [Fin.insertNth_apply_below] pick_goal 2 · change m.1 < i.1 + 1; exact hm ▸ lt_add_one _ simp] convert prev_connect · ext; exact hm · change Fin.insertNth _ _ _ _ = _ rw [show m.succ = i.succ.castSucc by ext; change _ + 1 = _ + 1; rw [hm], Fin.insertNth_apply_same] · rw [Nat.lt_iff_add_one_le, le_iff_lt_or_eq] at hm obtain hm | hm := hm · convert p.step ⟨m.1 - 1, Nat.sub_lt_right_of_lt_add (by omega) m.2⟩ · change Fin.insertNth _ _ _ _ = _ rw [Fin.insertNth_apply_above (h := hm)] aesop · change Fin.insertNth _ _ _ _ = _ rw [Fin.insertNth_apply_above] swap · exact hm.trans (lt_add_one _) simp only [Fin.pred_succ, eq_rec_constant, Fin.succ_mk] congr exact Fin.ext <| Eq.symm <| Nat.succ_pred_eq_of_pos (lt_trans (Nat.zero_lt_succ _) hm) · convert connect_next · change Fin.insertNth _ _ _ _ = _ rw [show m.castSucc = i.succ.castSucc from Fin.ext hm.symm, Fin.insertNth_apply_same] · change Fin.insertNth _ _ _ _ = _ rw [Fin.insertNth_apply_above] swap · change i.1 + 1 < m.1 + 1; omega simp only [Fin.pred_succ, eq_rec_constant] congr; ext; exact hm.symm /-- A relation series `a₀ -r→ a₁ -r→ ... -r→ aₙ` of `r` gives a relation series of the reverse of `r` by reversing the series `aₙ ←r- aₙ₋₁ ←r- ... ←r- a₁ ←r- a₀`. -/ @[simps length] def reverse (p : RelSeries r) : RelSeries r.inv where length := p.length toFun := p ∘ Fin.rev step i := by rw [Function.comp_apply, Function.comp_apply, SetRel.mem_inv] have hi : i.1 + 1 ≤ p.length := by omega convert p.step ⟨p.length - (i.1 + 1), Nat.sub_lt_self (by omega) hi⟩ · ext; simp · ext simp only [Fin.val_rev, Fin.coe_castSucc, Fin.val_succ] omega @[simp] lemma reverse_apply (p : RelSeries r) (i : Fin (p.length + 1)) : p.reverse i = p i.rev := rfl @[simp] lemma last_reverse (p : RelSeries r) : p.reverse.last = p.head := by simp [RelSeries.last, RelSeries.head] @[simp] lemma head_reverse (p : RelSeries r) : p.reverse.head = p.last := by simp [RelSeries.last, RelSeries.head] @[simp] lemma reverse_reverse {r : SetRel α α} (p : RelSeries r) : p.reverse.reverse = p := by ext <;> simp /-- Given a series `a₀ -r→ a₁ -r→ ... -r→ aₙ` and an `a` such that `a₀ -r→ a` holds, there is a series of length `n+1`: `a -r→ a₀ -r→ a₁ -r→ ... -r→ aₙ`. -/ @[simps! length] def cons (p : RelSeries r) (newHead : α) (rel : newHead ~[r] p.head) : RelSeries r := (singleton r newHead).append p rel @[simp] lemma head_cons (p : RelSeries r) (newHead : α) (rel : newHead ~[r] p.head) : (p.cons newHead rel).head = newHead := rfl @[simp] lemma last_cons (p : RelSeries r) (newHead : α) (rel : newHead ~[r] p.head) : (p.cons newHead rel).last = p.last := by delta cons rw [last_append] lemma cons_cast_succ (s : RelSeries r) (a : α) (h : a ~[r] s.head) (i : Fin (s.length + 1)) : (s.cons a h) (.cast (by simp) (.succ i)) = s i := by dsimp [cons] convert append_apply_right (singleton r a) s h i ext1 dsimp omega @[simp] lemma append_singleton_left (p : RelSeries r) (x : α) (hx : x ~[r] p.head) : (singleton r x).append p hx = p.cons x hx := rfl @[simp] lemma toList_cons (p : RelSeries r) (x : α) (hx : x ~[r] p.head) : (p.cons x hx).toList = x :: p.toList := by rw [cons, toList_append] simp lemma fromListIsChain_cons (l : List α) (l_ne_nil : l ≠ []) (hl : l.IsChain (· ~[r] ·)) (x : α) (hx : x ~[r] l.head l_ne_nil) : fromListIsChain (x :: l) (by simp) (hl.cons_of_ne_nil l_ne_nil hx) = (fromListIsChain l l_ne_nil hl).cons x (by simpa) := by apply toList_injective simp @[deprecated (since := "2025-09-24")] alias fromListChain'_cons := fromListIsChain_cons lemma append_cons {p q : RelSeries r} {x : α} (hx : x ~[r] p.head) (hq : p.last ~[r] q.head) : (p.cons x hx).append q (by simpa) = (p.append q hq).cons x (by simpa) := by simp only [cons] rw [append_assoc] /-- Given a series `a₀ -r→ a₁ -r→ ... -r→ aₙ` and an `a` such that `aₙ -r→ a` holds, there is a series of length `n+1`: `a₀ -r→ a₁ -r→ ... -r→ aₙ -r→ a`. -/ @[simps! length] def snoc (p : RelSeries r) (newLast : α) (rel : p.last ~[r] newLast) : RelSeries r := p.append (singleton r newLast) rel @[simp] lemma head_snoc (p : RelSeries r) (newLast : α) (rel : p.last ~[r] newLast) : (p.snoc newLast rel).head = p.head := by delta snoc; rw [head_append] @[simp] lemma last_snoc (p : RelSeries r) (newLast : α) (rel : p.last ~[r] newLast) : (p.snoc newLast rel).last = newLast := last_append _ _ _ lemma snoc_cast_castSucc (s : RelSeries r) (a : α) (h : s.last ~[r] a) (i : Fin (s.length + 1)) : (s.snoc a h) (.cast (by simp) (.castSucc i)) = s i := append_apply_left s (singleton r a) h i -- This lemma is useful because `last_snoc` is about `Fin.last (p.snoc _ _).length`, but we often -- see `Fin.last (p.length + 1)` in practice. They are equal by definition, but sometimes simplifier -- does not pick up `last_snoc` @[simp] lemma last_snoc' (p : RelSeries r) (newLast : α) (rel : p.last ~[r] newLast) : p.snoc newLast rel (Fin.last (p.length + 1)) = newLast := last_append _ _ _ @[simp] lemma snoc_castSucc (s : RelSeries r) (a : α) (connect : s.last ~[r] a) (i : Fin (s.length + 1)) : snoc s a connect (Fin.castSucc i) = s i := Fin.append_left _ _ i lemma mem_snoc {p : RelSeries r} {newLast : α} {rel : p.last ~[r] newLast} {x : α} : x ∈ p.snoc newLast rel ↔ x ∈ p ∨ x = newLast := by simp only [snoc, append, singleton_length, Nat.add_zero, Nat.reduceAdd, Fin.cast_refl, Function.comp_id, mem_def, Set.mem_range] constructor · rintro ⟨i, rfl⟩ exact Fin.lastCases (Or.inr <| Fin.append_right _ _ 0) (fun i => Or.inl ⟨⟨i.1, i.2⟩, (Fin.append_left _ _ _).symm⟩) i · intro h rcases h with (⟨i, rfl⟩ | rfl) · exact ⟨i.castSucc, Fin.append_left _ _ _⟩ · exact ⟨Fin.last _, Fin.append_right _ _ 0⟩ /-- If a series `a₀ -r→ a₁ -r→ ...` has positive length, then `a₁ -r→ ...` is another series -/ @[simps] def tail (p : RelSeries r) (len_pos : p.length ≠ 0) : RelSeries r where length := p.length - 1 toFun := Fin.tail p ∘ (Fin.cast <| Nat.succ_pred_eq_of_pos <| Nat.pos_of_ne_zero len_pos) step i := p.step ⟨i.1 + 1, Nat.lt_pred_iff.mp i.2⟩ @[simp] lemma head_tail (p : RelSeries r) (len_pos : p.length ≠ 0) : (p.tail len_pos).head = p 1 := by change p (Fin.succ _) = p 1 congr ext change (1 : ℕ) = (1 : ℕ) % _ rw [Nat.mod_eq_of_lt] simpa only [lt_add_iff_pos_left, Nat.pos_iff_ne_zero] @[simp] lemma last_tail (p : RelSeries r) (len_pos : p.length ≠ 0) : (p.tail len_pos).last = p.last := by change p _ = p _ congr ext simp only [tail_length, Fin.val_succ, Fin.coe_cast, Fin.val_last] exact Nat.succ_pred_eq_of_pos (by simpa [Nat.pos_iff_ne_zero] using len_pos) @[simp] lemma toList_tail {p : RelSeries r} (hp : p.length ≠ 0) : (p.tail hp).toList = p.toList.tail := by refine List.ext_getElem ?_ fun i h1 h2 ↦ ?_ · simp cutsat · rw [List.getElem_tail, toList_getElem_eq_apply_of_lt_length (by simp_all), toList_getElem_eq_apply_of_lt_length (by simp_all)] simp_all [Fin.tail] @[simp] lemma tail_cons (p : RelSeries r) (x : α) (hx : x ~[r] p.head) : (p.cons x hx).tail (by simp) = p := by apply toList_injective simp lemma cons_self_tail {p : RelSeries r} (hp : p.length ≠ 0) : (p.tail hp).cons p.head (p.3 ⟨0, Nat.zero_lt_of_ne_zero hp⟩) = p := by apply toList_injective simp [← head_toList] /-- To show a proposition `p` for `xs : RelSeries r` it suffices to show it for all singletons and to show that when `p` holds for `xs` it also holds for `xs` prepended with one element. Note: This can also be used to construct data, but it does not have good definitional properties, since `(p.cons x hx).tail _ = p` is not a definitional equality. -/ @[elab_as_elim] def inductionOn (motive : RelSeries r → Sort*) (singleton : (x : α) → motive (RelSeries.singleton r x)) (cons : (p : RelSeries r) → (x : α) → (hx : x ~[r] p.head) → (hp : motive p) → motive (p.cons x hx)) (p : RelSeries r) : motive p := by let this {n : ℕ} (heq : p.length = n) : motive p := by induction n generalizing p with | zero => convert singleton p.head ext n · exact heq simp [show n = 0 by cutsat, apply_zero] | succ d hd => have lq := p.tail_length (heq ▸ d.zero_ne_add_one.symm) nth_rw 3 [heq] at lq convert cons (p.tail (heq ▸ d.zero_ne_add_one.symm)) p.head (p.3 ⟨0, heq ▸ d.zero_lt_succ⟩) (hd _ lq) exact (p.cons_self_tail (heq ▸ d.zero_ne_add_one.symm)).symm exact this rfl @[simp] lemma toList_snoc (p : RelSeries r) (newLast : α) (rel : p.last ~[r] newLast) : (p.snoc newLast rel).toList = p.toList ++ [newLast] := by simp [snoc] /-- If a series ``a₀ -r→ a₁ -r→ ... -r→ aₙ``, then `a₀ -r→ a₁ -r→ ... -r→ aₙ₋₁` is another series -/ @[simps] def eraseLast (p : RelSeries r) : RelSeries r where length := p.length - 1 toFun i := p ⟨i, lt_of_lt_of_le i.2 (Nat.succ_le_succ (Nat.sub_le _ _))⟩ step i := p.step ⟨i, lt_of_lt_of_le i.2 (Nat.sub_le _ _)⟩ @[simp] lemma head_eraseLast (p : RelSeries r) : p.eraseLast.head = p.head := rfl @[simp] lemma last_eraseLast (p : RelSeries r) : p.eraseLast.last = p ⟨p.length.pred, Nat.lt_succ_iff.2 (Nat.pred_le _)⟩ := rfl /-- In a non-trivial series `p`, the last element of `p.eraseLast` is related to `p.last` -/ lemma eraseLast_last_rel_last (p : RelSeries r) (h : p.length ≠ 0) : p.eraseLast.last ~[r] p.last := by simp only [last, Fin.last, eraseLast_length, eraseLast_toFun] convert p.step ⟨p.length - 1, by cutsat⟩ simp only [Fin.succ_mk]; cutsat @[simp] lemma toList_eraseLast (p : RelSeries r) (hp : p.length ≠ 0) : p.eraseLast.toList = p.toList.dropLast := by apply List.ext_getElem · simpa using Nat.succ_pred_eq_of_ne_zero hp · intro i hi h2 rw [toList_getElem_eq_apply_of_lt_length (hi.trans_eq (by simp))] simp [← toList_getElem_eq_apply_of_lt_length] lemma snoc_self_eraseLast (p : RelSeries r) (h : p.length ≠ 0) : p.eraseLast.snoc p.last (p.eraseLast_last_rel_last h) = p := by apply toList_injective rw [toList_snoc, ← getLast_toList, toList_eraseLast _ h, List.dropLast_append_getLast] /-- To show a proposition `p` for `xs : RelSeries r` it suffices to show it for all singletons and to show that when `p` holds for `xs` it also holds for `xs` appended with one element. -/ @[elab_as_elim] def inductionOn' (motive : RelSeries r → Sort*) (singleton : (x : α) → motive (RelSeries.singleton r x)) (snoc : (p : RelSeries r) → (x : α) → (hx : p.last ~[r] x) → (hp : motive p) → motive (p.snoc x hx)) (p : RelSeries r) : motive p := by let this {n : ℕ} (heq : p.length = n) : motive p := by induction n generalizing p with | zero => convert singleton p.head ext n · exact heq · simp [show n = 0 by cutsat, apply_zero] | succ d hd => have ne0 : p.length ≠ 0 := by simp [heq] have len : p.eraseLast.length = d := by simp [heq] convert snoc p.eraseLast p.last (p.eraseLast_last_rel_last ne0) (hd _ len) exact (p.snoc_self_eraseLast ne0).symm exact this rfl /-- Given two series of the form `a₀ -r→ ... -r→ X` and `X -r→ b ---> ...`, then `a₀ -r→ ... -r→ X -r→ b ...` is another series obtained by combining the given two. -/ @[simps length] def smash (p q : RelSeries r) (connect : p.last = q.head) : RelSeries r where length := p.length + q.length toFun := Fin.addCases (m := p.length) (n := q.length + 1) (p ∘ Fin.castSucc) q step := by apply Fin.addCases <;> intro i · simp_rw [Fin.castSucc_castAdd, Fin.addCases_left, Fin.succ_castAdd] convert p.step i split_ifs with h · rw [Fin.addCases_right, h, ← last, connect, head] · apply Fin.addCases_left simpa only [Fin.castSucc_natAdd, Fin.succ_natAdd, Fin.addCases_right] using q.step i lemma smash_castLE {p q : RelSeries r} (h : p.last = q.head) (i : Fin (p.length + 1)) : p.smash q h (i.castLE (by simp)) = p i := by refine i.lastCases ?_ fun _ ↦ by dsimp only [smash]; apply Fin.addCases_left change p.smash q h (Fin.natAdd p.length (0 : Fin (q.length + 1))) = _ simpa only [smash, Fin.addCases_right] using h.symm lemma smash_castAdd {p q : RelSeries r} (h : p.last = q.head) (i : Fin p.length) : p.smash q h (i.castAdd q.length).castSucc = p i.castSucc := smash_castLE h i.castSucc lemma smash_succ_castAdd {p q : RelSeries r} (h : p.last = q.head) (i : Fin p.length) : p.smash q h (i.castAdd q.length).succ = p i.succ := smash_castLE h i.succ lemma smash_natAdd {p q : RelSeries r} (h : p.last = q.head) (i : Fin q.length) : smash p q h (i.natAdd p.length).castSucc = q i.castSucc := by dsimp only [smash, Fin.castSucc_natAdd] apply Fin.addCases_right lemma smash_succ_natAdd {p q : RelSeries r} (h : p.last = q.head) (i : Fin q.length) : smash p q h (i.natAdd p.length).succ = q i.succ := by dsimp only [smash, Fin.succ_natAdd] apply Fin.addCases_right @[simp] lemma head_smash {p q : RelSeries r} (h : p.last = q.head) : (smash p q h).head = p.head := by obtain ⟨_ | _, _⟩ := p · simpa [Fin.addCases] using h.symm dsimp only [smash, head] exact Fin.addCases_left 0 @[simp] lemma last_smash {p q : RelSeries r} (h : p.last = q.head) : (smash p q h).last = q.last := by dsimp only [smash, last] rw [← Fin.natAdd_last, Fin.addCases_right] /-- Given the series `a₀ -r→ … -r→ aᵢ -r→ … -r→ aₙ`, the series `a₀ -r→ … -r→ aᵢ`. -/ @[simps! length] def take {r : SetRel α α} (p : RelSeries r) (i : Fin (p.length + 1)) : RelSeries r where length := i toFun := fun ⟨j, h⟩ => p.toFun ⟨j, by omega⟩ step := fun ⟨j, h⟩ => p.step ⟨j, by omega⟩ @[simp] lemma head_take (p : RelSeries r) (i : Fin (p.length + 1)) : (p.take i).head = p.head := by simp [take, head] @[simp] lemma last_take (p : RelSeries r) (i : Fin (p.length + 1)) : (p.take i).last = p i := by simp [take, last, Fin.last] /-- Given the series `a₀ -r→ … -r→ aᵢ -r→ … -r→ aₙ`, the series `aᵢ₊₁ -r→ … -r→ aₙ`. -/ @[simps! length] def drop (p : RelSeries r) (i : Fin (p.length + 1)) : RelSeries r where length := p.length - i toFun := fun ⟨j, h⟩ => p.toFun ⟨j+i, by omega⟩ step := fun ⟨j, h⟩ => by convert p.step ⟨j+i.1, by omega⟩ simp only [Fin.succ_mk]; omega @[simp] lemma head_drop (p : RelSeries r) (i : Fin (p.length + 1)) : (p.drop i).head = p.toFun i := by simp [drop, head] @[simp] lemma last_drop (p : RelSeries r) (i : Fin (p.length + 1)) : (p.drop i).last = p.last := by simp only [last, drop, Fin.last] congr cutsat end RelSeries variable {r} in lemma SetRel.not_finiteDimensional_iff [Nonempty α] : ¬ r.FiniteDimensional ↔ r.InfiniteDimensional := by rw [finiteDimensional_iff, infiniteDimensional_iff] push_neg constructor · intro H n induction n with | zero => refine ⟨⟨0, ![_root_.Nonempty.some ‹_›], by simp⟩, by simp⟩ | succ n IH => obtain ⟨l, hl⟩ := IH obtain ⟨l', hl'⟩ := H l exact ⟨l'.take ⟨n + 1, by simpa [hl] using hl'⟩, rfl⟩ · intro H l obtain ⟨l', hl'⟩ := H (l.length + 1) exact ⟨l', by simp [hl']⟩ variable {r} in lemma SetRel.not_infiniteDimensional_iff [Nonempty α] : ¬ r.InfiniteDimensional ↔ r.FiniteDimensional := by rw [← not_finiteDimensional_iff, not_not] lemma SetRel.finiteDimensional_or_infiniteDimensional [Nonempty α] : r.FiniteDimensional ∨ r.InfiniteDimensional := by rw [← not_finiteDimensional_iff] exact em r.FiniteDimensional instance SetRel.FiniteDimensional.inv [FiniteDimensional r] : FiniteDimensional r.inv := ⟨.reverse (.longestOf r), fun s ↦ s.reverse.length_le_length_longestOf r⟩ variable {r} in @[simp] lemma SetRel.finiteDimensional_inv : FiniteDimensional r.inv ↔ FiniteDimensional r := ⟨fun _ ↦ .inv r.inv, fun _ ↦ .inv _⟩ @[deprecated (since := "2025-07-06")] alias SetRel.finiteDimensional_swap_iff := SetRel.finiteDimensional_inv instance SetRel.InfiniteDimensional.inv [InfiniteDimensional r] : InfiniteDimensional r.inv := ⟨fun n ↦ ⟨.reverse (.withLength r n), RelSeries.length_withLength r n⟩⟩ variable {r} in @[simp] lemma SetRel.infiniteDimensional_inv : InfiniteDimensional r.inv ↔ InfiniteDimensional r := ⟨fun _ ↦ .inv r.inv, fun _ ↦ .inv _⟩ @[deprecated (since := "2025-07-06")] alias SetRel.infiniteDimensional_swap_iff := SetRel.infiniteDimensional_inv lemma SetRel.IsWellFounded.inv_of_finiteDimensional [r.FiniteDimensional] : r.inv.IsWellFounded := by rw [IsWellFounded, wellFounded_iff_isEmpty_descending_chain] refine ⟨fun ⟨f, hf⟩ ↦ ?_⟩ let s := RelSeries.mk (r := r) ((RelSeries.longestOf r).length + 1) (f ·) (hf ·) exact (RelSeries.longestOf r).length.lt_succ_self.not_ge s.length_le_length_longestOf @[deprecated (since := "2025-07-06")] alias Rel.wellFounded_swap_of_finiteDimensional := SetRel.IsWellFounded.inv_of_finiteDimensional lemma SetRel.IsWellFounded.of_finiteDimensional [r.FiniteDimensional] : r.IsWellFounded := .inv_of_finiteDimensional r.inv @[deprecated (since := "2025-07-06")] alias SetRel.wellFounded_of_finiteDimensional := SetRel.IsWellFounded.of_finiteDimensional /-- A type is finite dimensional if its `LTSeries` has bounded length. -/ abbrev FiniteDimensionalOrder (γ : Type*) [Preorder γ] := SetRel.FiniteDimensional {(a, b) : γ × γ | a < b} instance FiniteDimensionalOrder.ofUnique (γ : Type*) [Preorder γ] [Unique γ] : FiniteDimensionalOrder γ where exists_longest_relSeries := ⟨.singleton _ default, fun x ↦ by by_contra! r exact (x.step ⟨0, by omega⟩).ne <| Subsingleton.elim _ _⟩ /-- A type is infinite dimensional if it has `LTSeries` of at least arbitrary length -/ abbrev InfiniteDimensionalOrder (γ : Type*) [Preorder γ] := SetRel.InfiniteDimensional {(a, b) : γ × γ | a < b} section LTSeries variable (α) [Preorder α] [Preorder β] /-- If `α` is a preorder, a LTSeries is a relation series of the less than relation. -/ abbrev LTSeries := RelSeries {(a, b) : α × α | a < b} namespace LTSeries /-- The longest `<`-series when a type is finite dimensional -/ protected noncomputable def longestOf [FiniteDimensionalOrder α] : LTSeries α := RelSeries.longestOf _ /-- A `<`-series with length `n` if the relation is infinite dimensional -/ protected noncomputable def withLength [InfiniteDimensionalOrder α] (n : ℕ) : LTSeries α := RelSeries.withLength _ n @[simp] lemma length_withLength [InfiniteDimensionalOrder α] (n : ℕ) : (LTSeries.withLength α n).length = n := RelSeries.length_withLength _ _ /-- if `α` is infinite dimensional, then `α` is nonempty. -/ lemma nonempty_of_infiniteDimensionalOrder [InfiniteDimensionalOrder α] : Nonempty α := ⟨LTSeries.withLength α 0 0⟩ lemma nonempty_of_finiteDimensionalOrder [FiniteDimensionalOrder α] : Nonempty α := by obtain ⟨p, _⟩ := (SetRel.finiteDimensional_iff _).mp ‹_› exact ⟨p 0⟩ variable {α} lemma longestOf_is_longest [FiniteDimensionalOrder α] (x : LTSeries α) : x.length ≤ (LTSeries.longestOf α).length := RelSeries.length_le_length_longestOf _ _ lemma longestOf_len_unique [FiniteDimensionalOrder α] (p : LTSeries α) (is_longest : ∀ (q : LTSeries α), q.length ≤ p.length) : p.length = (LTSeries.longestOf α).length := le_antisymm (longestOf_is_longest _) (is_longest _) lemma strictMono (x : LTSeries α) : StrictMono x := fun _ _ h => x.rel_of_lt h lemma monotone (x : LTSeries α) : Monotone x := x.strictMono.monotone lemma head_le (x : LTSeries α) (n : Fin (x.length + 1)) : x.head ≤ x n := x.monotone (Fin.zero_le n) lemma head_le_last (x : LTSeries α) : x.head ≤ x.last := x.head_le _ /-- An alternative constructor of `LTSeries` from a strictly monotone function. -/ @[simps] def mk (length : ℕ) (toFun : Fin (length + 1) → α) (strictMono : StrictMono toFun) : LTSeries α where length := length toFun := toFun step i := strictMono <| lt_add_one i.1 /-- An injection from the type of strictly monotone functions with limited length to `LTSeries`. -/ def injStrictMono (n : ℕ) : {f : (l : Fin n) × (Fin (l + 1) → α) // StrictMono f.2} ↪ LTSeries α where toFun f := mk f.1.1 f.1.2 f.2 inj' f g e := by obtain ⟨⟨lf, f⟩, mf⟩ := f obtain ⟨⟨lg, g⟩, mg⟩ := g dsimp only at mf mg e have leq := congr($(e).length) rw [mk_length lf f mf, mk_length lg g mg, Fin.val_eq_val] at leq subst leq simp_rw [Subtype.mk_eq_mk, Sigma.mk.inj_iff, heq_eq_eq, true_and] have feq := fun i ↦ congr($(e).toFun i) simp_rw [mk_toFun lf f mf, mk_toFun lf g mg, mk_length lf f mf] at feq rwa [funext_iff] /-- For two preorders `α, β`, if `f : α → β` is strictly monotonic, then a strict chain of `α` can be pushed out to a strict chain of `β` by `a₀ < a₁ < ... < aₙ ↦ f a₀ < f a₁ < ... < f aₙ` -/ @[simps!] def map (p : LTSeries α) (f : α → β) (hf : StrictMono f) : LTSeries β := LTSeries.mk p.length (f.comp p) (hf.comp p.strictMono) @[simp] lemma head_map (p : LTSeries α) (f : α → β) (hf : StrictMono f) : (p.map f hf).head = f p.head := rfl @[simp] lemma last_map (p : LTSeries α) (f : α → β) (hf : StrictMono f) : (p.map f hf).last = f p.last := rfl /-- For two preorders `α, β`, if `f : α → β` is surjective and strictly comonotonic, then a strict series of `β` can be pulled back to a strict chain of `α` by `b₀ < b₁ < ... < bₙ ↦ f⁻¹ b₀ < f⁻¹ b₁ < ... < f⁻¹ bₙ` where `f⁻¹ bᵢ` is an arbitrary element in the preimage of `f⁻¹ {bᵢ}`. -/ @[simps!] noncomputable def comap (p : LTSeries β) (f : α → β) (comap : ∀ ⦃x y⦄, f x < f y → x < y) (surjective : Function.Surjective f) : LTSeries α := mk p.length (fun i ↦ (surjective (p i)).choose) (fun i j h ↦ comap (by simpa only [(surjective _).choose_spec] using p.strictMono h)) /-- The strict series `0 < … < n` in `ℕ`. -/ def range (n : ℕ) : LTSeries ℕ where length := n toFun := fun i => i step i := Nat.lt_add_one i @[simp] lemma length_range (n : ℕ) : (range n).length = n := rfl @[simp] lemma range_apply (n : ℕ) (i : Fin (n + 1)) : (range n) i = i := rfl @[simp] lemma head_range (n : ℕ) : (range n).head = 0 := rfl @[simp] lemma last_range (n : ℕ) : (range n).last = n := rfl /-- Any `LTSeries` can be refined to a `CovBy`-`RelSeries` in a bidirectionally well-founded order. -/ theorem exists_relSeries_covBy {α} [PartialOrder α] [WellFoundedLT α] [WellFoundedGT α] (s : LTSeries α) : ∃ (t : RelSeries {(a, b) : α × α | a ⋖ b}) (i : Fin (s.length + 1) ↪ Fin (t.length + 1)), t ∘ i = s ∧ i 0 = 0 ∧ i (.last _) = .last _ := by obtain ⟨n, s, h⟩ := s induction n with | zero => exact ⟨⟨0, s, nofun⟩, (Equiv.refl _).toEmbedding, rfl, rfl, rfl⟩ | succ n IH => obtain ⟨t₁, i, ht, hi₁, hi₂⟩ := IH (s ∘ Fin.castSucc) fun _ ↦ h _ obtain ⟨t₂, h₁, m, h₂, ht₂⟩ := exists_covBy_seq_of_wellFoundedLT_wellFoundedGT_of_le (h (.last _)).le let t₃ : RelSeries {(a, b) : α × α | a ⋖ b} := ⟨m, (t₂ ·), fun i ↦ by simpa using ht₂ i⟩ have H : t₁.last = t₂ 0 := (congr(t₁ $hi₂.symm).trans (congr_fun ht _)).trans h₁.symm refine ⟨t₁.smash t₃ H, ⟨Fin.snoc (Fin.castLE (by simp) ∘ i) (.last _), ?_⟩, ?_, ?_, ?_⟩ · refine Fin.lastCases (Fin.lastCases (fun _ ↦ rfl) fun j eq ↦ ?_) fun j ↦ Fin.lastCases (fun eq ↦ ?_) fun k eq ↦ Fin.ext (congr_arg Fin.val (by simpa using eq) :) on_goal 2 => rw [eq_comm] at eq all_goals rw [Fin.snoc_castSucc] at eq obtain rfl : m = 0 := by simpa [t₃] using (congr_arg Fin.val eq).trans_lt (i j).2 cases (h (.last _)).ne' (h₂.symm.trans h₁) · refine funext (Fin.lastCases ?_ fun j ↦ ?_) · convert h₂; simpa using RelSeries.last_smash .. convert congr_fun ht j using 1 simp [RelSeries.smash_castLE] all_goals simp [Fin.snoc, Fin.castPred_zero, hi₁] theorem exists_relSeries_covBy_and_head_eq_bot_and_last_eq_bot {α} [PartialOrder α] [BoundedOrder α] [WellFoundedLT α] [WellFoundedGT α] (s : LTSeries α) : ∃ (t : RelSeries {(a, b) : α × α | a ⋖ b}) (i : Fin (s.length + 1) ↪ Fin (t.length + 1)), t ∘ i = s ∧ t.head = ⊥ ∧ t.last = ⊤ := by wlog h₁ : s.head = ⊥ · obtain ⟨t, i, hi, ht⟩ := this (s.cons ⊥ (bot_lt_iff_ne_bot.mpr h₁)) rfl exact ⟨t, ⟨fun j ↦ i (j.succ.cast (by simp)), fun _ _ ↦ by simp⟩, funext fun j ↦ (congr_fun hi _).trans (RelSeries.cons_cast_succ _ _ _ _), ht⟩ wlog h₂ : s.last = ⊤ · obtain ⟨t, i, hi, ht⟩ := this (s.snoc ⊤ (lt_top_iff_ne_top.mpr h₂)) (by simp [h₁]) (by simp) exact ⟨t, ⟨fun j ↦ i (.cast (by simp) j.castSucc), fun _ _ ↦ by simp⟩, funext fun j ↦ (congr_fun hi _).trans (RelSeries.snoc_cast_castSucc _ _ _ _), ht⟩ obtain ⟨t, i, hit, hi₁, hi₂⟩ := s.exists_relSeries_covBy refine ⟨t, i, hit, ?_, ?_⟩ · rw [← h₁, RelSeries.head, RelSeries.head, ← hi₁, ← hit, Function.comp] · rw [← h₂, RelSeries.last, RelSeries.last, ← hi₂, ← hit, Function.comp] /-- In ℕ, two entries in an `LTSeries` differ by at least the difference of their indices. (Expressed in a way that avoids subtraction). -/ lemma apply_add_index_le_apply_add_index_nat (p : LTSeries ℕ) (i j : Fin (p.length + 1)) (hij : i ≤ j) : p i + j ≤ p j + i := by have ⟨i, hi⟩ := i have ⟨j, hj⟩ := j simp only [Fin.mk_le_mk] at hij simp only at * induction j, hij using Nat.le_induction with | base => simp | succ j _hij ih => specialize ih (Nat.lt_of_succ_lt hj) have step : p ⟨j, _⟩ < p ⟨j + 1, _⟩ := p.step ⟨j, by cutsat⟩ norm_cast at *; cutsat /-- In ℤ, two entries in an `LTSeries` differ by at least the difference of their indices. (Expressed in a way that avoids subtraction). -/ lemma apply_add_index_le_apply_add_index_int (p : LTSeries ℤ) (i j : Fin (p.length + 1)) (hij : i ≤ j) : p i + j ≤ p j + i := by -- The proof is identical to `LTSeries.apply_add_index_le_apply_add_index_nat`, but seemed easier -- to copy rather than to abstract have ⟨i, hi⟩ := i have ⟨j, hj⟩ := j simp only [Fin.mk_le_mk] at hij simp only at * induction j, hij using Nat.le_induction with | base => simp | succ j _hij ih => specialize ih (Nat.lt_of_succ_lt hj) have step : p ⟨j, _⟩ < p ⟨j + 1, _⟩:= p.step ⟨j, by cutsat⟩ norm_cast at *; cutsat /-- In ℕ, the head and tail of an `LTSeries` differ at least by the length of the series -/ lemma head_add_length_le_nat (p : LTSeries ℕ) : p.head + p.length ≤ p.last := LTSeries.apply_add_index_le_apply_add_index_nat _ _ (Fin.last _) (Fin.zero_le _) /-- In ℤ, the head and tail of an `LTSeries` differ at least by the length of the series -/ lemma head_add_length_le_int (p : LTSeries ℤ) : p.head + p.length ≤ p.last := by simpa using LTSeries.apply_add_index_le_apply_add_index_int _ _ (Fin.last _) (Fin.zero_le _) section Fintype variable [Fintype α] lemma length_lt_card (s : LTSeries α) : s.length < Fintype.card α := by by_contra! h obtain ⟨i, j, hn, he⟩ := Fintype.exists_ne_map_eq_of_card_lt s (by rw [Fintype.card_fin]; cutsat) wlog hl : i < j generalizing i j · exact this j i hn.symm he.symm (by cutsat) exact absurd he (s.strictMono hl).ne instance [DecidableLT α] : Fintype (LTSeries α) where elems := Finset.univ.map (injStrictMono (Fintype.card α)) complete s := by have bl := s.length_lt_card obtain ⟨l, f, mf⟩ := s simp_rw [Finset.mem_map, Finset.mem_univ, true_and, Subtype.exists] use ⟨⟨l, bl⟩, f⟩, Fin.strictMono_iff_lt_succ.mpr mf; rfl end Fintype end LTSeries end LTSeries lemma not_finiteDimensionalOrder_iff [Preorder α] [Nonempty α] : ¬ FiniteDimensionalOrder α ↔ InfiniteDimensionalOrder α := SetRel.not_finiteDimensional_iff lemma not_infiniteDimensionalOrder_iff [Preorder α] [Nonempty α] : ¬ InfiniteDimensionalOrder α ↔ FiniteDimensionalOrder α := SetRel.not_infiniteDimensional_iff variable (α) in lemma finiteDimensionalOrder_or_infiniteDimensionalOrder [Preorder α] [Nonempty α] : FiniteDimensionalOrder α ∨ InfiniteDimensionalOrder α := SetRel.finiteDimensional_or_infiniteDimensional _ /-- If `f : α → β` is a strictly monotonic function and `α` is an infinite-dimensional type then so is `β`. -/ lemma infiniteDimensionalOrder_of_strictMono [Preorder α] [Preorder β] (f : α → β) (hf : StrictMono f) [InfiniteDimensionalOrder α] : InfiniteDimensionalOrder β := ⟨fun n ↦ ⟨(LTSeries.withLength _ n).map f hf, LTSeries.length_withLength α n⟩⟩
.lake/packages/mathlib/Mathlib/Order/JordanHolder.lean
import Mathlib.Order.Lattice import Mathlib.Data.List.Sort import Mathlib.Logic.Equiv.Fin.Basic import Mathlib.Logic.Equiv.Functor import Mathlib.Data.Fintype.Pigeonhole import Mathlib.Order.RelSeries /-! # Jordan-Hölder Theorem This file proves the Jordan Hölder theorem for a `JordanHolderLattice`, a class also defined in this file. Examples of `JordanHolderLattice` include `Subgroup G` if `G` is a group, and `Submodule R M` if `M` is an `R`-module. Using this approach the theorem need not be proved separately for both groups and modules, the proof in this file can be applied to both. ## Main definitions The main definitions in this file are `JordanHolderLattice` and `CompositionSeries`, and the relation `Equivalent` on `CompositionSeries` A `JordanHolderLattice` is the class for which the Jordan Hölder theorem is proved. A Jordan Hölder lattice is a lattice equipped with a notion of maximality, `IsMaximal`, and a notion of isomorphism of pairs `Iso`. In the example of subgroups of a group, `IsMaximal H K` means that `H` is a maximal normal subgroup of `K`, and `Iso (H₁, K₁) (H₂, K₂)` means that the quotient `H₁ / K₁` is isomorphic to the quotient `H₂ / K₂`. `Iso` must be symmetric and transitive and must satisfy the second isomorphism theorem `Iso (H, H ⊔ K) (H ⊓ K, K)`. A `CompositionSeries X` is a finite nonempty series of elements of the lattice `X` such that each element is maximal inside the next. The length of a `CompositionSeries X` is one less than the number of elements in the series. Note that there is no stipulation that a series start from the bottom of the lattice and finish at the top. For a composition series `s`, `s.last` is the largest element of the series, and `s.head` is the least element. Two `CompositionSeries X`, `s₁` and `s₂` are equivalent if there is a bijection `e : Fin s₁.length ≃ Fin s₂.length` such that for any `i`, `Iso (s₁ i, s₁ i.succ) (s₂ (e i), s₂ (e i.succ))` ## Main theorems The main theorem is `CompositionSeries.jordan_holder`, which says that if two composition series have the same least element and the same largest element, then they are `Equivalent`. ## TODO Provide instances of `JordanHolderLattice` for subgroups, and potentially for modular lattices. It is not entirely clear how this should be done. Possibly there should be no global instances of `JordanHolderLattice`, and the instances should only be defined locally in order to prove the Jordan-Hölder theorem for modules/groups and the API should be transferred because many of the theorems in this file will have stronger versions for modules. There will also need to be an API for mapping composition series across homomorphisms. It is also probably possible to provide an instance of `JordanHolderLattice` for any `ModularLattice`, and in this case the Jordan-Hölder theorem will say that there is a well-defined notion of length of a modular lattice. However an instance of `JordanHolderLattice` for a modular lattice will not be able to contain the correct notion of isomorphism for modules, so a separate instance for modules will still be required and this will clash with the instance for modular lattices, and so at least one of these instances should not be a global instance. > [!NOTE] > The previous paragraph indicates that the instance of `JordanHolderLattice` for submodules should > be obtained via `ModularLattice`. This is not the case in `mathlib4`. > See `JordanHolderModule.instJordanHolderLattice`. -/ universe u open Set RelSeries /-- A `JordanHolderLattice` is the class for which the Jordan Hölder theorem is proved. A Jordan Hölder lattice is a lattice equipped with a notion of maximality, `IsMaximal`, and a notion of isomorphism of pairs `Iso`. In the example of subgroups of a group, `IsMaximal H K` means that `H` is a maximal normal subgroup of `K`, and `Iso (H₁, K₁) (H₂, K₂)` means that the quotient `H₁ / K₁` is isomorphic to the quotient `H₂ / K₂`. `Iso` must be symmetric and transitive and must satisfy the second isomorphism theorem `Iso (H, H ⊔ K) (H ⊓ K, K)`. Examples include `Subgroup G` if `G` is a group, and `Submodule R M` if `M` is an `R`-module. -/ class JordanHolderLattice (X : Type u) [Lattice X] where IsMaximal : X → X → Prop lt_of_isMaximal : ∀ {x y}, IsMaximal x y → x < y sup_eq_of_isMaximal : ∀ {x y z}, IsMaximal x z → IsMaximal y z → x ≠ y → x ⊔ y = z isMaximal_inf_left_of_isMaximal_sup : ∀ {x y}, IsMaximal x (x ⊔ y) → IsMaximal y (x ⊔ y) → IsMaximal (x ⊓ y) x Iso : X × X → X × X → Prop iso_symm : ∀ {x y}, Iso x y → Iso y x iso_trans : ∀ {x y z}, Iso x y → Iso y z → Iso x z second_iso : ∀ {x y}, IsMaximal x (x ⊔ y) → Iso (x, x ⊔ y) (x ⊓ y, y) namespace JordanHolderLattice variable {X : Type u} [Lattice X] [JordanHolderLattice X] theorem isMaximal_inf_right_of_isMaximal_sup {x y : X} (hxz : IsMaximal x (x ⊔ y)) (hyz : IsMaximal y (x ⊔ y)) : IsMaximal (x ⊓ y) y := by rw [inf_comm] rw [sup_comm] at hxz hyz exact isMaximal_inf_left_of_isMaximal_sup hyz hxz theorem isMaximal_of_eq_inf (x b : X) {a y : X} (ha : x ⊓ y = a) (hxy : x ≠ y) (hxb : IsMaximal x b) (hyb : IsMaximal y b) : IsMaximal a y := by have hb : x ⊔ y = b := sup_eq_of_isMaximal hxb hyb hxy substs a b exact isMaximal_inf_right_of_isMaximal_sup hxb hyb theorem second_iso_of_eq {x y a b : X} (hm : IsMaximal x a) (ha : x ⊔ y = a) (hb : x ⊓ y = b) : Iso (x, a) (b, y) := by substs a b; exact second_iso hm theorem IsMaximal.iso_refl {x y : X} (h : IsMaximal x y) : Iso (x, y) (x, y) := second_iso_of_eq h (sup_eq_right.2 (le_of_lt (lt_of_isMaximal h))) (inf_eq_left.2 (le_of_lt (lt_of_isMaximal h))) end JordanHolderLattice open JordanHolderLattice attribute [symm] iso_symm attribute [trans] iso_trans /-- A `CompositionSeries X` is a finite nonempty series of elements of a `JordanHolderLattice` such that each element is maximal inside the next. The length of a `CompositionSeries X` is one less than the number of elements in the series. Note that there is no stipulation that a series start from the bottom of the lattice and finish at the top. For a composition series `s`, `s.last` is the largest element of the series, and `s.head` is the least element. -/ abbrev CompositionSeries (X : Type u) [Lattice X] [JordanHolderLattice X] : Type u := RelSeries {(x, y) : X × X | IsMaximal x y} namespace CompositionSeries variable {X : Type u} [Lattice X] [JordanHolderLattice X] theorem lt_succ (s : CompositionSeries X) (i : Fin s.length) : s (Fin.castSucc i) < s (Fin.succ i) := lt_of_isMaximal (s.step _) protected theorem strictMono (s : CompositionSeries X) : StrictMono s := Fin.strictMono_iff_lt_succ.2 s.lt_succ protected theorem injective (s : CompositionSeries X) : Function.Injective s := s.strictMono.injective @[simp] protected theorem inj (s : CompositionSeries X) {i j : Fin s.length.succ} : s i = s j ↔ i = j := s.injective.eq_iff theorem total {s : CompositionSeries X} {x y : X} (hx : x ∈ s) (hy : y ∈ s) : x ≤ y ∨ y ≤ x := by rcases Set.mem_range.1 hx with ⟨i, rfl⟩ rcases Set.mem_range.1 hy with ⟨j, rfl⟩ rw [s.strictMono.le_iff_le, s.strictMono.le_iff_le] exact le_total i j theorem toList_sorted (s : CompositionSeries X) : s.toList.Sorted (· < ·) := List.pairwise_iff_get.2 fun i j h => by dsimp only [RelSeries.toList] rw [List.get_ofFn, List.get_ofFn] exact s.strictMono h theorem toList_nodup (s : CompositionSeries X) : s.toList.Nodup := s.toList_sorted.nodup /-- Two `CompositionSeries` are equal if they have the same elements. See also `ext_fun`. -/ @[ext] theorem ext {s₁ s₂ : CompositionSeries X} (h : ∀ x, x ∈ s₁ ↔ x ∈ s₂) : s₁ = s₂ := toList_injective <| List.eq_of_perm_of_sorted (by classical exact List.perm_of_nodup_nodup_toFinset_eq s₁.toList_nodup s₂.toList_nodup (Finset.ext <| by simpa only [List.mem_toFinset, RelSeries.mem_toList])) s₁.toList_sorted s₂.toList_sorted @[simp] theorem le_last {s : CompositionSeries X} (i : Fin (s.length + 1)) : s i ≤ s.last := s.strictMono.monotone (Fin.le_last _) theorem le_last_of_mem {s : CompositionSeries X} {x : X} (hx : x ∈ s) : x ≤ s.last := let ⟨_i, hi⟩ := Set.mem_range.2 hx hi ▸ le_last _ @[simp] theorem head_le {s : CompositionSeries X} (i : Fin (s.length + 1)) : s.head ≤ s i := s.strictMono.monotone (Fin.zero_le _) theorem head_le_of_mem {s : CompositionSeries X} {x : X} (hx : x ∈ s) : s.head ≤ x := let ⟨_i, hi⟩ := Set.mem_range.2 hx hi ▸ head_le _ theorem last_eraseLast_le (s : CompositionSeries X) : s.eraseLast.last ≤ s.last := by simp [eraseLast, last, s.strictMono.le_iff_le, Fin.le_iff_val_le_val] theorem mem_eraseLast_of_ne_of_mem {s : CompositionSeries X} {x : X} (hx : x ≠ s.last) (hxs : x ∈ s) : x ∈ s.eraseLast := by rcases hxs with ⟨i, rfl⟩ have hi : (i : ℕ) < (s.length - 1).succ := by conv_rhs => rw [← Nat.succ_sub (length_pos_of_nontrivial ⟨_, ⟨i, rfl⟩, _, s.last_mem, hx⟩), Nat.add_one_sub_one] exact lt_of_le_of_ne (Nat.le_of_lt_succ i.2) (by simpa [last, s.inj, Fin.ext_iff] using hx) exact ⟨⟨↑i, hi⟩, by simp⟩ theorem mem_eraseLast {s : CompositionSeries X} {x : X} (h : 0 < s.length) : x ∈ s.eraseLast ↔ x ≠ s.last ∧ x ∈ s := by simp only [RelSeries.mem_def, eraseLast] constructor · rintro ⟨i, rfl⟩ have hi : (i : ℕ) < s.length := by omega simp [last, Fin.ext_iff, ne_of_lt hi, -Set.mem_range, Set.mem_range_self] · intro h exact mem_eraseLast_of_ne_of_mem h.1 h.2 theorem lt_last_of_mem_eraseLast {s : CompositionSeries X} {x : X} (h : 0 < s.length) (hx : x ∈ s.eraseLast) : x < s.last := lt_of_le_of_ne (le_last_of_mem ((mem_eraseLast h).1 hx).2) ((mem_eraseLast h).1 hx).1 theorem isMaximal_eraseLast_last {s : CompositionSeries X} (h : 0 < s.length) : IsMaximal s.eraseLast.last s.last := by rw [last_eraseLast, last] have := s.step ⟨s.length - 1, by cutsat⟩ simp only [Fin.castSucc_mk, Fin.succ_mk, mem_setOf_eq] at this convert this using 3 exact (tsub_add_cancel_of_le h).symm theorem eq_snoc_eraseLast {s : CompositionSeries X} (h : 0 < s.length) : s = snoc (eraseLast s) s.last (isMaximal_eraseLast_last h) := by ext x simp only [mem_snoc, mem_eraseLast h, ne_eq] by_cases h : x = s.last <;> simp [*, s.last_mem] @[simp] theorem snoc_eraseLast_last {s : CompositionSeries X} (h : IsMaximal s.eraseLast.last s.last) : s.eraseLast.snoc s.last h = s := have h : 0 < s.length := Nat.pos_of_ne_zero (fun hs => ne_of_gt (lt_of_isMaximal h) <| by simp [last, Fin.ext_iff, hs]) (eq_snoc_eraseLast h).symm /-- Two `CompositionSeries X`, `s₁` and `s₂` are equivalent if there is a bijection `e : Fin s₁.length ≃ Fin s₂.length` such that for any `i`, `Iso (s₁ i) (s₁ i.succ) (s₂ (e i), s₂ (e i.succ))` -/ def Equivalent (s₁ s₂ : CompositionSeries X) : Prop := ∃ f : Fin s₁.length ≃ Fin s₂.length, ∀ i : Fin s₁.length, Iso (s₁ (Fin.castSucc i), s₁ i.succ) (s₂ (Fin.castSucc (f i)), s₂ (Fin.succ (f i))) namespace Equivalent @[refl] theorem refl (s : CompositionSeries X) : Equivalent s s := ⟨Equiv.refl _, fun _ => (s.step _).iso_refl⟩ @[symm] theorem symm {s₁ s₂ : CompositionSeries X} (h : Equivalent s₁ s₂) : Equivalent s₂ s₁ := ⟨h.choose.symm, fun i => iso_symm (by simpa using h.choose_spec (h.choose.symm i))⟩ @[trans] theorem trans {s₁ s₂ s₃ : CompositionSeries X} (h₁ : Equivalent s₁ s₂) (h₂ : Equivalent s₂ s₃) : Equivalent s₁ s₃ := ⟨h₁.choose.trans h₂.choose, fun i => iso_trans (h₁.choose_spec i) (h₂.choose_spec (h₁.choose i))⟩ protected theorem smash {s₁ s₂ t₁ t₂ : CompositionSeries X} (hs : s₁.last = s₂.head) (ht : t₁.last = t₂.head) (h₁ : Equivalent s₁ t₁) (h₂ : Equivalent s₂ t₂) : Equivalent (smash s₁ s₂ hs) (smash t₁ t₂ ht) := let e : Fin (s₁.length + s₂.length) ≃ Fin (t₁.length + t₂.length) := calc Fin (s₁.length + s₂.length) ≃ (Fin s₁.length) ⊕ (Fin s₂.length) := finSumFinEquiv.symm _ ≃ (Fin t₁.length) ⊕ (Fin t₂.length) := Equiv.sumCongr h₁.choose h₂.choose _ ≃ Fin (t₁.length + t₂.length) := finSumFinEquiv ⟨e, by intro i refine Fin.addCases ?_ ?_ i · intro i simpa [e, smash_castAdd, smash_succ_castAdd] using h₁.choose_spec i · intro i simpa [e, -Fin.castSucc_natAdd, smash_natAdd, smash_succ_natAdd] using h₂.choose_spec i⟩ protected theorem snoc {s₁ s₂ : CompositionSeries X} {x₁ x₂ : X} {hsat₁ : IsMaximal s₁.last x₁} {hsat₂ : IsMaximal s₂.last x₂} (hequiv : Equivalent s₁ s₂) (hlast : Iso (s₁.last, x₁) (s₂.last, x₂)) : Equivalent (s₁.snoc x₁ hsat₁) (s₂.snoc x₂ hsat₂) := let e : Fin s₁.length.succ ≃ Fin s₂.length.succ := calc Fin (s₁.length + 1) ≃ Option (Fin s₁.length) := finSuccEquivLast _ ≃ Option (Fin s₂.length) := Functor.mapEquiv Option hequiv.choose _ ≃ Fin (s₂.length + 1) := finSuccEquivLast.symm ⟨e, fun i => by refine Fin.lastCases ?_ ?_ i · simpa [e, apply_last] using hlast · intro i simpa [e, ← Fin.castSucc_succ] using hequiv.choose_spec i⟩ theorem length_eq {s₁ s₂ : CompositionSeries X} (h : Equivalent s₁ s₂) : s₁.length = s₂.length := by simpa using Fintype.card_congr h.choose theorem snoc_snoc_swap {s : CompositionSeries X} {x₁ x₂ y₁ y₂ : X} {hsat₁ : IsMaximal s.last x₁} {hsat₂ : IsMaximal s.last x₂} {hsaty₁ : IsMaximal (snoc s x₁ hsat₁).last y₁} {hsaty₂ : IsMaximal (snoc s x₂ hsat₂).last y₂} (hr₁ : Iso (s.last, x₁) (x₂, y₂)) (hr₂ : Iso (x₁, y₁) (s.last, x₂)) : Equivalent (snoc (snoc s x₁ hsat₁) y₁ hsaty₁) (snoc (snoc s x₂ hsat₂) y₂ hsaty₂) := let e : Fin (s.length + 1 + 1) ≃ Fin (s.length + 1 + 1) := Equiv.swap (Fin.last _) (Fin.castSucc (Fin.last _)) have h1 : ∀ {i : Fin s.length}, (Fin.castSucc (Fin.castSucc i)) ≠ (Fin.castSucc (Fin.last _)) := by simp have h2 : ∀ {i : Fin s.length}, (Fin.castSucc (Fin.castSucc i)) ≠ Fin.last _ := by simp ⟨e, by intro i dsimp only [e] refine Fin.lastCases ?_ (fun i => ?_) i · erw [Equiv.swap_apply_left, snoc_castSucc, show (snoc s x₁ hsat₁).toFun (Fin.last _) = x₁ from last_snoc _ _ _, Fin.succ_last, show ((s.snoc x₁ hsat₁).snoc y₁ hsaty₁).toFun (Fin.last _) = y₁ from last_snoc _ _ _, snoc_castSucc, snoc_castSucc, Fin.succ_castSucc, snoc_castSucc, Fin.succ_last, show (s.snoc _ hsat₂).toFun (Fin.last _) = x₂ from last_snoc _ _ _] exact hr₂ · refine Fin.lastCases ?_ (fun i => ?_) i · erw [Equiv.swap_apply_right, snoc_castSucc, snoc_castSucc, snoc_castSucc, Fin.succ_castSucc, snoc_castSucc, Fin.succ_last, last_snoc', last_snoc', last_snoc'] exact hr₁ · erw [Equiv.swap_apply_of_ne_of_ne h2 h1, snoc_castSucc, snoc_castSucc, snoc_castSucc, snoc_castSucc, Fin.succ_castSucc, snoc_castSucc, Fin.succ_castSucc, snoc_castSucc, snoc_castSucc, snoc_castSucc] exact (s.step i).iso_refl⟩ end Equivalent theorem length_eq_zero_of_head_eq_head_of_last_eq_last_of_length_eq_zero {s₁ s₂ : CompositionSeries X} (hb : s₁.head = s₂.head) (ht : s₁.last = s₂.last) (hs₁ : s₁.length = 0) : s₂.length = 0 := by have : Fin.last s₂.length = (0 : Fin s₂.length.succ) := s₂.injective (hb.symm.trans ((congr_arg s₁ (Fin.ext (by simp [hs₁]))).trans ht)).symm simpa [Fin.ext_iff] theorem length_pos_of_head_eq_head_of_last_eq_last_of_length_pos {s₁ s₂ : CompositionSeries X} (hb : s₁.head = s₂.head) (ht : s₁.last = s₂.last) : 0 < s₁.length → 0 < s₂.length := not_imp_not.1 (by simpa only [pos_iff_ne_zero, ne_eq, Decidable.not_not] using length_eq_zero_of_head_eq_head_of_last_eq_last_of_length_eq_zero hb.symm ht.symm) theorem eq_of_head_eq_head_of_last_eq_last_of_length_eq_zero {s₁ s₂ : CompositionSeries X} (hb : s₁.head = s₂.head) (ht : s₁.last = s₂.last) (hs₁0 : s₁.length = 0) : s₁ = s₂ := by have : ∀ x, x ∈ s₁ ↔ x = s₁.last := fun x => ⟨fun hx => subsingleton_of_length_eq_zero hs₁0 hx s₁.last_mem, fun hx => hx.symm ▸ s₁.last_mem⟩ have : ∀ x, x ∈ s₂ ↔ x = s₂.last := fun x => ⟨fun hx => subsingleton_of_length_eq_zero (length_eq_zero_of_head_eq_head_of_last_eq_last_of_length_eq_zero hb ht hs₁0) hx s₂.last_mem, fun hx => hx.symm ▸ s₂.last_mem⟩ ext simp [*] /-- Given a `CompositionSeries`, `s`, and an element `x` such that `x` is maximal inside `s.last` there is a series, `t`, such that `t.last = x`, `t.head = s.head` and `snoc t s.last _` is equivalent to `s`. -/ theorem exists_last_eq_snoc_equivalent (s : CompositionSeries X) (x : X) (hm : IsMaximal x s.last) (hb : s.head ≤ x) : ∃ t : CompositionSeries X, t.head = s.head ∧ t.length + 1 = s.length ∧ ∃ htx : t.last = x, Equivalent s (snoc t s.last (show IsMaximal t.last _ from htx.symm ▸ hm)) := by induction hn : s.length generalizing s x with | zero => exact (ne_of_gt (lt_of_le_of_lt hb (lt_of_isMaximal hm)) (subsingleton_of_length_eq_zero hn s.last_mem s.head_mem)).elim | succ n ih => have h0s : 0 < s.length := hn.symm ▸ Nat.succ_pos _ by_cases hetx : s.eraseLast.last = x · use s.eraseLast simp [← hetx, hn, Equivalent.refl] · have imxs : IsMaximal (x ⊓ s.eraseLast.last) s.eraseLast.last := isMaximal_of_eq_inf x s.last rfl (Ne.symm hetx) hm (isMaximal_eraseLast_last h0s) have := ih _ _ imxs (le_inf (by simpa) (le_last_of_mem s.eraseLast.head_mem)) (by simp [hn]) rcases this with ⟨t, htb, htl, htt, hteqv⟩ have hmtx : IsMaximal t.last x := isMaximal_of_eq_inf s.eraseLast.last s.last (by rw [inf_comm, htt]) hetx (isMaximal_eraseLast_last h0s) hm use snoc t x hmtx refine ⟨by simp [htb], by simp [htl], by simp, ?_⟩ have : s.Equivalent ((snoc t s.eraseLast.last <| show IsMaximal t.last _ from htt.symm ▸ imxs).snoc s.last (by simpa using isMaximal_eraseLast_last h0s)) := by conv_lhs => rw [eq_snoc_eraseLast h0s] exact Equivalent.snoc hteqv (by simpa using (isMaximal_eraseLast_last h0s).iso_refl) refine this.trans <| Equivalent.snoc_snoc_swap (iso_symm (second_iso_of_eq hm (sup_eq_of_isMaximal hm (isMaximal_eraseLast_last h0s) (Ne.symm hetx)) htt.symm)) (second_iso_of_eq (isMaximal_eraseLast_last h0s) (sup_eq_of_isMaximal (isMaximal_eraseLast_last h0s) hm hetx) (by rw [inf_comm, htt])) /-- The **Jordan-Hölder** theorem, stated for any `JordanHolderLattice`. If two composition series start and finish at the same place, they are equivalent. -/ theorem jordan_holder (s₁ s₂ : CompositionSeries X) (hb : s₁.head = s₂.head) (ht : s₁.last = s₂.last) : Equivalent s₁ s₂ := by induction hle : s₁.length generalizing s₁ s₂ with | zero => rw [eq_of_head_eq_head_of_last_eq_last_of_length_eq_zero hb ht hle] | succ n ih => have h0s₂ : 0 < s₂.length := length_pos_of_head_eq_head_of_last_eq_last_of_length_pos hb ht (hle.symm ▸ Nat.succ_pos _) rcases exists_last_eq_snoc_equivalent s₁ s₂.eraseLast.last (ht.symm ▸ isMaximal_eraseLast_last h0s₂) (hb.symm ▸ s₂.head_eraseLast ▸ head_le_of_mem (last_mem _)) with ⟨t, htb, htl, htt, hteq⟩ have := ih t s₂.eraseLast (by simp [htb, ← hb]) htt (Nat.succ_inj.1 (htl.trans hle)) refine hteq.trans ?_ conv_rhs => rw [eq_snoc_eraseLast h0s₂] simp only [ht] exact Equivalent.snoc this (by simpa [htt] using (isMaximal_eraseLast_last h0s₂).iso_refl) end CompositionSeries
.lake/packages/mathlib/Mathlib/Order/SupIndep.lean
import Mathlib.Data.Finset.Lattice.Union import Mathlib.Data.Finset.Lattice.Prod import Mathlib.Data.Finset.Sigma import Mathlib.Data.Fintype.Basic import Mathlib.Order.CompleteLatticeIntervals import Mathlib.Order.ModularLattice /-! # Supremum independence In this file, we define supremum independence of indexed sets. An indexed family `f : ι → α` is sup-independent if, for all `a`, `f a` and the supremum of the rest are disjoint. ## Main definitions * `Finset.SupIndep s f`: a family of elements `f` are supremum independent on the finite set `s`. * `sSupIndep s`: a set of elements are supremum independent. * `iSupIndep f`: a family of elements are supremum independent. ## Main statements * In a distributive lattice, supremum independence is equivalent to pairwise disjointness: * `Finset.supIndep_iff_pairwiseDisjoint` * `CompleteLattice.sSupIndep_iff_pairwiseDisjoint` * `CompleteLattice.iSupIndep_iff_pairwiseDisjoint` * Otherwise, supremum independence is stronger than pairwise disjointness: * `Finset.SupIndep.pairwiseDisjoint` * `sSupIndep.pairwiseDisjoint` * `iSupIndep.pairwiseDisjoint` ## Implementation notes For the finite version, we avoid the "obvious" definition `∀ i ∈ s, Disjoint (f i) ((s.erase i).sup f)` because `erase` would require decidable equality on `ι`. -/ variable {α β ι ι' : Type*} /-! ### On lattices with a bottom element, via `Finset.sup` -/ namespace Finset section Lattice variable [Lattice α] [OrderBot α] /-- Supremum independence of finite sets. We avoid the "obvious" definition using `s.erase i` because `erase` would require decidable equality on `ι`. -/ def SupIndep (s : Finset ι) (f : ι → α) : Prop := ∀ ⦃t⦄, t ⊆ s → ∀ ⦃i⦄, i ∈ s → i ∉ t → Disjoint (f i) (t.sup f) variable {s t : Finset ι} {f g : ι → α} {i : ι} /-- The RHS looks like the definition of `iSupIndep`. -/ theorem supIndep_iff_disjoint_erase [DecidableEq ι] : s.SupIndep f ↔ ∀ i ∈ s, Disjoint (f i) ((s.erase i).sup f) := ⟨fun hs _ hi => hs (erase_subset _ _) hi (notMem_erase _ _), fun hs _ ht i hi hit => (hs i hi).mono_right (sup_mono fun _ hj => mem_erase.2 ⟨ne_of_mem_of_not_mem hj hit, ht hj⟩)⟩ /-- If both the index type and the lattice have decidable equality, then the `SupIndep` predicate is decidable. TODO: speedup the definition and drop the `[DecidableEq ι]` assumption by iterating over the pairs `(a, t)` such that `s = Finset.cons a t _` using something like `List.eraseIdx` or by generating both `f i` and `(s.erase i).sup f` in one loop over `s`. Yet another possible optimization is to precompute partial suprema of `f` over the inits and tails of the list representing `s`, store them in 2 `Array`s, then compute each `sup` in 1 operation. -/ instance [DecidableEq ι] [DecidableEq α] : Decidable (SupIndep s f) := have : ∀ i, Decidable (Disjoint (f i) ((s.erase i).sup f)) := fun _ ↦ decidable_of_iff _ disjoint_iff.symm decidable_of_iff _ supIndep_iff_disjoint_erase.symm theorem SupIndep.subset (ht : t.SupIndep f) (h : s ⊆ t) : s.SupIndep f := fun _ hu _ hi => ht (hu.trans h) (h hi) lemma SupIndep.mono (hf : s.SupIndep f) (h : ∀ i ∈ s, g i ≤ f i) : s.SupIndep g := fun _ ht j hj htj ↦ (hf ht hj htj).mono (h j hj) (sup_mono_fun fun b a ↦ h b (ht a)) @[simp, grind ←] theorem supIndep_empty (f : ι → α) : (∅ : Finset ι).SupIndep f := fun _ _ a ha => (notMem_empty a ha).elim @[simp, grind ←] theorem supIndep_singleton (i : ι) (f : ι → α) : ({i} : Finset ι).SupIndep f := fun s hs j hji hj => by rw [eq_empty_of_ssubset_singleton ⟨hs, fun h => hj (h hji)⟩, sup_empty] exact disjoint_bot_right theorem SupIndep.pairwiseDisjoint (hs : s.SupIndep f) : (s : Set ι).PairwiseDisjoint f := fun _ ha _ hb hab => sup_singleton.subst <| hs (singleton_subset_iff.2 hb) ha <| notMem_singleton.2 hab theorem SupIndep.le_sup_iff (hs : s.SupIndep f) (hts : t ⊆ s) (hi : i ∈ s) (hf : ∀ i, f i ≠ ⊥) : f i ≤ t.sup f ↔ i ∈ t := by refine ⟨fun h => ?_, le_sup⟩ by_contra hit exact hf i (disjoint_self.1 <| (hs hts hi hit).mono_right h) theorem SupIndep.antitone_fun {g : ι → α} (hle : ∀ x ∈ s, f x ≤ g x) (h : s.SupIndep g) : s.SupIndep f := fun _t hts i his hit ↦ (h hts his hit).mono (hle i his) <| Finset.sup_mono_fun fun x hx ↦ hle x <| hts hx protected theorem SupIndep.image [DecidableEq ι] {s : Finset ι'} {g : ι' → ι} (hs : s.SupIndep (f ∘ g)) : (s.image g).SupIndep f := by intro t ht i hi hit rcases subset_image_iff.mp ht with ⟨t, hts, rfl⟩ rcases mem_image.mp hi with ⟨i, his, rfl⟩ rw [sup_image] exact hs hts his (hit <| mem_image_of_mem _ ·) theorem supIndep_map {s : Finset ι'} {g : ι' ↪ ι} : (s.map g).SupIndep f ↔ s.SupIndep (f ∘ g) := by refine ⟨fun hs t ht i hi hit => ?_, fun hs => ?_⟩ · rw [← sup_map] exact hs (map_subset_map.2 ht) ((mem_map' _).2 hi) (by rwa [mem_map']) · classical rw [map_eq_image] exact hs.image @[simp] theorem supIndep_pair [DecidableEq ι] {i j : ι} (hij : i ≠ j) : ({i, j} : Finset ι).SupIndep f ↔ Disjoint (f i) (f j) := by suffices Disjoint (f i) (f j) → Disjoint (f j) ((Finset.erase {i, j} j).sup f) by simpa [supIndep_iff_disjoint_erase, hij] rw [pair_comm] simp [hij.symm, disjoint_comm] theorem supIndep_univ_bool (f : Bool → α) : (Finset.univ : Finset Bool).SupIndep f ↔ Disjoint (f false) (f true) := haveI : true ≠ false := by simp only [Ne, not_false_iff, reduceCtorEq] (supIndep_pair this).trans disjoint_comm @[simp] theorem supIndep_univ_fin_two (f : Fin 2 → α) : (Finset.univ : Finset (Fin 2)).SupIndep f ↔ Disjoint (f 0) (f 1) := have : (0 : Fin 2) ≠ 1 := by simp supIndep_pair this @[simp] theorem supIndep_attach : (s.attach.SupIndep fun a => f a) ↔ s.SupIndep f := by simpa [Finset.attach_map_val] using (supIndep_map (s := s.attach) (g := .subtype _)).symm alias ⟨_, SupIndep.attach⟩ := supIndep_attach end Lattice section IsModularLattice variable [Lattice α] [IsModularLattice α] [OrderBot α] {s : Finset ι} {f : ι → α} /-- Bind operation for `SupIndep`. -/ protected theorem SupIndep.biUnion [DecidableEq ι] {s : Finset ι'} {g : ι' → Finset ι} {f : ι → α} (hs : s.SupIndep fun i => (g i).sup f) (hg : ∀ i' ∈ s, (g i').SupIndep f) : (s.biUnion g).SupIndep f := by classical intro a ha b hb hab obtain ⟨i', hi', hb⟩ := mem_biUnion.mp hb let t := s.erase i' let u := (g i').erase b apply Disjoint.mono_right <| calc a.sup f ≤ (t.biUnion g ∪ u).sup f := by grind _ ≤ (t.sup fun i => (g i).sup f) ⊔ (u.sup f) := by grind symm apply Disjoint.disjoint_sup_left_of_disjoint_sup_right · exact (supIndep_iff_disjoint_erase.mp (hg i' hi') b hb).symm · rw [← sup_singleton (f := f) (b := b), ← sup_union, show u ∪ {b} = g i' by grind] exact (supIndep_iff_disjoint_erase.mp hs i' hi').symm /-- Bind operation for `SupIndep`. -/ protected theorem SupIndep.sup [DecidableEq ι] {s : Finset ι'} {g : ι' → Finset ι} {f : ι → α} (hs : s.SupIndep fun i => (g i).sup f) (hg : ∀ i' ∈ s, (g i').SupIndep f) : (s.sup g).SupIndep f := by rw [sup_eq_biUnion] exact hs.biUnion hg /-- Bind operation for `SupIndep`. -/ protected theorem SupIndep.sigma {β : ι → Type*} {s : Finset ι} {g : ∀ i, Finset (β i)} {f : Sigma β → α} (hs : s.SupIndep fun i => (g i).sup fun b => f ⟨i, b⟩) (hg : ∀ i ∈ s, (g i).SupIndep fun b => f ⟨i, b⟩) : (s.sigma g).SupIndep f := by classical rw [Finset.sigma_eq_biUnion] apply Finset.SupIndep.biUnion · simpa using hs · simpa [Finset.supIndep_map] using hg protected theorem SupIndep.product {s : Finset ι} {t : Finset ι'} {f : ι × ι' → α} (hs : s.SupIndep fun i => t.sup fun i' => f (i, i')) (ht : t.SupIndep fun i' => s.sup fun i => f (i, i')) : (s ×ˢ t).SupIndep f := by classical rw [Finset.product_eq_biUnion] apply Finset.SupIndep.biUnion · simpa using hs · exact fun i' hi' ↦ (ht.mono fun i hi ↦ Finset.le_sup (f := fun i' ↦ f (i', i)) hi').image protected theorem SupIndep.disjoint_sup_sup {s : Finset ι} {f : ι → α} {u v : Finset ι} (hs : s.SupIndep f) (hu : u ⊆ s) (hv : v ⊆ s) (huv : Disjoint u v) : Disjoint (u.sup f) (v.sup f) := by classical induction u using Finset.induction generalizing v with | empty => simp | insert x u hx ih => grind [= SupIndep, = disjoint_comm, ← Disjoint.disjoint_sup_left_of_disjoint_sup_right] theorem supIndep_sigma_iff' {β : ι → Type*} {s : Finset ι} {g : ∀ i, Finset (β i)} {f : Sigma β → α} : (s.sigma g).SupIndep f ↔ (s.SupIndep fun i => (g i).sup fun b => f ⟨i, b⟩) ∧ ∀ i ∈ s, (g i).SupIndep fun b => f ⟨i, b⟩ := by classical refine ⟨fun h ↦ ⟨fun t _ i _ _ ↦ ?_, fun i _ t _ j _ _ ↦ ?_⟩, fun h ↦ h.1.sigma h.2⟩ · let u := (g i).map (Function.Embedding.sigmaMk i) let v := t.biUnion (fun j => (g j).map (Function.Embedding.sigmaMk j)) suffices Disjoint (u.sup f) (v.sup f) by simpa only [sup_map, sup_biUnion, u, v] apply SupIndep.disjoint_sup_sup h <;> grind [disjoint_left] · suffices Disjoint (f ⟨i, j⟩) ((t.image fun b ↦ ⟨i, b⟩).sup f) by simpa only [sup_image] grind [= SupIndep] theorem supIndep_product_iff {s : Finset ι} {t : Finset ι'} {f : ι × ι' → α} : (s.product t).SupIndep f ↔ (s.SupIndep fun i => t.sup fun i' => f (i, i')) ∧ t.SupIndep fun i' => s.sup fun i => f (i, i') := by classical refine ⟨fun h ↦ ⟨fun u _ i _ _ ↦ ?_, fun u _ i _ _ ↦ ?_⟩, fun h ↦ h.1.product h.2⟩ · suffices Disjoint ((t.image ((i, ·))).sup f) ((u ×ˢ t).sup f) by simpa only [sup_image, sup_product_left] grind [Finset.SupIndep.disjoint_sup_sup, = product_eq_sprod, = disjoint_left] · suffices Disjoint ((s.image ((·, i))).sup f) ((s ×ˢ u).sup f) by simpa only [sup_image, sup_product_right] grind [Finset.SupIndep.disjoint_sup_sup, = product_eq_sprod, = disjoint_left] end IsModularLattice section DistribLattice variable [DistribLattice α] [OrderBot α] {s : Finset ι} {f : ι → α} theorem supIndep_iff_pairwiseDisjoint : s.SupIndep f ↔ (s : Set ι).PairwiseDisjoint f := ⟨SupIndep.pairwiseDisjoint, fun hs _ ht _ hi hit => Finset.disjoint_sup_right.2 fun _ hj => hs hi (ht hj) (ne_of_mem_of_not_mem hj hit).symm⟩ alias ⟨_, _root_.Set.PairwiseDisjoint.supIndep⟩ := supIndep_iff_pairwiseDisjoint end DistribLattice end Finset /-! ### On complete lattices via `sSup` -/ section CompleteLattice variable [CompleteLattice α] open Set Function /-- An independent set of elements in a complete lattice is one in which every element is disjoint from the `Sup` of the rest. -/ def sSupIndep (s : Set α) : Prop := ∀ ⦃a⦄, a ∈ s → Disjoint a (sSup (s \ {a})) variable {s : Set α} (hs : sSupIndep s) @[simp] theorem sSupIndep_empty : sSupIndep (∅ : Set α) := fun x hx => (Set.notMem_empty x hx).elim include hs in theorem sSupIndep.mono {t : Set α} (hst : t ⊆ s) : sSupIndep t := fun _ ha => (hs (hst ha)).mono_right (sSup_le_sSup (diff_subset_diff_left hst)) include hs in /-- If the elements of a set are independent, then any pair within that set is disjoint. -/ theorem sSupIndep.pairwiseDisjoint : s.PairwiseDisjoint id := fun _ hx y hy h => disjoint_sSup_right (hs hx) ((mem_diff y).mpr ⟨hy, h.symm⟩) theorem sSupIndep_singleton (a : α) : sSupIndep ({a} : Set α) := fun i hi ↦ by simp_all theorem sSupIndep_pair {a b : α} (hab : a ≠ b) : sSupIndep ({a, b} : Set α) ↔ Disjoint a b := by constructor · intro h exact h.pairwiseDisjoint (mem_insert _ _) (mem_insert_of_mem _ (mem_singleton _)) hab · rintro h c ((rfl : c = a) | (rfl : c = b)) · convert h using 1 simp [hab, sSup_singleton] · convert h.symm using 1 simp [hab, sSup_singleton] include hs in /-- If the elements of a set are independent, then any element is disjoint from the `sSup` of some subset of the rest. -/ theorem sSupIndep.disjoint_sSup {x : α} {y : Set α} (hx : x ∈ s) (hy : y ⊆ s) (hxy : x ∉ y) : Disjoint x (sSup y) := by have := (hs.mono <| insert_subset_iff.mpr ⟨hx, hy⟩) (mem_insert x _) rw [insert_diff_of_mem _ (mem_singleton _), diff_singleton_eq_self hxy] at this exact this /-- An independent indexed family of elements in a complete lattice is one in which every element is disjoint from the `iSup` of the rest. Example: an indexed family of non-zero elements in a vector space is linearly independent iff the indexed family of subspaces they generate is independent in this sense. Example: an indexed family of submodules of a module is independent in this sense if and only the natural map from the direct sum of the submodules to the module is injective. -/ def iSupIndep {ι : Sort*} {α : Type*} [CompleteLattice α] (t : ι → α) : Prop := ∀ i : ι, Disjoint (t i) (⨆ (j) (_ : j ≠ i), t j) theorem sSupIndep_iff {α : Type*} [CompleteLattice α] (s : Set α) : sSupIndep s ↔ iSupIndep ((↑) : s → α) := by simp_rw [iSupIndep, sSupIndep, SetCoe.forall, sSup_eq_iSup] refine forall₂_congr fun a ha => ?_ simp [iSup_subtype, iSup_and] variable {t : ι → α} (ht : iSupIndep t) theorem iSupIndep_def : iSupIndep t ↔ ∀ i, Disjoint (t i) (⨆ (j) (_ : j ≠ i), t j) := Iff.rfl theorem iSupIndep_def' : iSupIndep t ↔ ∀ i, Disjoint (t i) (sSup (t '' { j | j ≠ i })) := by simp_rw [sSup_image] rfl theorem iSupIndep_def'' : iSupIndep t ↔ ∀ i, Disjoint (t i) (sSup { a | ∃ j ≠ i, t j = a }) := by rw [iSupIndep_def'] aesop @[simp] theorem iSupIndep_subsingleton [Subsingleton ι] (t : ι → α) : iSupIndep t := fun i ↦ by simp [← Subsingleton.elim i] @[deprecated "use iSupIndep_subsingleton instead" (since := "2025-09-18")] theorem iSupIndep_empty (t : Empty → α) : iSupIndep t := nofun @[deprecated "use iSupIndep_subsingleton instead" (since := "2025-09-18")] theorem iSupIndep_pempty (t : PEmpty → α) : iSupIndep t := nofun include ht in /-- If the elements of a set are independent, then any pair within that set is disjoint. -/ theorem iSupIndep.pairwiseDisjoint : Pairwise (Disjoint on t) := fun x y h => disjoint_sSup_right (ht x) ⟨y, iSup_pos h.symm⟩ theorem iSupIndep.mono {s t : ι → α} (hs : iSupIndep s) (hst : t ≤ s) : iSupIndep t := fun i => (hs i).mono (hst i) <| iSup₂_mono fun j _ => hst j /-- Composing an independent indexed family with an injective function on the index results in another independent indexed family. -/ theorem iSupIndep.comp {ι ι' : Sort*} {t : ι → α} {f : ι' → ι} (ht : iSupIndep t) (hf : Injective f) : iSupIndep (t ∘ f) := fun i => (ht (f i)).mono_right <| by refine (iSup_mono fun i => ?_).trans (iSup_comp_le _ f) exact iSup_const_mono hf.ne theorem iSupIndep.comp' {ι ι' : Sort*} {t : ι → α} {f : ι' → ι} (ht : iSupIndep <| t ∘ f) (hf : Surjective f) : iSupIndep t := by intro i obtain ⟨i', rfl⟩ := hf i rw [← hf.iSup_comp] exact (ht i').mono_right (biSup_mono fun j' hij => mt (congr_arg f) hij) theorem iSupIndep.sSupIndep_range (ht : iSupIndep t) : sSupIndep <| range t := by rw [sSupIndep_iff] rw [← coe_comp_rangeFactorization t] at ht exact ht.comp' rangeFactorization_surjective @[simp] theorem iSupIndep_ne_bot : iSupIndep (fun i : {i // t i ≠ ⊥} ↦ t i) ↔ iSupIndep t := by refine ⟨fun h ↦ ?_, fun h ↦ h.comp Subtype.val_injective⟩ simp only [iSupIndep_def] at h ⊢ intro i cases eq_or_ne (t i) ⊥ with | inl hi => simp [hi] | inr hi => ?_ convert h ⟨i, hi⟩ have : ∀ j, ⨆ (_ : t j = ⊥), t j = ⊥ := fun j ↦ by simp only [iSup_eq_bot, imp_self] rw [iSup_split _ (fun j ↦ t j = ⊥), iSup_subtype] simp only [iSup_comm (ι' := _ ≠ i), this, ne_eq, sup_of_le_right, Subtype.mk.injEq, iSup_bot, bot_le] theorem iSupIndep.injOn (ht : iSupIndep t) : InjOn t {i | t i ≠ ⊥} := by rintro i _ j (hj : t j ≠ ⊥) h by_contra! contra apply hj suffices t j ≤ ⨆ (k) (_ : k ≠ i), t k by replace ht := (ht i).mono_right this rwa [h, disjoint_self] at ht replace contra : j ≠ i := Ne.symm contra -- Porting note: needs explicit `f` exact le_iSup₂ (f := fun x _ ↦ t x) j contra lemma iSupIndep.injOn_iInf {β : ι → Type*} (t : (i : ι) → β i → α) (ht : ∀ i, iSupIndep (t i)) : InjOn (fun b : (i : ι) → β i ↦ ⨅ i, t i (b i)) {b | ⨅ i, t i (b i) ≠ ⊥} := by intro b₁ hb₁ b₂ hb₂ h_eq beta_reduce at h_eq by_contra h_neq obtain ⟨i, hi⟩ : ∃ i, b₁ i ≠ b₂ i := Function.ne_iff.mp h_neq have := calc ⨅ i, t i (b₁ i) ≤ t i (b₁ i) ⊓ t i (b₂ i) := le_inf (iInf_le ..) (h_eq ▸ iInf_le ..) _ = ⊥ := (ht i (b₁ i) |>.mono_right <| le_iSup₂_of_le (b₂ i) hi.symm le_rfl).eq_bot simp_all theorem iSupIndep.injective (ht : iSupIndep t) (h_ne_bot : ∀ i, t i ≠ ⊥) : Injective t := by suffices univ = {i | t i ≠ ⊥} by simpa [← this] using ht.injOn simp_all theorem iSupIndep_pair {i j : ι} (hij : i ≠ j) (huniv : ∀ k, k = i ∨ k = j) : iSupIndep t ↔ Disjoint (t i) (t j) := by constructor · exact fun h => h.pairwiseDisjoint hij · rintro h k obtain rfl | rfl := huniv k · refine h.mono_right (iSup_le fun i => iSup_le fun hi => Eq.le ?_) rw [(huniv i).resolve_left hi] · refine h.symm.mono_right (iSup_le fun j => iSup_le fun hj => Eq.le ?_) rw [(huniv j).resolve_right hj] /-- Composing an independent indexed family with an order isomorphism on the elements results in another independent indexed family. -/ theorem iSupIndep.map_orderIso {ι : Sort*} {α β : Type*} [CompleteLattice α] [CompleteLattice β] (f : α ≃o β) {a : ι → α} (ha : iSupIndep a) : iSupIndep (f ∘ a) := fun i => ((ha i).map_orderIso f).mono_right (f.monotone.le_map_iSup₂ _) @[simp] theorem iSupIndep_map_orderIso_iff {ι : Sort*} {α β : Type*} [CompleteLattice α] [CompleteLattice β] (f : α ≃o β) {a : ι → α} : iSupIndep (f ∘ a) ↔ iSupIndep a := ⟨fun h => have hf : f.symm ∘ f ∘ a = a := congr_arg (· ∘ a) f.left_inv.comp_eq_id hf ▸ h.map_orderIso f.symm, fun h => h.map_orderIso f⟩ /-- If the elements of a set are independent, then any element is disjoint from the `iSup` of some subset of the rest. -/ theorem iSupIndep.disjoint_biSup {ι : Type*} {α : Type*} [CompleteLattice α] {t : ι → α} (ht : iSupIndep t) {x : ι} {y : Set ι} (hx : x ∉ y) : Disjoint (t x) (⨆ i ∈ y, t i) := Disjoint.mono_right (biSup_mono fun _ hi => (ne_of_mem_of_not_mem hi hx :)) (ht x) lemma iSupIndep.of_coe_Iic_comp {ι : Sort*} {a : α} {t : ι → Set.Iic a} (ht : iSupIndep ((↑) ∘ t : ι → α)) : iSupIndep t := by intro i x specialize ht i simp_rw [Function.comp_apply, ← Set.Iic.coe_iSup] at ht exact @ht x theorem iSupIndep_iff_supIndep {s : Finset ι} {f : ι → α} : iSupIndep (f ∘ ((↑) : s → ι)) ↔ s.SupIndep f := by classical rw [Finset.supIndep_iff_disjoint_erase] refine Subtype.forall.trans (forall₂_congr fun a b => ?_) rw [Finset.sup_eq_iSup] congr! 1 refine iSup_subtype.trans ?_ congr! 1 simp [iSup_and, @iSup_comm _ (_ ∈ s)] alias ⟨iSupIndep.supIndep, Finset.SupIndep.independent⟩ := iSupIndep_iff_supIndep theorem iSupIndep.supIndep' {f : ι → α} (s : Finset ι) (h : iSupIndep f) : s.SupIndep f := iSupIndep.supIndep (h.comp Subtype.coe_injective) /-- A variant of `CompleteLattice.iSupIndep_iff_supIndep` for `Fintype`s. -/ theorem iSupIndep_iff_supIndep_univ [Fintype ι] {f : ι → α} : iSupIndep f ↔ Finset.univ.SupIndep f := by classical simp [Finset.supIndep_iff_disjoint_erase, iSupIndep, Finset.sup_eq_iSup] alias ⟨iSupIndep.sup_indep_univ, Finset.SupIndep.iSupIndep_of_univ⟩ := iSupIndep_iff_supIndep_univ end CompleteLattice section Frame variable [Order.Frame α] theorem sSupIndep_iff_pairwiseDisjoint {s : Set α} : sSupIndep s ↔ s.PairwiseDisjoint id := ⟨sSupIndep.pairwiseDisjoint, fun hs _ hi => disjoint_sSup_iff.2 fun _ hj => hs hi hj.1 <| Ne.symm hj.2⟩ alias ⟨_, _root_.Set.PairwiseDisjoint.sSupIndep⟩ := sSupIndep_iff_pairwiseDisjoint open scoped Function in -- required for scoped `on` notation theorem iSupIndep_iff_pairwiseDisjoint {f : ι → α} : iSupIndep f ↔ Pairwise (Disjoint on f) := ⟨iSupIndep.pairwiseDisjoint, fun hs _ => disjoint_iSup_iff.2 fun _ => disjoint_iSup_iff.2 fun hij => hs hij.symm⟩ end Frame
.lake/packages/mathlib/Mathlib/Order/OrdContinuous.lean
import Mathlib.Order.ConditionallyCompleteLattice.Basic import Mathlib.Order.RelIso.Basic /-! # Order continuity We say that a function is *left order continuous* if it sends all least upper bounds to least upper bounds. The order dual notion is called *right order continuity*. For monotone functions `ℝ → ℝ` these notions correspond to the usual left and right continuity. We prove some basic lemmas (`map_sup`, `map_sSup` etc) and prove that a `RelIso` is both left and right order continuous. -/ universe u v w x variable {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} open Function OrderDual Set /-! ### Definitions -/ /-- A function `f` between preorders is left order continuous if it preserves all suprema. We define it using `IsLUB` instead of `sSup` so that the proof works both for complete lattices and conditionally complete lattices. -/ def LeftOrdContinuous [Preorder α] [Preorder β] (f : α → β) := ∀ ⦃s : Set α⦄ ⦃x⦄, IsLUB s x → IsLUB (f '' s) (f x) /-- A function `f` between preorders is right order continuous if it preserves all infima. We define it using `IsGLB` instead of `sInf` so that the proof works both for complete lattices and conditionally complete lattices. -/ def RightOrdContinuous [Preorder α] [Preorder β] (f : α → β) := ∀ ⦃s : Set α⦄ ⦃x⦄, IsGLB s x → IsGLB (f '' s) (f x) namespace LeftOrdContinuous section Preorder variable (α) [Preorder α] [Preorder β] [Preorder γ] {g : β → γ} {f : α → β} protected theorem id : LeftOrdContinuous (id : α → α) := fun s x h => by simpa only [image_id] using h variable {α} protected theorem rightOrdContinuous_dual : LeftOrdContinuous f → RightOrdContinuous (toDual ∘ f ∘ ofDual) := id theorem map_isGreatest (hf : LeftOrdContinuous f) {s : Set α} {x : α} (h : IsGreatest s x) : IsGreatest (f '' s) (f x) := ⟨mem_image_of_mem f h.1, (hf h.isLUB).1⟩ theorem mono (hf : LeftOrdContinuous f) : Monotone f := fun a₁ a₂ h => have : IsGreatest {a₁, a₂} a₂ := ⟨Or.inr rfl, by simp [*]⟩ (hf.map_isGreatest this).2 <| mem_image_of_mem _ (Or.inl rfl) theorem comp (hg : LeftOrdContinuous g) (hf : LeftOrdContinuous f) : LeftOrdContinuous (g ∘ f) := fun s x h => by simpa only [image_image] using hg (hf h) protected theorem iterate {f : α → α} (hf : LeftOrdContinuous f) (n : ℕ) : LeftOrdContinuous f^[n] := match n with | 0 => LeftOrdContinuous.id α | (n + 1) => (LeftOrdContinuous.iterate hf n).comp hf end Preorder section SemilatticeSup variable [SemilatticeSup α] [SemilatticeSup β] {f : α → β} theorem map_sup (hf : LeftOrdContinuous f) (x y : α) : f (x ⊔ y) = f x ⊔ f y := (hf isLUB_pair).unique <| by simp only [image_pair, isLUB_pair] theorem le_iff (hf : LeftOrdContinuous f) (h : Injective f) {x y} : f x ≤ f y ↔ x ≤ y := by simp only [← sup_eq_right, ← hf.map_sup, h.eq_iff] theorem lt_iff (hf : LeftOrdContinuous f) (h : Injective f) {x y} : f x < f y ↔ x < y := by simp only [lt_iff_le_not_ge, hf.le_iff h] variable (f) /-- Convert an injective left order continuous function to an order embedding. -/ def toOrderEmbedding (hf : LeftOrdContinuous f) (h : Injective f) : α ↪o β := ⟨⟨f, h⟩, hf.le_iff h⟩ variable {f} @[simp] theorem coe_toOrderEmbedding (hf : LeftOrdContinuous f) (h : Injective f) : ⇑(hf.toOrderEmbedding f h) = f := rfl end SemilatticeSup section CompleteLattice variable [CompleteLattice α] [CompleteLattice β] {f : α → β} theorem map_sSup' (hf : LeftOrdContinuous f) (s : Set α) : f (sSup s) = sSup (f '' s) := (hf <| isLUB_sSup s).sSup_eq.symm theorem map_sSup (hf : LeftOrdContinuous f) (s : Set α) : f (sSup s) = ⨆ x ∈ s, f x := by rw [hf.map_sSup', sSup_image] theorem map_iSup (hf : LeftOrdContinuous f) (g : ι → α) : f (⨆ i, g i) = ⨆ i, f (g i) := by simp only [iSup, hf.map_sSup', ← range_comp] rfl end CompleteLattice section ConditionallyCompleteLattice variable [ConditionallyCompleteLattice α] [ConditionallyCompleteLattice β] [Nonempty ι] {f : α → β} theorem map_csSup (hf : LeftOrdContinuous f) {s : Set α} (sne : s.Nonempty) (sbdd : BddAbove s) : f (sSup s) = sSup (f '' s) := ((hf <| isLUB_csSup sne sbdd).csSup_eq <| sne.image f).symm theorem map_ciSup (hf : LeftOrdContinuous f) {g : ι → α} (hg : BddAbove (range g)) : f (⨆ i, g i) = ⨆ i, f (g i) := by simp only [iSup, hf.map_csSup (range_nonempty _) hg, ← range_comp] rfl end ConditionallyCompleteLattice end LeftOrdContinuous namespace RightOrdContinuous section Preorder variable (α) [Preorder α] [Preorder β] [Preorder γ] {g : β → γ} {f : α → β} protected theorem id : RightOrdContinuous (id : α → α) := fun s x h => by simpa only [image_id] using h variable {α} protected theorem orderDual : RightOrdContinuous f → LeftOrdContinuous (toDual ∘ f ∘ ofDual) := id theorem map_isLeast (hf : RightOrdContinuous f) {s : Set α} {x : α} (h : IsLeast s x) : IsLeast (f '' s) (f x) := hf.orderDual.map_isGreatest h theorem mono (hf : RightOrdContinuous f) : Monotone f := hf.orderDual.mono.dual theorem comp (hg : RightOrdContinuous g) (hf : RightOrdContinuous f) : RightOrdContinuous (g ∘ f) := hg.orderDual.comp hf.orderDual protected theorem iterate {f : α → α} (hf : RightOrdContinuous f) (n : ℕ) : RightOrdContinuous f^[n] := hf.orderDual.iterate n end Preorder section SemilatticeInf variable [SemilatticeInf α] [SemilatticeInf β] {f : α → β} theorem map_inf (hf : RightOrdContinuous f) (x y : α) : f (x ⊓ y) = f x ⊓ f y := hf.orderDual.map_sup x y theorem le_iff (hf : RightOrdContinuous f) (h : Injective f) {x y} : f x ≤ f y ↔ x ≤ y := hf.orderDual.le_iff h theorem lt_iff (hf : RightOrdContinuous f) (h : Injective f) {x y} : f x < f y ↔ x < y := hf.orderDual.lt_iff h variable (f) /-- Convert an injective left order continuous function to an `OrderEmbedding`. -/ def toOrderEmbedding (hf : RightOrdContinuous f) (h : Injective f) : α ↪o β := ⟨⟨f, h⟩, hf.le_iff h⟩ variable {f} @[simp] theorem coe_toOrderEmbedding (hf : RightOrdContinuous f) (h : Injective f) : ⇑(hf.toOrderEmbedding f h) = f := rfl end SemilatticeInf section CompleteLattice variable [CompleteLattice α] [CompleteLattice β] {f : α → β} theorem map_sInf' (hf : RightOrdContinuous f) (s : Set α) : f (sInf s) = sInf (f '' s) := hf.orderDual.map_sSup' s theorem map_sInf (hf : RightOrdContinuous f) (s : Set α) : f (sInf s) = ⨅ x ∈ s, f x := hf.orderDual.map_sSup s theorem map_iInf (hf : RightOrdContinuous f) (g : ι → α) : f (⨅ i, g i) = ⨅ i, f (g i) := hf.orderDual.map_iSup g end CompleteLattice section ConditionallyCompleteLattice variable [ConditionallyCompleteLattice α] [ConditionallyCompleteLattice β] [Nonempty ι] {f : α → β} theorem map_csInf (hf : RightOrdContinuous f) {s : Set α} (sne : s.Nonempty) (sbdd : BddBelow s) : f (sInf s) = sInf (f '' s) := hf.orderDual.map_csSup sne sbdd theorem map_ciInf (hf : RightOrdContinuous f) {g : ι → α} (hg : BddBelow (range g)) : f (⨅ i, g i) = ⨅ i, f (g i) := hf.orderDual.map_ciSup hg end ConditionallyCompleteLattice end RightOrdContinuous namespace GaloisConnection variable [Preorder α] [Preorder β] {f : α → β} {g : β → α} /-- A left adjoint in a Galois connection is left-continuous in the order-theoretic sense. -/ lemma leftOrdContinuous (gc : GaloisConnection f g) : LeftOrdContinuous f := fun _ _ ↦ gc.isLUB_l_image /-- A right adjoint in a Galois connection is right-continuous in the order-theoretic sense. -/ lemma rightOrdContinuous (gc : GaloisConnection f g) : RightOrdContinuous g := fun _ _ ↦ gc.isGLB_u_image end GaloisConnection namespace OrderIso variable [Preorder α] [Preorder β] (e : α ≃o β) protected lemma leftOrdContinuous : LeftOrdContinuous e := e.to_galoisConnection.leftOrdContinuous protected lemma rightOrdContinuous : RightOrdContinuous e := e.symm.to_galoisConnection.rightOrdContinuous end OrderIso
.lake/packages/mathlib/Mathlib/Order/Nat.lean
import Mathlib.Data.Nat.Find import Mathlib.Order.BoundedOrder.Basic import Mathlib.Order.Bounds.Defs /-! # The natural numbers form a linear order This file contains the linear order instance on the natural numbers. See note [foundational algebra order theory]. ## TODO Move the `LinearOrder ℕ` instance here (https://github.com/leanprover-community/mathlib4/pull/13092). -/ namespace Nat instance instOrderBot : OrderBot ℕ where bot := 0 bot_le := zero_le instance instNoMaxOrder : NoMaxOrder ℕ where exists_gt n := ⟨n + 1, n.lt_succ_self⟩ /-! ### Miscellaneous lemmas -/ @[simp high] protected lemma bot_eq_zero : ⊥ = 0 := rfl /-- `Nat.find` is the minimum natural number satisfying a predicate `p`. -/ lemma isLeast_find {p : ℕ → Prop} [DecidablePred p] (hp : ∃ n, p n) : IsLeast {n | p n} (Nat.find hp) := ⟨Nat.find_spec hp, fun _ ↦ Nat.find_min' hp⟩ end Nat /-- `Nat.find` is the minimum element of a nonempty set of natural numbers. -/ lemma Set.Nonempty.isLeast_natFind {s : Set ℕ} [DecidablePred (· ∈ s)] (hs : s.Nonempty) : IsLeast s (Nat.find hs) := Nat.isLeast_find hs
.lake/packages/mathlib/Mathlib/Order/LiminfLimsup.lean
import Mathlib.Order.ConditionallyCompleteLattice.Indexed import Mathlib.Order.Filter.IsBounded import Mathlib.Order.Hom.CompleteLattice /-! # liminfs and limsups of functions and filters Defines the liminf/limsup of a function taking values in a conditionally complete lattice, with respect to an arbitrary filter. We define `limsSup f` (`limsInf f`) where `f` is a filter taking values in a conditionally complete lattice. `limsSup f` is the smallest element `a` such that, eventually, `u ≤ a` (and vice versa for `limsInf f`). To work with the Limsup along a function `u` use `limsSup (map u f)`. Usually, one defines the Limsup as `inf (sup s)` where the Inf is taken over all sets in the filter. For instance, in ℕ along a function `u`, this is `inf_n (sup_{k ≥ n} u k)` (and the latter quantity decreases with `n`, so this is in fact a limit.). There is however a difficulty: it is well possible that `u` is not bounded on the whole space, only eventually (think of `limsup (fun x ↦ 1/x)` on ℝ. Then there is no guarantee that the quantity above really decreases (the value of the `sup` beforehand is not really well defined, as one cannot use ∞), so that the Inf could be anything. So one cannot use this `inf sup ...` definition in conditionally complete lattices, and one has to use a less tractable definition. In conditionally complete lattices, the definition is only useful for filters which are eventually bounded above (otherwise, the Limsup would morally be +∞, which does not belong to the space) and which are frequently bounded below (otherwise, the Limsup would morally be -∞, which is not in the space either). We start with definitions of these concepts for arbitrary filters, before turning to the definitions of Limsup and Liminf. In complete lattices, however, it coincides with the `Inf Sup` definition. -/ open Filter Set Function variable {α β γ ι ι' : Type*} namespace Filter section ConditionallyCompleteLattice variable [ConditionallyCompleteLattice α] {s : Set α} {u : β → α} /-- The `limsSup` of a filter `f` is the infimum of the `a` such that the inequality `x ≤ a` eventually holds for `f`. -/ def limsSup (f : Filter α) : α := sInf { a | ∀ᶠ n in f, n ≤ a } /-- The `limsInf` of a filter `f` is the supremum of the `a` such that the inequality `x ≥ a` eventually holds for `f`. -/ def limsInf (f : Filter α) : α := sSup { a | ∀ᶠ n in f, a ≤ n } /-- The `limsup` of a function `u` along a filter `f` is the infimum of the `a` such that the inequality `u x ≤ a` eventually holds for `f`. -/ def limsup (u : β → α) (f : Filter β) : α := limsSup (map u f) /-- The `liminf` of a function `u` along a filter `f` is the supremum of the `a` such that the inequality `u x ≥ a` eventually holds for `f`. -/ def liminf (u : β → α) (f : Filter β) : α := limsInf (map u f) /-- The `blimsup` of a function `u` along a filter `f`, bounded by a predicate `p`, is the infimum of the `a` such that the inequality `u x ≤ a` eventually holds for `f`, whenever `p x` holds. -/ def blimsup (u : β → α) (f : Filter β) (p : β → Prop) := sInf { a | ∀ᶠ x in f, p x → u x ≤ a } /-- The `bliminf` of a function `u` along a filter `f`, bounded by a predicate `p`, is the supremum of the `a` such that the inequality `a ≤ u x` eventually holds for `f` whenever `p x` holds. -/ def bliminf (u : β → α) (f : Filter β) (p : β → Prop) := sSup { a | ∀ᶠ x in f, p x → a ≤ u x } section variable {f : Filter β} {u : β → α} {p : β → Prop} theorem limsup_eq : limsup u f = sInf { a | ∀ᶠ n in f, u n ≤ a } := rfl theorem liminf_eq : liminf u f = sSup { a | ∀ᶠ n in f, a ≤ u n } := rfl theorem blimsup_eq : blimsup u f p = sInf { a | ∀ᶠ x in f, p x → u x ≤ a } := rfl theorem bliminf_eq : bliminf u f p = sSup { a | ∀ᶠ x in f, p x → a ≤ u x } := rfl lemma liminf_comp (u : β → α) (v : γ → β) (f : Filter γ) : liminf (u ∘ v) f = liminf u (map v f) := rfl lemma limsup_comp (u : β → α) (v : γ → β) (f : Filter γ) : limsup (u ∘ v) f = limsup u (map v f) := rfl end @[simp] theorem blimsup_true (f : Filter β) (u : β → α) : (blimsup u f fun _ => True) = limsup u f := by simp [blimsup_eq, limsup_eq] @[simp] theorem bliminf_true (f : Filter β) (u : β → α) : (bliminf u f fun _ => True) = liminf u f := by simp [bliminf_eq, liminf_eq] lemma blimsup_eq_limsup {f : Filter β} {u : β → α} {p : β → Prop} : blimsup u f p = limsup u (f ⊓ 𝓟 {x | p x}) := by simp only [blimsup_eq, limsup_eq, eventually_inf_principal, mem_setOf_eq] lemma bliminf_eq_liminf {f : Filter β} {u : β → α} {p : β → Prop} : bliminf u f p = liminf u (f ⊓ 𝓟 {x | p x}) := blimsup_eq_limsup (α := αᵒᵈ) theorem blimsup_eq_limsup_subtype {f : Filter β} {u : β → α} {p : β → Prop} : blimsup u f p = limsup (u ∘ ((↑) : { x | p x } → β)) (comap (↑) f) := by rw [blimsup_eq_limsup, limsup, limsup, ← map_map, map_comap_setCoe_val] theorem bliminf_eq_liminf_subtype {f : Filter β} {u : β → α} {p : β → Prop} : bliminf u f p = liminf (u ∘ ((↑) : { x | p x } → β)) (comap (↑) f) := blimsup_eq_limsup_subtype (α := αᵒᵈ) theorem limsSup_le_of_le {f : Filter α} {a} (hf : f.IsCobounded (· ≤ ·) := by isBoundedDefault) (h : ∀ᶠ n in f, n ≤ a) : limsSup f ≤ a := csInf_le hf h theorem le_limsInf_of_le {f : Filter α} {a} (hf : f.IsCobounded (· ≥ ·) := by isBoundedDefault) (h : ∀ᶠ n in f, a ≤ n) : a ≤ limsInf f := le_csSup hf h theorem limsup_le_of_le {f : Filter β} {u : β → α} {a} (hf : f.IsCoboundedUnder (· ≤ ·) u := by isBoundedDefault) (h : ∀ᶠ n in f, u n ≤ a) : limsup u f ≤ a := csInf_le hf h theorem le_liminf_of_le {f : Filter β} {u : β → α} {a} (hf : f.IsCoboundedUnder (· ≥ ·) u := by isBoundedDefault) (h : ∀ᶠ n in f, a ≤ u n) : a ≤ liminf u f := le_csSup hf h theorem le_limsSup_of_le {f : Filter α} {a} (hf : f.IsBounded (· ≤ ·) := by isBoundedDefault) (h : ∀ b, (∀ᶠ n in f, n ≤ b) → a ≤ b) : a ≤ limsSup f := le_csInf hf h theorem limsInf_le_of_le {f : Filter α} {a} (hf : f.IsBounded (· ≥ ·) := by isBoundedDefault) (h : ∀ b, (∀ᶠ n in f, b ≤ n) → b ≤ a) : limsInf f ≤ a := csSup_le hf h theorem le_limsup_of_le {f : Filter β} {u : β → α} {a} (hf : f.IsBoundedUnder (· ≤ ·) u := by isBoundedDefault) (h : ∀ b, (∀ᶠ n in f, u n ≤ b) → a ≤ b) : a ≤ limsup u f := le_csInf hf h theorem liminf_le_of_le {f : Filter β} {u : β → α} {a} (hf : f.IsBoundedUnder (· ≥ ·) u := by isBoundedDefault) (h : ∀ b, (∀ᶠ n in f, b ≤ u n) → b ≤ a) : liminf u f ≤ a := csSup_le hf h theorem limsInf_le_limsSup {f : Filter α} [NeBot f] (h₁ : f.IsBounded (· ≤ ·) := by isBoundedDefault) (h₂ : f.IsBounded (· ≥ ·) := by isBoundedDefault) : limsInf f ≤ limsSup f := liminf_le_of_le h₂ fun a₀ ha₀ => le_limsup_of_le h₁ fun a₁ ha₁ => show a₀ ≤ a₁ from let ⟨_, hb₀, hb₁⟩ := (ha₀.and ha₁).exists le_trans hb₀ hb₁ theorem liminf_le_limsup {f : Filter β} [NeBot f] {u : β → α} (h : f.IsBoundedUnder (· ≤ ·) u := by isBoundedDefault) (h' : f.IsBoundedUnder (· ≥ ·) u := by isBoundedDefault) : liminf u f ≤ limsup u f := limsInf_le_limsSup h h' theorem limsSup_le_limsSup {f g : Filter α} (hf : f.IsCobounded (· ≤ ·) := by isBoundedDefault) (hg : g.IsBounded (· ≤ ·) := by isBoundedDefault) (h : ∀ a, (∀ᶠ n in g, n ≤ a) → ∀ᶠ n in f, n ≤ a) : limsSup f ≤ limsSup g := csInf_le_csInf hf hg h theorem limsInf_le_limsInf {f g : Filter α} (hf : f.IsBounded (· ≥ ·) := by isBoundedDefault) (hg : g.IsCobounded (· ≥ ·) := by isBoundedDefault) (h : ∀ a, (∀ᶠ n in f, a ≤ n) → ∀ᶠ n in g, a ≤ n) : limsInf f ≤ limsInf g := csSup_le_csSup hg hf h theorem limsup_le_limsup {α : Type*} [ConditionallyCompleteLattice β] {f : Filter α} {u v : α → β} (h : u ≤ᶠ[f] v) (hu : f.IsCoboundedUnder (· ≤ ·) u := by isBoundedDefault) (hv : f.IsBoundedUnder (· ≤ ·) v := by isBoundedDefault) : limsup u f ≤ limsup v f := limsSup_le_limsSup hu hv fun _ => h.trans theorem liminf_le_liminf {α : Type*} [ConditionallyCompleteLattice β] {f : Filter α} {u v : α → β} (h : ∀ᶠ a in f, u a ≤ v a) (hu : f.IsBoundedUnder (· ≥ ·) u := by isBoundedDefault) (hv : f.IsCoboundedUnder (· ≥ ·) v := by isBoundedDefault) : liminf u f ≤ liminf v f := limsup_le_limsup (β := βᵒᵈ) h hv hu theorem limsSup_le_limsSup_of_le {f g : Filter α} (h : f ≤ g) (hf : f.IsCobounded (· ≤ ·) := by isBoundedDefault) (hg : g.IsBounded (· ≤ ·) := by isBoundedDefault) : limsSup f ≤ limsSup g := limsSup_le_limsSup hf hg fun _ ha => h ha theorem limsInf_le_limsInf_of_le {f g : Filter α} (h : g ≤ f) (hf : f.IsBounded (· ≥ ·) := by isBoundedDefault) (hg : g.IsCobounded (· ≥ ·) := by isBoundedDefault) : limsInf f ≤ limsInf g := limsInf_le_limsInf hf hg fun _ ha => h ha theorem limsup_le_limsup_of_le {α β} [ConditionallyCompleteLattice β] {f g : Filter α} (h : f ≤ g) {u : α → β} (hf : f.IsCoboundedUnder (· ≤ ·) u := by isBoundedDefault) (hg : g.IsBoundedUnder (· ≤ ·) u := by isBoundedDefault) : limsup u f ≤ limsup u g := limsSup_le_limsSup_of_le (map_mono h) hf hg theorem liminf_le_liminf_of_le {α β} [ConditionallyCompleteLattice β] {f g : Filter α} (h : g ≤ f) {u : α → β} (hf : f.IsBoundedUnder (· ≥ ·) u := by isBoundedDefault) (hg : g.IsCoboundedUnder (· ≥ ·) u := by isBoundedDefault) : liminf u f ≤ liminf u g := limsInf_le_limsInf_of_le (map_mono h) hf hg lemma limsSup_principal_eq_csSup (h : BddAbove s) (hs : s.Nonempty) : limsSup (𝓟 s) = sSup s := by simp only [limsSup, eventually_principal]; exact csInf_upperBounds_eq_csSup h hs lemma limsInf_principal_eq_csSup (h : BddBelow s) (hs : s.Nonempty) : limsInf (𝓟 s) = sInf s := limsSup_principal_eq_csSup (α := αᵒᵈ) h hs lemma limsup_top_eq_ciSup [Nonempty β] (hu : BddAbove (range u)) : limsup u ⊤ = ⨆ i, u i := by rw [limsup, map_top, limsSup_principal_eq_csSup hu (range_nonempty _), sSup_range] lemma liminf_top_eq_ciInf [Nonempty β] (hu : BddBelow (range u)) : liminf u ⊤ = ⨅ i, u i := by rw [liminf, map_top, limsInf_principal_eq_csSup hu (range_nonempty _), sInf_range] theorem limsup_congr {α : Type*} [ConditionallyCompleteLattice β] {f : Filter α} {u v : α → β} (h : ∀ᶠ a in f, u a = v a) : limsup u f = limsup v f := by rw [limsup_eq] congr with b exact eventually_congr (h.mono fun x hx => by simp [hx]) theorem blimsup_congr {f : Filter β} {u v : β → α} {p : β → Prop} (h : ∀ᶠ a in f, p a → u a = v a) : blimsup u f p = blimsup v f p := by simpa only [blimsup_eq_limsup] using limsup_congr <| eventually_inf_principal.2 h theorem bliminf_congr {f : Filter β} {u v : β → α} {p : β → Prop} (h : ∀ᶠ a in f, p a → u a = v a) : bliminf u f p = bliminf v f p := blimsup_congr (α := αᵒᵈ) h theorem liminf_congr {α : Type*} [ConditionallyCompleteLattice β] {f : Filter α} {u v : α → β} (h : ∀ᶠ a in f, u a = v a) : liminf u f = liminf v f := limsup_congr (β := βᵒᵈ) h @[simp] theorem limsup_const {α : Type*} [ConditionallyCompleteLattice β] {f : Filter α} [NeBot f] (b : β) : limsup (fun _ => b) f = b := by simpa only [limsup_eq, eventually_const] using csInf_Ici @[simp] theorem liminf_const {α : Type*} [ConditionallyCompleteLattice β] {f : Filter α} [NeBot f] (b : β) : liminf (fun _ => b) f = b := limsup_const (β := βᵒᵈ) b theorem HasBasis.liminf_eq_sSup_iUnion_iInter {ι ι' : Type*} {f : ι → α} {v : Filter ι} {p : ι' → Prop} {s : ι' → Set ι} (hv : v.HasBasis p s) : liminf f v = sSup (⋃ (j : Subtype p), ⋂ (i : s j), Iic (f i)) := by simp_rw [liminf_eq, hv.eventually_iff] congr 1 ext x simp only [mem_setOf_eq, iInter_coe_set, mem_iUnion, mem_iInter, mem_Iic, Subtype.exists, exists_prop] theorem HasBasis.liminf_eq_sSup_univ_of_empty {f : ι → α} {v : Filter ι} {p : ι' → Prop} {s : ι' → Set ι} (hv : v.HasBasis p s) (i : ι') (hi : p i) (h'i : s i = ∅) : liminf f v = sSup univ := by simp [hv.eq_bot_iff.2 ⟨i, hi, h'i⟩, liminf_eq] theorem HasBasis.limsup_eq_sInf_iUnion_iInter {ι ι' : Type*} {f : ι → α} {v : Filter ι} {p : ι' → Prop} {s : ι' → Set ι} (hv : v.HasBasis p s) : limsup f v = sInf (⋃ (j : Subtype p), ⋂ (i : s j), Ici (f i)) := HasBasis.liminf_eq_sSup_iUnion_iInter (α := αᵒᵈ) hv theorem HasBasis.limsup_eq_sInf_univ_of_empty {f : ι → α} {v : Filter ι} {p : ι' → Prop} {s : ι' → Set ι} (hv : v.HasBasis p s) (i : ι') (hi : p i) (h'i : s i = ∅) : limsup f v = sInf univ := HasBasis.liminf_eq_sSup_univ_of_empty (α := αᵒᵈ) hv i hi h'i @[simp] theorem liminf_nat_add (f : ℕ → α) (k : ℕ) : liminf (fun i => f (i + k)) atTop = liminf f atTop := by rw [← Function.comp_def, liminf, liminf, ← map_map, map_add_atTop_eq_nat] @[simp] theorem limsup_nat_add (f : ℕ → α) (k : ℕ) : limsup (fun i => f (i + k)) atTop = limsup f atTop := @liminf_nat_add αᵒᵈ _ f k end ConditionallyCompleteLattice section CompleteLattice variable [CompleteLattice α] @[simp] theorem limsSup_bot : limsSup (⊥ : Filter α) = ⊥ := bot_unique <| sInf_le <| by simp @[simp] theorem limsup_bot (f : β → α) : limsup f ⊥ = ⊥ := by simp [limsup] @[simp] theorem limsInf_bot : limsInf (⊥ : Filter α) = ⊤ := top_unique <| le_sSup <| by simp @[simp] theorem liminf_bot (f : β → α) : liminf f ⊥ = ⊤ := by simp [liminf] @[simp] theorem limsSup_top : limsSup (⊤ : Filter α) = ⊤ := top_unique <| le_sInf <| by simpa [eq_univ_iff_forall] using fun b hb => top_unique <| hb _ @[simp] theorem limsInf_top : limsInf (⊤ : Filter α) = ⊥ := bot_unique <| sSup_le <| by simpa [eq_univ_iff_forall] using fun b hb => bot_unique <| hb _ @[simp] theorem blimsup_false {f : Filter β} {u : β → α} : (blimsup u f fun _ => False) = ⊥ := by simp [blimsup_eq] @[simp] theorem bliminf_false {f : Filter β} {u : β → α} : (bliminf u f fun _ => False) = ⊤ := by simp [bliminf_eq] /-- Same as limsup_const applied to `⊥` but without the `NeBot f` assumption -/ @[simp] theorem limsup_const_bot {f : Filter β} : limsup (fun _ : β => (⊥ : α)) f = (⊥ : α) := by rw [limsup_eq, eq_bot_iff] exact sInf_le (Eventually.of_forall fun _ => le_rfl) /-- Same as limsup_const applied to `⊤` but without the `NeBot f` assumption -/ @[simp] theorem liminf_const_top {f : Filter β} : liminf (fun _ : β => (⊤ : α)) f = (⊤ : α) := limsup_const_bot (α := αᵒᵈ) theorem HasBasis.limsSup_eq_iInf_sSup {ι} {p : ι → Prop} {s} {f : Filter α} (h : f.HasBasis p s) : limsSup f = ⨅ (i) (_ : p i), sSup (s i) := le_antisymm (le_iInf₂ fun i hi => sInf_le <| h.eventually_iff.2 ⟨i, hi, fun _ => le_sSup⟩) (le_sInf fun _ ha => let ⟨_, hi, ha⟩ := h.eventually_iff.1 ha iInf₂_le_of_le _ hi <| sSup_le ha) theorem HasBasis.limsInf_eq_iSup_sInf {p : ι → Prop} {s : ι → Set α} {f : Filter α} (h : f.HasBasis p s) : limsInf f = ⨆ (i) (_ : p i), sInf (s i) := HasBasis.limsSup_eq_iInf_sSup (α := αᵒᵈ) h theorem limsSup_eq_iInf_sSup {f : Filter α} : limsSup f = ⨅ s ∈ f, sSup s := f.basis_sets.limsSup_eq_iInf_sSup theorem limsInf_eq_iSup_sInf {f : Filter α} : limsInf f = ⨆ s ∈ f, sInf s := limsSup_eq_iInf_sSup (α := αᵒᵈ) theorem limsup_le_iSup {f : Filter β} {u : β → α} : limsup u f ≤ ⨆ n, u n := limsup_le_of_le (by isBoundedDefault) (Eventually.of_forall (le_iSup u)) theorem iInf_le_liminf {f : Filter β} {u : β → α} : ⨅ n, u n ≤ liminf u f := le_liminf_of_le (by isBoundedDefault) (Eventually.of_forall (iInf_le u)) /-- In a complete lattice, the limsup of a function is the infimum over sets `s` in the filter of the supremum of the function over `s` -/ theorem limsup_eq_iInf_iSup {f : Filter β} {u : β → α} : limsup u f = ⨅ s ∈ f, ⨆ a ∈ s, u a := (f.basis_sets.map u).limsSup_eq_iInf_sSup.trans <| by simp only [sSup_image, id] theorem limsup_eq_iInf_iSup_of_nat {u : ℕ → α} : limsup u atTop = ⨅ n : ℕ, ⨆ i ≥ n, u i := (atTop_basis.map u).limsSup_eq_iInf_sSup.trans <| by simp only [sSup_image, iInf_const]; rfl theorem limsup_eq_iInf_iSup_of_nat' {u : ℕ → α} : limsup u atTop = ⨅ n : ℕ, ⨆ i : ℕ, u (i + n) := by simp only [limsup_eq_iInf_iSup_of_nat, iSup_ge_eq_iSup_nat_add] theorem HasBasis.limsup_eq_iInf_iSup {p : ι → Prop} {s : ι → Set β} {f : Filter β} {u : β → α} (h : f.HasBasis p s) : limsup u f = ⨅ (i) (_ : p i), ⨆ a ∈ s i, u a := (h.map u).limsSup_eq_iInf_sSup.trans <| by simp only [sSup_image] lemma limsSup_principal_eq_sSup (s : Set α) : limsSup (𝓟 s) = sSup s := by simpa only [limsSup, eventually_principal] using sInf_upperBounds_eq_csSup s lemma limsInf_principal_eq_sInf (s : Set α) : limsInf (𝓟 s) = sInf s := by simpa only [limsInf, eventually_principal] using sSup_lowerBounds_eq_sInf s @[simp] lemma limsup_top_eq_iSup (u : β → α) : limsup u ⊤ = ⨆ i, u i := by rw [limsup, map_top, limsSup_principal_eq_sSup, sSup_range] @[simp] lemma liminf_top_eq_iInf (u : β → α) : liminf u ⊤ = ⨅ i, u i := by rw [liminf, map_top, limsInf_principal_eq_sInf, sInf_range] theorem blimsup_congr' {f : Filter β} {p q : β → Prop} {u : β → α} (h : ∀ᶠ x in f, u x ≠ ⊥ → (p x ↔ q x)) : blimsup u f p = blimsup u f q := by simp only [blimsup_eq] congr with a refine eventually_congr (h.mono fun b hb => ?_) rcases eq_or_ne (u b) ⊥ with hu | hu; · simp [hu] rw [hb hu] theorem bliminf_congr' {f : Filter β} {p q : β → Prop} {u : β → α} (h : ∀ᶠ x in f, u x ≠ ⊤ → (p x ↔ q x)) : bliminf u f p = bliminf u f q := blimsup_congr' (α := αᵒᵈ) h lemma HasBasis.blimsup_eq_iInf_iSup {p : ι → Prop} {s : ι → Set β} {f : Filter β} {u : β → α} (hf : f.HasBasis p s) {q : β → Prop} : blimsup u f q = ⨅ (i) (_ : p i), ⨆ a ∈ s i, ⨆ (_ : q a), u a := by simp only [blimsup_eq_limsup, (hf.inf_principal _).limsup_eq_iInf_iSup, mem_inter_iff, iSup_and, mem_setOf_eq] theorem blimsup_eq_iInf_biSup {f : Filter β} {p : β → Prop} {u : β → α} : blimsup u f p = ⨅ s ∈ f, ⨆ (b) (_ : p b ∧ b ∈ s), u b := by simp only [f.basis_sets.blimsup_eq_iInf_iSup, iSup_and', id, and_comm] theorem blimsup_eq_iInf_biSup_of_nat {p : ℕ → Prop} {u : ℕ → α} : blimsup u atTop p = ⨅ i, ⨆ (j) (_ : p j ∧ i ≤ j), u j := by simp only [atTop_basis.blimsup_eq_iInf_iSup, @and_comm (p _), iSup_and, mem_Ici, iInf_true] /-- In a complete lattice, the liminf of a function is the infimum over sets `s` in the filter of the supremum of the function over `s` -/ theorem liminf_eq_iSup_iInf {f : Filter β} {u : β → α} : liminf u f = ⨆ s ∈ f, ⨅ a ∈ s, u a := limsup_eq_iInf_iSup (α := αᵒᵈ) theorem liminf_eq_iSup_iInf_of_nat {u : ℕ → α} : liminf u atTop = ⨆ n : ℕ, ⨅ i ≥ n, u i := @limsup_eq_iInf_iSup_of_nat αᵒᵈ _ u theorem liminf_eq_iSup_iInf_of_nat' {u : ℕ → α} : liminf u atTop = ⨆ n : ℕ, ⨅ i : ℕ, u (i + n) := @limsup_eq_iInf_iSup_of_nat' αᵒᵈ _ _ theorem HasBasis.liminf_eq_iSup_iInf {p : ι → Prop} {s : ι → Set β} {f : Filter β} {u : β → α} (h : f.HasBasis p s) : liminf u f = ⨆ (i) (_ : p i), ⨅ a ∈ s i, u a := HasBasis.limsup_eq_iInf_iSup (α := αᵒᵈ) h theorem bliminf_eq_iSup_biInf {f : Filter β} {p : β → Prop} {u : β → α} : bliminf u f p = ⨆ s ∈ f, ⨅ (b) (_ : p b ∧ b ∈ s), u b := @blimsup_eq_iInf_biSup αᵒᵈ β _ f p u theorem bliminf_eq_iSup_biInf_of_nat {p : ℕ → Prop} {u : ℕ → α} : bliminf u atTop p = ⨆ i, ⨅ (j) (_ : p j ∧ i ≤ j), u j := @blimsup_eq_iInf_biSup_of_nat αᵒᵈ _ p u theorem limsup_eq_sInf_sSup {ι R : Type*} (F : Filter ι) [CompleteLattice R] (a : ι → R) : limsup a F = sInf ((fun I => sSup (a '' I)) '' F.sets) := by apply le_antisymm · rw [limsup_eq] refine sInf_le_sInf fun x hx => ?_ rcases (mem_image _ F.sets x).mp hx with ⟨I, ⟨I_mem_F, hI⟩⟩ filter_upwards [I_mem_F] with i hi exact hI ▸ le_sSup (mem_image_of_mem _ hi) · refine le_sInf fun b hb => sInf_le_of_le (mem_image_of_mem _ hb) <| sSup_le ?_ rintro _ ⟨_, h, rfl⟩ exact h theorem liminf_eq_sSup_sInf {ι R : Type*} (F : Filter ι) [CompleteLattice R] (a : ι → R) : liminf a F = sSup ((fun I => sInf (a '' I)) '' F.sets) := @Filter.limsup_eq_sInf_sSup ι (OrderDual R) _ _ a theorem liminf_le_of_frequently_le' {α β} [CompleteLattice β] {f : Filter α} {u : α → β} {x : β} (h : ∃ᶠ a in f, u a ≤ x) : liminf u f ≤ x := by rw [liminf_eq] refine sSup_le fun b hb => ?_ have hbx : ∃ᶠ _ in f, b ≤ x := by revert h rw [← not_imp_not, not_frequently, not_frequently] exact fun h => hb.mp (h.mono fun a hbx hba hax => hbx (hba.trans hax)) exact hbx.exists.choose_spec theorem le_limsup_of_frequently_le' {α β} [CompleteLattice β] {f : Filter α} {u : α → β} {x : β} (h : ∃ᶠ a in f, x ≤ u a) : x ≤ limsup u f := liminf_le_of_frequently_le' (β := βᵒᵈ) h /-- If `f : α → α` is a morphism of complete lattices, then the limsup of its iterates of any `a : α` is a fixed point. -/ @[simp] theorem _root_.CompleteLatticeHom.apply_limsup_iterate (f : CompleteLatticeHom α α) (a : α) : f (limsup (fun n => f^[n] a) atTop) = limsup (fun n => f^[n] a) atTop := by rw [limsup_eq_iInf_iSup_of_nat', map_iInf] simp_rw [_root_.map_iSup, ← Function.comp_apply (f := f), ← Function.iterate_succ' f, ← Nat.add_succ] conv_rhs => rw [iInf_split _ (0 < ·)] simp only [not_lt, Nat.le_zero, iInf_iInf_eq_left, add_zero, iInf_nat_gt_zero_eq, left_eq_inf] refine (iInf_le (fun i => ⨆ j, f^[j + (i + 1)] a) 0).trans ?_ simp only [zero_add, iSup_le_iff] exact fun i => le_iSup (fun i => f^[i] a) (i + 1) /-- If `f : α → α` is a morphism of complete lattices, then the liminf of its iterates of any `a : α` is a fixed point. -/ theorem _root_.CompleteLatticeHom.apply_liminf_iterate (f : CompleteLatticeHom α α) (a : α) : f (liminf (fun n => f^[n] a) atTop) = liminf (fun n => f^[n] a) atTop := (CompleteLatticeHom.dual f).apply_limsup_iterate _ variable {f g : Filter β} {p q : β → Prop} {u v : β → α} theorem blimsup_mono (h : ∀ x, p x → q x) : blimsup u f p ≤ blimsup u f q := sInf_le_sInf fun a ha => ha.mono <| by tauto theorem bliminf_antitone (h : ∀ x, p x → q x) : bliminf u f q ≤ bliminf u f p := sSup_le_sSup fun a ha => ha.mono <| by tauto theorem mono_blimsup' (h : ∀ᶠ x in f, p x → u x ≤ v x) : blimsup u f p ≤ blimsup v f p := sInf_le_sInf fun _ ha => (ha.and h).mono fun _ hx hx' => (hx.2 hx').trans (hx.1 hx') theorem mono_blimsup (h : ∀ x, p x → u x ≤ v x) : blimsup u f p ≤ blimsup v f p := mono_blimsup' <| Eventually.of_forall h theorem mono_bliminf' (h : ∀ᶠ x in f, p x → u x ≤ v x) : bliminf u f p ≤ bliminf v f p := sSup_le_sSup fun _ ha => (ha.and h).mono fun _ hx hx' => (hx.1 hx').trans (hx.2 hx') theorem mono_bliminf (h : ∀ x, p x → u x ≤ v x) : bliminf u f p ≤ bliminf v f p := mono_bliminf' <| Eventually.of_forall h theorem bliminf_antitone_filter (h : f ≤ g) : bliminf u g p ≤ bliminf u f p := sSup_le_sSup fun _ ha => ha.filter_mono h theorem blimsup_monotone_filter (h : f ≤ g) : blimsup u f p ≤ blimsup u g p := sInf_le_sInf fun _ ha => ha.filter_mono h theorem blimsup_and_le_inf : (blimsup u f fun x => p x ∧ q x) ≤ blimsup u f p ⊓ blimsup u f q := le_inf (blimsup_mono <| by tauto) (blimsup_mono <| by tauto) @[simp] theorem bliminf_sup_le_inf_aux_left : (blimsup u f fun x => p x ∧ q x) ≤ blimsup u f p := blimsup_and_le_inf.trans inf_le_left @[simp] theorem bliminf_sup_le_inf_aux_right : (blimsup u f fun x => p x ∧ q x) ≤ blimsup u f q := blimsup_and_le_inf.trans inf_le_right theorem bliminf_sup_le_and : bliminf u f p ⊔ bliminf u f q ≤ bliminf u f fun x => p x ∧ q x := blimsup_and_le_inf (α := αᵒᵈ) @[simp] theorem bliminf_sup_le_and_aux_left : bliminf u f p ≤ bliminf u f fun x => p x ∧ q x := le_sup_left.trans bliminf_sup_le_and @[simp] theorem bliminf_sup_le_and_aux_right : bliminf u f q ≤ bliminf u f fun x => p x ∧ q x := le_sup_right.trans bliminf_sup_le_and /-- See also `Filter.blimsup_or_eq_sup`. -/ theorem blimsup_sup_le_or : blimsup u f p ⊔ blimsup u f q ≤ blimsup u f fun x => p x ∨ q x := sup_le (blimsup_mono <| by tauto) (blimsup_mono <| by tauto) @[simp] theorem bliminf_sup_le_or_aux_left : blimsup u f p ≤ blimsup u f fun x => p x ∨ q x := le_sup_left.trans blimsup_sup_le_or @[simp] theorem bliminf_sup_le_or_aux_right : blimsup u f q ≤ blimsup u f fun x => p x ∨ q x := le_sup_right.trans blimsup_sup_le_or /-- See also `Filter.bliminf_or_eq_inf`. -/ theorem bliminf_or_le_inf : (bliminf u f fun x => p x ∨ q x) ≤ bliminf u f p ⊓ bliminf u f q := blimsup_sup_le_or (α := αᵒᵈ) @[simp] theorem bliminf_or_le_inf_aux_left : (bliminf u f fun x => p x ∨ q x) ≤ bliminf u f p := bliminf_or_le_inf.trans inf_le_left @[simp] theorem bliminf_or_le_inf_aux_right : (bliminf u f fun x => p x ∨ q x) ≤ bliminf u f q := bliminf_or_le_inf.trans inf_le_right theorem _root_.OrderIso.apply_blimsup [CompleteLattice γ] (e : α ≃o γ) : e (blimsup u f p) = blimsup (e ∘ u) f p := by simp only [blimsup_eq, map_sInf, Function.comp_apply, e.image_eq_preimage_symm, Set.preimage_setOf_eq, e.le_symm_apply] theorem _root_.OrderIso.apply_bliminf [CompleteLattice γ] (e : α ≃o γ) : e (bliminf u f p) = bliminf (e ∘ u) f p := e.dual.apply_blimsup theorem _root_.sSupHom.apply_blimsup_le [CompleteLattice γ] (g : sSupHom α γ) : g (blimsup u f p) ≤ blimsup (g ∘ u) f p := by simp only [blimsup_eq_iInf_biSup, Function.comp] refine ((OrderHomClass.mono g).map_iInf₂_le _).trans ?_ simp only [_root_.map_iSup, le_refl] theorem _root_.sInfHom.le_apply_bliminf [CompleteLattice γ] (g : sInfHom α γ) : bliminf (g ∘ u) f p ≤ g (bliminf u f p) := (sInfHom.dual g).apply_blimsup_le end CompleteLattice section CompleteDistribLattice variable [CompleteDistribLattice α] {f : Filter β} {p q : β → Prop} {u : β → α} lemma limsup_sup_filter {g} : limsup u (f ⊔ g) = limsup u f ⊔ limsup u g := by refine le_antisymm ?_ (sup_le (limsup_le_limsup_of_le le_sup_left) (limsup_le_limsup_of_le le_sup_right)) simp_rw [limsup_eq, sInf_sup_eq, sup_sInf_eq, mem_setOf_eq, le_iInf₂_iff] intro a ha b hb exact sInf_le ⟨ha.mono fun _ h ↦ h.trans le_sup_left, hb.mono fun _ h ↦ h.trans le_sup_right⟩ lemma liminf_sup_filter {g} : liminf u (f ⊔ g) = liminf u f ⊓ liminf u g := limsup_sup_filter (α := αᵒᵈ) @[simp] theorem blimsup_or_eq_sup : (blimsup u f fun x => p x ∨ q x) = blimsup u f p ⊔ blimsup u f q := by simp only [blimsup_eq_limsup, ← limsup_sup_filter, ← inf_sup_left, sup_principal, setOf_or] @[simp] theorem bliminf_or_eq_inf : (bliminf u f fun x => p x ∨ q x) = bliminf u f p ⊓ bliminf u f q := blimsup_or_eq_sup (α := αᵒᵈ) @[simp] lemma blimsup_sup_not : blimsup u f p ⊔ blimsup u f (¬p ·) = limsup u f := by simp_rw [← blimsup_or_eq_sup, or_not, blimsup_true] @[simp] lemma bliminf_inf_not : bliminf u f p ⊓ bliminf u f (¬p ·) = liminf u f := blimsup_sup_not (α := αᵒᵈ) @[simp] lemma blimsup_not_sup : blimsup u f (¬p ·) ⊔ blimsup u f p = limsup u f := by simpa only [not_not] using blimsup_sup_not (p := (¬p ·)) @[simp] lemma bliminf_not_inf : bliminf u f (¬p ·) ⊓ bliminf u f p = liminf u f := blimsup_not_sup (α := αᵒᵈ) lemma limsup_piecewise {s : Set β} [DecidablePred (· ∈ s)] {v} : limsup (s.piecewise u v) f = blimsup u f (· ∈ s) ⊔ blimsup v f (· ∉ s) := by rw [← blimsup_sup_not (p := (· ∈ s))] refine congr_arg₂ _ (blimsup_congr ?_) (blimsup_congr ?_) <;> filter_upwards with _ h using by simp [h] lemma liminf_piecewise {s : Set β} [DecidablePred (· ∈ s)] {v} : liminf (s.piecewise u v) f = bliminf u f (· ∈ s) ⊓ bliminf v f (· ∉ s) := limsup_piecewise (α := αᵒᵈ) theorem sup_limsup [NeBot f] (a : α) : a ⊔ limsup u f = limsup (fun x => a ⊔ u x) f := by simp only [limsup_eq_iInf_iSup, iSup_sup_eq, sup_iInf₂_eq] congr; ext s; congr; ext hs; congr exact (biSup_const (nonempty_of_mem hs)).symm theorem inf_liminf [NeBot f] (a : α) : a ⊓ liminf u f = liminf (fun x => a ⊓ u x) f := sup_limsup (α := αᵒᵈ) a theorem sup_liminf (a : α) : a ⊔ liminf u f = liminf (fun x => a ⊔ u x) f := by simp only [liminf_eq_iSup_iInf] rw [sup_comm, biSup_sup (⟨univ, univ_mem⟩ : ∃ i : Set β, i ∈ f)] simp_rw [iInf₂_sup_eq, sup_comm (a := a)] theorem inf_limsup (a : α) : a ⊓ limsup u f = limsup (fun x => a ⊓ u x) f := sup_liminf (α := αᵒᵈ) a end CompleteDistribLattice section CompleteBooleanAlgebra variable [CompleteBooleanAlgebra α] (f : Filter β) (u : β → α) theorem limsup_compl : (limsup u f)ᶜ = liminf (compl ∘ u) f := by simp only [limsup_eq_iInf_iSup, compl_iInf, compl_iSup, liminf_eq_iSup_iInf, Function.comp_apply] theorem liminf_compl : (liminf u f)ᶜ = limsup (compl ∘ u) f := by simp only [limsup_eq_iInf_iSup, compl_iInf, compl_iSup, liminf_eq_iSup_iInf, Function.comp_apply] theorem limsup_sdiff (a : α) : limsup u f \ a = limsup (fun b => u b \ a) f := by simp only [limsup_eq_iInf_iSup, sdiff_eq] rw [biInf_inf (⟨univ, univ_mem⟩ : ∃ i : Set β, i ∈ f)] simp_rw [inf_comm, inf_iSup₂_eq, inf_comm] theorem liminf_sdiff [NeBot f] (a : α) : liminf u f \ a = liminf (fun b => u b \ a) f := by simp only [sdiff_eq, inf_comm _ aᶜ, inf_liminf] theorem sdiff_limsup [NeBot f] (a : α) : a \ limsup u f = liminf (fun b => a \ u b) f := by rw [← compl_inj_iff] simp only [sdiff_eq, liminf_compl, comp_def, compl_inf, compl_compl, sup_limsup] theorem sdiff_liminf (a : α) : a \ liminf u f = limsup (fun b => a \ u b) f := by rw [← compl_inj_iff] simp only [sdiff_eq, limsup_compl, comp_def, compl_inf, compl_compl, sup_liminf] end CompleteBooleanAlgebra section SetLattice variable {p : ι → Prop} {s : ι → Set α} {𝓕 : Filter ι} {a : α} lemma mem_liminf_iff_eventually_mem : (a ∈ liminf s 𝓕) ↔ (∀ᶠ i in 𝓕, a ∈ s i) := by simpa only [liminf_eq_iSup_iInf, iSup_eq_iUnion, iInf_eq_iInter, mem_iUnion, mem_iInter] using ⟨fun ⟨S, hS, hS'⟩ ↦ mem_of_superset hS (by tauto), fun h ↦ ⟨{i | a ∈ s i}, h, by tauto⟩⟩ lemma mem_limsup_iff_frequently_mem : (a ∈ limsup s 𝓕) ↔ (∃ᶠ i in 𝓕, a ∈ s i) := by simp only [Filter.Frequently, iff_not_comm, ← mem_compl_iff, limsup_compl, comp_apply, mem_liminf_iff_eventually_mem] theorem cofinite.blimsup_set_eq : blimsup s cofinite p = { x | { n | p n ∧ x ∈ s n }.Infinite } := by simp only [blimsup_eq, le_eq_subset, eventually_cofinite, not_forall, sInf_eq_sInter, exists_prop] ext x refine ⟨fun h => ?_, fun hx t h => ?_⟩ <;> contrapose! h · simp only [mem_sInter, mem_setOf_eq, not_forall, exists_prop] exact ⟨{x}ᶜ, by simpa using h, by simp⟩ · exact hx.mono fun i hi => ⟨hi.1, fun hit => h (hit hi.2)⟩ theorem cofinite.bliminf_set_eq : bliminf s cofinite p = { x | { n | p n ∧ x ∉ s n }.Finite } := by rw [← compl_inj_iff] simp only [bliminf_eq_iSup_biInf, compl_iInf, compl_iSup, ← blimsup_eq_iInf_biSup, cofinite.blimsup_set_eq] rfl /-- In other words, `limsup cofinite s` is the set of elements lying inside the family `s` infinitely often. -/ theorem cofinite.limsup_set_eq : limsup s cofinite = { x | { n | x ∈ s n }.Infinite } := by simp only [← cofinite.blimsup_true s, cofinite.blimsup_set_eq, true_and] /-- In other words, `liminf cofinite s` is the set of elements lying outside the family `s` finitely often. -/ theorem cofinite.liminf_set_eq : liminf s cofinite = { x | { n | x ∉ s n }.Finite } := by simp only [← cofinite.bliminf_true s, cofinite.bliminf_set_eq, true_and] theorem exists_forall_mem_of_hasBasis_mem_blimsup {l : Filter β} {b : ι → Set β} {q : ι → Prop} (hl : l.HasBasis q b) {u : β → Set α} {p : β → Prop} {x : α} (hx : x ∈ blimsup u l p) : ∃ f : { i | q i } → β, ∀ i, x ∈ u (f i) ∧ p (f i) ∧ f i ∈ b i := by rw [blimsup_eq_iInf_biSup] at hx simp only [iSup_eq_iUnion, iInf_eq_iInter, mem_iInter, mem_iUnion, exists_prop] at hx choose g hg hg' using hx refine ⟨fun i : { i | q i } => g (b i) (hl.mem_of_mem i.2), fun i => ⟨?_, ?_⟩⟩ · exact hg' (b i) (hl.mem_of_mem i.2) · exact hg (b i) (hl.mem_of_mem i.2) theorem exists_forall_mem_of_hasBasis_mem_blimsup' {l : Filter β} {b : ι → Set β} (hl : l.HasBasis (fun _ => True) b) {u : β → Set α} {p : β → Prop} {x : α} (hx : x ∈ blimsup u l p) : ∃ f : ι → β, ∀ i, x ∈ u (f i) ∧ p (f i) ∧ f i ∈ b i := by obtain ⟨f, hf⟩ := exists_forall_mem_of_hasBasis_mem_blimsup hl hx exact ⟨fun i => f ⟨i, trivial⟩, fun i => hf ⟨i, trivial⟩⟩ end SetLattice section ConditionallyCompleteLinearOrder theorem frequently_lt_of_lt_limsSup {f : Filter α} [ConditionallyCompleteLinearOrder α] {a : α} (hf : f.IsCobounded (· ≤ ·) := by isBoundedDefault) (h : a < limsSup f) : ∃ᶠ n in f, a < n := by contrapose! h simp only [not_frequently, not_lt] at h exact limsSup_le_of_le hf h theorem frequently_lt_of_limsInf_lt {f : Filter α} [ConditionallyCompleteLinearOrder α] {a : α} (hf : f.IsCobounded (· ≥ ·) := by isBoundedDefault) (h : limsInf f < a) : ∃ᶠ n in f, n < a := frequently_lt_of_lt_limsSup (α := OrderDual α) hf h theorem eventually_lt_of_lt_liminf {f : Filter α} [ConditionallyCompleteLinearOrder β] {u : α → β} {b : β} (h : b < liminf u f) (hu : f.IsBoundedUnder (· ≥ ·) u := by isBoundedDefault) : ∀ᶠ a in f, b < u a := by obtain ⟨c, hc, hbc⟩ : ∃ (c : β) (_ : c ∈ { c : β | ∀ᶠ n : α in f, c ≤ u n }), b < c := by simp_rw [exists_prop] exact exists_lt_of_lt_csSup hu h exact hc.mono fun x hx => lt_of_lt_of_le hbc hx theorem eventually_lt_of_limsup_lt {f : Filter α} [ConditionallyCompleteLinearOrder β] {u : α → β} {b : β} (h : limsup u f < b) (hu : f.IsBoundedUnder (· ≤ ·) u := by isBoundedDefault) : ∀ᶠ a in f, u a < b := eventually_lt_of_lt_liminf (β := βᵒᵈ) h hu section ConditionallyCompleteLinearOrder variable [ConditionallyCompleteLinearOrder α] /-- If `Filter.limsup u atTop ≤ x`, then for all `ε > 0`, eventually we have `u b < x + ε`. -/ theorem eventually_lt_add_pos_of_limsup_le [Preorder β] [AddZeroClass α] [AddLeftStrictMono α] {x ε : α} {u : β → α} (hu_bdd : IsBoundedUnder LE.le atTop u) (hu : Filter.limsup u atTop ≤ x) (hε : 0 < ε) : ∀ᶠ b : β in atTop, u b < x + ε := eventually_lt_of_limsup_lt (lt_of_le_of_lt hu (lt_add_of_pos_right x hε)) hu_bdd /-- If `x ≤ Filter.liminf u atTop`, then for all `ε < 0`, eventually we have `x + ε < u b`. -/ theorem eventually_add_neg_lt_of_le_liminf [Preorder β] [AddZeroClass α] [AddLeftStrictMono α] {x ε : α} {u : β → α} (hu_bdd : IsBoundedUnder GE.ge atTop u) (hu : x ≤ Filter.liminf u atTop) (hε : ε < 0) : ∀ᶠ b : β in atTop, x + ε < u b := eventually_lt_of_lt_liminf (lt_of_lt_of_le (add_lt_of_neg_right x hε) hu) hu_bdd /-- If `Filter.limsup u atTop ≤ x`, then for all `ε > 0`, there exists a positive natural number `n` such that `u n < x + ε`. -/ theorem exists_lt_of_limsup_le [AddZeroClass α] [AddLeftStrictMono α] {x ε : α} {u : ℕ → α} (hu_bdd : IsBoundedUnder LE.le atTop u) (hu : Filter.limsup u atTop ≤ x) (hε : 0 < ε) : ∃ n : PNat, u n < x + ε := by have h : ∀ᶠ n : ℕ in atTop, u n < x + ε := eventually_lt_add_pos_of_limsup_le hu_bdd hu hε simp only [eventually_atTop] at h obtain ⟨n, hn⟩ := h exact ⟨⟨n + 1, Nat.succ_pos _⟩, hn (n + 1) (Nat.le_succ _)⟩ /-- If `x ≤ Filter.liminf u atTop`, then for all `ε < 0`, there exists a positive natural number `n` such that ` x + ε < u n`. -/ theorem exists_lt_of_le_liminf [AddZeroClass α] [AddLeftStrictMono α] {x ε : α} {u : ℕ → α} (hu_bdd : IsBoundedUnder GE.ge atTop u) (hu : x ≤ Filter.liminf u atTop) (hε : ε < 0) : ∃ n : PNat, x + ε < u n := by have h : ∀ᶠ n : ℕ in atTop, x + ε < u n := eventually_add_neg_lt_of_le_liminf hu_bdd hu hε simp only [eventually_atTop] at h obtain ⟨n, hn⟩ := h exact ⟨⟨n + 1, Nat.succ_pos _⟩, hn (n + 1) (Nat.le_succ _)⟩ end ConditionallyCompleteLinearOrder variable [ConditionallyCompleteLinearOrder β] {f : Filter α} {u : α → β} theorem le_limsup_of_frequently_le {b : β} (hu_le : ∃ᶠ x in f, b ≤ u x) (hu : f.IsBoundedUnder (· ≤ ·) u := by isBoundedDefault) : b ≤ limsup u f := by revert hu_le rw [← not_imp_not, not_frequently] simp_rw [← lt_iff_not_ge] exact fun h => eventually_lt_of_limsup_lt h hu theorem liminf_le_of_frequently_le {b : β} (hu_le : ∃ᶠ x in f, u x ≤ b) (hu : f.IsBoundedUnder (· ≥ ·) u := by isBoundedDefault) : liminf u f ≤ b := le_limsup_of_frequently_le (β := βᵒᵈ) hu_le hu theorem frequently_lt_of_lt_limsup {b : β} (hu : f.IsCoboundedUnder (· ≤ ·) u := by isBoundedDefault) (h : b < limsup u f) : ∃ᶠ x in f, b < u x := by contrapose! h apply limsSup_le_of_le hu simpa using h theorem frequently_lt_of_liminf_lt {b : β} (hu : f.IsCoboundedUnder (· ≥ ·) u := by isBoundedDefault) (h : liminf u f < b) : ∃ᶠ x in f, u x < b := frequently_lt_of_lt_limsup (β := βᵒᵈ) hu h theorem limsup_le_iff {x : β} (h₁ : f.IsCoboundedUnder (· ≤ ·) u := by isBoundedDefault) (h₂ : f.IsBoundedUnder (· ≤ ·) u := by isBoundedDefault) : limsup u f ≤ x ↔ ∀ y > x, ∀ᶠ a in f, u a < y := by refine ⟨fun h _ h' ↦ eventually_lt_of_limsup_lt (h.trans_lt h') h₂, fun h ↦ ?_⟩ --Two cases: Either `x` is a cluster point from above, or it is not. --In the first case, we use `forall_gt_iff_le` and split an interval. --In the second case, the function `u` must eventually be smaller or equal to `x`. by_cases h' : ∀ y > x, ∃ z, x < z ∧ z < y · rw [← forall_gt_iff_le] intro y x_y rcases h' y x_y with ⟨z, x_z, z_y⟩ exact (limsup_le_of_le h₁ ((h z x_z).mono (fun _ ↦ le_of_lt))).trans_lt z_y · apply limsup_le_of_le h₁ set_option push_neg.use_distrib true in push_neg at h' rcases h' with ⟨z, x_z, hz⟩ exact (h z x_z).mono <| fun w hw ↦ (or_iff_left (not_le_of_gt hw)).1 (hz (u w)) /- A version of `limsup_le_iff` with large inequalities in densely ordered spaces.-/ lemma limsup_le_iff' [DenselyOrdered β] {x : β} (h₁ : IsCoboundedUnder (· ≤ ·) f u := by isBoundedDefault) (h₂ : IsBoundedUnder (· ≤ ·) f u := by isBoundedDefault) : limsup u f ≤ x ↔ ∀ y > x, ∀ᶠ (a : α) in f, u a ≤ y := by refine ⟨fun h _ h' ↦ (eventually_lt_of_limsup_lt (h.trans_lt h') h₂).mono fun _ ↦ le_of_lt, ?_⟩ rw [← forall_gt_iff_le] intro h y x_y obtain ⟨z, x_z, z_y⟩ := exists_between x_y exact (limsup_le_of_le h₁ (h z x_z)).trans_lt z_y theorem le_limsup_iff {x : β} (h₁ : f.IsCoboundedUnder (· ≤ ·) u := by isBoundedDefault) (h₂ : f.IsBoundedUnder (· ≤ ·) u := by isBoundedDefault) : x ≤ limsup u f ↔ ∀ y < x, ∃ᶠ a in f, y < u a := by refine ⟨fun h _ h' ↦ frequently_lt_of_lt_limsup h₁ (h'.trans_le h), fun h ↦ ?_⟩ --Two cases: Either `x` is a cluster point from below, or it is not. --In the first case, we use `forall_lt_iff_le` and split an interval. --In the second case, the function `u` must frequently be larger or equal to `x`. by_cases h' : ∀ y < x, ∃ z, y < z ∧ z < x · rw [← forall_lt_iff_le] intro y y_x obtain ⟨z, y_z, z_x⟩ := h' y y_x exact y_z.trans_le (le_limsup_of_frequently_le ((h z z_x).mono (fun _ ↦ le_of_lt)) h₂) · apply le_limsup_of_frequently_le _ h₂ set_option push_neg.use_distrib true in push_neg at h' rcases h' with ⟨z, z_x, hz⟩ exact (h z z_x).mono <| fun w hw ↦ (or_iff_right (not_le_of_gt hw)).1 (hz (u w)) /- A version of `le_limsup_iff` with large inequalities in densely ordered spaces.-/ lemma le_limsup_iff' [DenselyOrdered β] {x : β} (h₁ : f.IsCoboundedUnder (· ≤ ·) u := by isBoundedDefault) (h₂ : f.IsBoundedUnder (· ≤ ·) u := by isBoundedDefault) : x ≤ limsup u f ↔ ∀ y < x, ∃ᶠ a in f, y ≤ u a := by refine ⟨fun h _ h' ↦ (frequently_lt_of_lt_limsup h₁ (h'.trans_le h)).mono fun _ ↦ le_of_lt, ?_⟩ rw [← forall_lt_iff_le] intro h y y_x obtain ⟨z, y_z, z_x⟩ := exists_between y_x exact y_z.trans_le (le_limsup_of_frequently_le (h z z_x) h₂) theorem le_liminf_iff {x : β} (h₁ : f.IsCoboundedUnder (· ≥ ·) u := by isBoundedDefault) (h₂ : f.IsBoundedUnder (· ≥ ·) u := by isBoundedDefault) : x ≤ liminf u f ↔ ∀ y < x, ∀ᶠ a in f, y < u a := limsup_le_iff (β := βᵒᵈ) h₁ h₂ /- A version of `le_liminf_iff` with large inequalities in densely ordered spaces.-/ theorem le_liminf_iff' [DenselyOrdered β] {x : β} (h₁ : f.IsCoboundedUnder (· ≥ ·) u := by isBoundedDefault) (h₂ : f.IsBoundedUnder (· ≥ ·) u := by isBoundedDefault) : x ≤ liminf u f ↔ ∀ y < x, ∀ᶠ a in f, y ≤ u a := limsup_le_iff' (β := βᵒᵈ) h₁ h₂ theorem liminf_le_iff {x : β} (h₁ : f.IsCoboundedUnder (· ≥ ·) u := by isBoundedDefault) (h₂ : f.IsBoundedUnder (· ≥ ·) u := by isBoundedDefault) : liminf u f ≤ x ↔ ∀ y > x, ∃ᶠ a in f, u a < y := le_limsup_iff (β := βᵒᵈ) h₁ h₂ /- A version of `liminf_le_iff` with large inequalities in densely ordered spaces.-/ theorem liminf_le_iff' [DenselyOrdered β] {x : β} (h₁ : f.IsCoboundedUnder (· ≥ ·) u := by isBoundedDefault) (h₂ : f.IsBoundedUnder (· ≥ ·) u := by isBoundedDefault) : liminf u f ≤ x ↔ ∀ y > x, ∃ᶠ a in f, u a ≤ y := le_limsup_iff' (β := βᵒᵈ) h₁ h₂ lemma liminf_le_limsup_of_frequently_le {v : α → β} (h : ∃ᶠ x in f, u x ≤ v x) (h₁ : f.IsBoundedUnder (· ≥ ·) u := by isBoundedDefault) (h₂ : f.IsBoundedUnder (· ≤ ·) v := by isBoundedDefault) : liminf u f ≤ limsup v f := by rcases f.eq_or_neBot with rfl | _ · exact (frequently_bot h).rec have h₃ : f.IsCoboundedUnder (· ≥ ·) u := by obtain ⟨a, ha⟩ := h₂.eventually_le apply IsCoboundedUnder.of_frequently_le (a := a) exact (h.and_eventually ha).mono fun x ⟨u_x, v_x⟩ ↦ u_x.trans v_x have h₄ : f.IsCoboundedUnder (· ≤ ·) v := by obtain ⟨a, ha⟩ := h₁.eventually_ge apply IsCoboundedUnder.of_frequently_ge (a := a) exact (ha.and_frequently h).mono fun x ⟨u_x, v_x⟩ ↦ u_x.trans v_x refine (le_limsup_iff h₄ h₂).2 fun y y_v ↦ ?_ have := (le_liminf_iff h₃ h₁).1 (le_refl (liminf u f)) y y_v exact (h.and_eventually this).mono fun x ⟨ux_vx, y_ux⟩ ↦ y_ux.trans_le ux_vx variable [ConditionallyCompleteLinearOrder α] {f : Filter α} {b : α} -- The linter erroneously claims that I'm not referring to `c` set_option linter.unusedVariables false in theorem lt_mem_sets_of_limsSup_lt (h : f.IsBounded (· ≤ ·)) (l : f.limsSup < b) : ∀ᶠ a in f, a < b := let ⟨c, (h : ∀ᶠ a in f, a ≤ c), hcb⟩ := exists_lt_of_csInf_lt h l mem_of_superset h fun _a => hcb.trans_le' theorem gt_mem_sets_of_limsInf_gt : f.IsBounded (· ≥ ·) → b < f.limsInf → ∀ᶠ a in f, b < a := @lt_mem_sets_of_limsSup_lt αᵒᵈ _ _ _ section Classical open Classical in /-- Given an indexed family of sets `s j` over `j : Subtype p` and a function `f`, then `liminf_reparam j` is equal to `j` if `f` is bounded below on `s j`, and otherwise to some index `k` such that `f` is bounded below on `s k` (if there exists one). To ensure good measurability behavior, this index `k` is chosen as the minimal suitable index. This function is used to write down a liminf in a measurable way, in `Filter.HasBasis.liminf_eq_ciSup_ciInf` and `Filter.HasBasis.liminf_eq_ite`. -/ noncomputable def liminf_reparam (f : ι → α) (s : ι' → Set ι) (p : ι' → Prop) [Countable (Subtype p)] [Nonempty (Subtype p)] (j : Subtype p) : Subtype p := let m : Set (Subtype p) := {j | BddBelow (range (fun (i : s j) ↦ f i))} let g : ℕ → Subtype p := (exists_surjective_nat _).choose have Z : ∃ n, g n ∈ m ∨ ∀ j, j ∉ m := by by_cases! H : ∃ j, j ∈ m · rcases H with ⟨j, hj⟩ rcases (exists_surjective_nat (Subtype p)).choose_spec j with ⟨n, rfl⟩ exact ⟨n, Or.inl hj⟩ · exact ⟨0, Or.inr H⟩ if j ∈ m then j else g (Nat.find Z) /-- Writing a liminf as a supremum of infimum, in a (possibly non-complete) conditionally complete linear order. A reparametrization trick is needed to avoid taking the infimum of sets which are not bounded below. -/ theorem HasBasis.liminf_eq_ciSup_ciInf {v : Filter ι} {p : ι' → Prop} {s : ι' → Set ι} [Countable (Subtype p)] [Nonempty (Subtype p)] (hv : v.HasBasis p s) {f : ι → α} (hs : ∀ (j : Subtype p), (s j).Nonempty) (H : ∃ (j : Subtype p), BddBelow (range (fun (i : s j) ↦ f i))) : liminf f v = ⨆ (j : Subtype p), ⨅ (i : s (liminf_reparam f s p j)), f i := by classical rcases H with ⟨j0, hj0⟩ let m : Set (Subtype p) := {j | BddBelow (range (fun (i : s j) ↦ f i))} have : ∀ (j : Subtype p), Nonempty (s j) := fun j ↦ Nonempty.coe_sort (hs j) have A : ⋃ (j : Subtype p), ⋂ (i : s j), Iic (f i) = ⋃ (j : Subtype p), ⋂ (i : s (liminf_reparam f s p j)), Iic (f i) := by apply Subset.antisymm · apply iUnion_subset (fun j ↦ ?_) by_cases hj : j ∈ m · have : j = liminf_reparam f s p j := by simp only [m, liminf_reparam, hj, ite_true] conv_lhs => rw [this] apply subset_iUnion _ j · simp only [m, mem_setOf_eq, ← nonempty_iInter_Iic_iff, not_nonempty_iff_eq_empty] at hj simp only [hj, empty_subset] · apply iUnion_subset (fun j ↦ ?_) exact subset_iUnion (fun (k : Subtype p) ↦ (⋂ (i : s k), Iic (f i))) (liminf_reparam f s p j) have B : ∀ (j : Subtype p), ⋂ (i : s (liminf_reparam f s p j)), Iic (f i) = Iic (⨅ (i : s (liminf_reparam f s p j)), f i) := by intro j apply (Iic_ciInf _).symm change liminf_reparam f s p j ∈ m by_cases Hj : j ∈ m · simpa only [m, liminf_reparam, if_pos Hj] using Hj · simp only [m, liminf_reparam, if_neg Hj] have Z : ∃ n, (exists_surjective_nat (Subtype p)).choose n ∈ m ∨ ∀ j, j ∉ m := by rcases (exists_surjective_nat (Subtype p)).choose_spec j0 with ⟨n, rfl⟩ exact ⟨n, Or.inl hj0⟩ rcases Nat.find_spec Z with hZ|hZ · exact hZ · exact (hZ j0 hj0).elim simp_rw [hv.liminf_eq_sSup_iUnion_iInter, A, B, sSup_iUnion_Iic] open Classical in /-- Writing a liminf as a supremum of infimum, in a (possibly non-complete) conditionally complete linear order. A reparametrization trick is needed to avoid taking the infimum of sets which are not bounded below. -/ theorem HasBasis.liminf_eq_ite {v : Filter ι} {p : ι' → Prop} {s : ι' → Set ι} [Countable (Subtype p)] [Nonempty (Subtype p)] (hv : v.HasBasis p s) (f : ι → α) : liminf f v = if ∃ (j : Subtype p), s j = ∅ then sSup univ else if ∀ (j : Subtype p), ¬BddBelow (range (fun (i : s j) ↦ f i)) then sSup ∅ else ⨆ (j : Subtype p), ⨅ (i : s (liminf_reparam f s p j)), f i := by by_cases H : ∃ (j : Subtype p), s j = ∅ · rw [if_pos H] rcases H with ⟨j, hj⟩ simp [hv.liminf_eq_sSup_univ_of_empty j j.2 hj] rw [if_neg H] by_cases H' : ∀ (j : Subtype p), ¬BddBelow (range (fun (i : s j) ↦ f i)) · have A : ∀ (j : Subtype p), ⋂ (i : s j), Iic (f i) = ∅ := by simp_rw [← not_nonempty_iff_eq_empty, nonempty_iInter_Iic_iff] exact H' simp_rw [if_pos H', hv.liminf_eq_sSup_iUnion_iInter, A, iUnion_empty] rw [if_neg H'] apply hv.liminf_eq_ciSup_ciInf · push_neg at H simpa only [nonempty_iff_ne_empty] using H · push_neg at H' exact H' /-- Given an indexed family of sets `s j` and a function `f`, then `limsup_reparam j` is equal to `j` if `f` is bounded above on `s j`, and otherwise to some index `k` such that `f` is bounded above on `s k` (if there exists one). To ensure good measurability behavior, this index `k` is chosen as the minimal suitable index. This function is used to write down a limsup in a measurable way, in `Filter.HasBasis.limsup_eq_ciInf_ciSup` and `Filter.HasBasis.limsup_eq_ite`. -/ noncomputable def limsup_reparam (f : ι → α) (s : ι' → Set ι) (p : ι' → Prop) [Countable (Subtype p)] [Nonempty (Subtype p)] (j : Subtype p) : Subtype p := liminf_reparam (α := αᵒᵈ) f s p j /-- Writing a limsup as an infimum of supremum, in a (possibly non-complete) conditionally complete linear order. A reparametrization trick is needed to avoid taking the supremum of sets which are not bounded above. -/ theorem HasBasis.limsup_eq_ciInf_ciSup {v : Filter ι} {p : ι' → Prop} {s : ι' → Set ι} [Countable (Subtype p)] [Nonempty (Subtype p)] (hv : v.HasBasis p s) {f : ι → α} (hs : ∀ (j : Subtype p), (s j).Nonempty) (H : ∃ (j : Subtype p), BddAbove (range (fun (i : s j) ↦ f i))) : limsup f v = ⨅ (j : Subtype p), ⨆ (i : s (limsup_reparam f s p j)), f i := HasBasis.liminf_eq_ciSup_ciInf (α := αᵒᵈ) hv hs H open Classical in /-- Writing a limsup as an infimum of supremum, in a (possibly non-complete) conditionally complete linear order. A reparametrization trick is needed to avoid taking the supremum of sets which are not bounded below. -/ theorem HasBasis.limsup_eq_ite {v : Filter ι} {p : ι' → Prop} {s : ι' → Set ι} [Countable (Subtype p)] [Nonempty (Subtype p)] (hv : v.HasBasis p s) (f : ι → α) : limsup f v = if ∃ (j : Subtype p), s j = ∅ then sInf univ else if ∀ (j : Subtype p), ¬BddAbove (range (fun (i : s j) ↦ f i)) then sInf ∅ else ⨅ (j : Subtype p), ⨆ (i : s (limsup_reparam f s p j)), f i := HasBasis.liminf_eq_ite (α := αᵒᵈ) hv f end Classical end ConditionallyCompleteLinearOrder end Filter section Order theorem GaloisConnection.l_limsup_le [ConditionallyCompleteLattice β] [ConditionallyCompleteLattice γ] {f : Filter α} {v : α → β} {l : β → γ} {u : γ → β} (gc : GaloisConnection l u) (hlv : f.IsBoundedUnder (· ≤ ·) fun x => l (v x) := by isBoundedDefault) (hv_co : f.IsCoboundedUnder (· ≤ ·) v := by isBoundedDefault) : l (limsup v f) ≤ limsup (fun x => l (v x)) f := by refine le_limsSup_of_le hlv fun c hc => ?_ rw [Filter.eventually_map] at hc simp_rw [gc _ _] at hc ⊢ exact limsSup_le_of_le hv_co hc theorem OrderIso.limsup_apply {γ} [ConditionallyCompleteLattice β] [ConditionallyCompleteLattice γ] {f : Filter α} {u : α → β} (g : β ≃o γ) (hu : f.IsBoundedUnder (· ≤ ·) u := by isBoundedDefault) (hu_co : f.IsCoboundedUnder (· ≤ ·) u := by isBoundedDefault) (hgu : f.IsBoundedUnder (· ≤ ·) fun x => g (u x) := by isBoundedDefault) (hgu_co : f.IsCoboundedUnder (· ≤ ·) fun x => g (u x) := by isBoundedDefault) : g (limsup u f) = limsup (fun x => g (u x)) f := by refine le_antisymm ((OrderIso.to_galoisConnection g).l_limsup_le hgu hu_co) ?_ rw [← g.symm.symm_apply_apply <| limsup (fun x => g (u x)) f, g.symm_symm] refine g.monotone ?_ have hf : u = fun i => g.symm (g (u i)) := funext fun i => (g.symm_apply_apply (u i)).symm nth_rw 2 [hf] refine (OrderIso.to_galoisConnection g.symm).l_limsup_le ?_ hgu_co simp_rw [g.symm_apply_apply] exact hu theorem OrderIso.liminf_apply {γ} [ConditionallyCompleteLattice β] [ConditionallyCompleteLattice γ] {f : Filter α} {u : α → β} (g : β ≃o γ) (hu : f.IsBoundedUnder (· ≥ ·) u := by isBoundedDefault) (hu_co : f.IsCoboundedUnder (· ≥ ·) u := by isBoundedDefault) (hgu : f.IsBoundedUnder (· ≥ ·) fun x => g (u x) := by isBoundedDefault) (hgu_co : f.IsCoboundedUnder (· ≥ ·) fun x => g (u x) := by isBoundedDefault) : g (liminf u f) = liminf (fun x => g (u x)) f := OrderIso.limsup_apply (β := βᵒᵈ) (γ := γᵒᵈ) g.dual hu hu_co hgu hgu_co end Order section MinMax open Filter theorem limsup_max [ConditionallyCompleteLinearOrder β] {f : Filter α} {u v : α → β} (h₁ : f.IsCoboundedUnder (· ≤ ·) u := by isBoundedDefault) (h₂ : f.IsCoboundedUnder (· ≤ ·) v := by isBoundedDefault) (h₃ : f.IsBoundedUnder (· ≤ ·) u := by isBoundedDefault) (h₄ : f.IsBoundedUnder (· ≤ ·) v := by isBoundedDefault) : limsup (fun a ↦ max (u a) (v a)) f = max (limsup u f) (limsup v f) := by have bddmax := IsBoundedUnder.sup h₃ h₄ have cobddmax := isCoboundedUnder_le_max (v := v) (Or.inl h₁) apply le_antisymm · refine (limsup_le_iff cobddmax bddmax).2 (fun b hb ↦ ?_) have hu := eventually_lt_of_limsup_lt (lt_of_le_of_lt (le_max_left _ _) hb) h₃ have hv := eventually_lt_of_limsup_lt (lt_of_le_of_lt (le_max_right _ _) hb) h₄ refine mem_of_superset (inter_mem hu hv) (fun _ ↦ by simp) · exact max_le (c := limsup (fun a ↦ max (u a) (v a)) f) (limsup_le_limsup (Eventually.of_forall (fun a : α ↦ le_max_left (u a) (v a))) h₁ bddmax) (limsup_le_limsup (Eventually.of_forall (fun a : α ↦ le_max_right (u a) (v a))) h₂ bddmax) theorem liminf_min [ConditionallyCompleteLinearOrder β] {f : Filter α} {u v : α → β} (h₁ : f.IsCoboundedUnder (· ≥ ·) u := by isBoundedDefault) (h₂ : f.IsCoboundedUnder (· ≥ ·) v := by isBoundedDefault) (h₃ : f.IsBoundedUnder (· ≥ ·) u := by isBoundedDefault) (h₄ : f.IsBoundedUnder (· ≥ ·) v := by isBoundedDefault) : liminf (fun a ↦ min (u a) (v a)) f = min (liminf u f) (liminf v f) := limsup_max (β := βᵒᵈ) h₁ h₂ h₃ h₄ open Finset theorem limsup_finset_sup' [ConditionallyCompleteLinearOrder β] {f : Filter α} {F : ι → α → β} {s : Finset ι} (hs : s.Nonempty) (h₁ : ∀ i ∈ s, f.IsCoboundedUnder (· ≤ ·) (F i) := by exact fun _ _ ↦ by isBoundedDefault) (h₂ : ∀ i ∈ s, f.IsBoundedUnder (· ≤ ·) (F i) := by exact fun _ _ ↦ by isBoundedDefault) : limsup (fun a ↦ sup' s hs (fun i ↦ F i a)) f = sup' s hs (fun i ↦ limsup (F i) f) := by have bddsup := isBoundedUnder_le_finset_sup' hs h₂ apply le_antisymm · have h₃ : ∃ i ∈ s, f.IsCoboundedUnder (· ≤ ·) (F i) := by rcases hs with ⟨i, i_s⟩ use i, i_s exact h₁ i i_s have cobddsup := isCoboundedUnder_le_finset_sup' hs h₃ refine (limsup_le_iff cobddsup bddsup).2 (fun b hb ↦ ?_) rw [eventually_iff_exists_mem] use ⋂ i ∈ s, {a | F i a < b} split_ands · rw [biInter_finset_mem] suffices key : ∀ i ∈ s, ∀ᶠ a in f, F i a < b from fun i i_s ↦ eventually_iff.1 (key i i_s) intro i i_s apply eventually_lt_of_limsup_lt _ (h₂ i i_s) exact lt_of_le_of_lt (Finset.le_sup' (f := fun i ↦ limsup (F i) f) i_s) hb · simp only [mem_iInter, mem_setOf_eq, sup'_lt_iff, imp_self, implies_true] · apply Finset.sup'_le hs (fun i ↦ limsup (F i) f) refine fun i i_s ↦ limsup_le_limsup (Eventually.of_forall (fun a ↦ ?_)) (h₁ i i_s) bddsup simp only [le_sup'_iff] use i, i_s theorem limsup_finset_sup [ConditionallyCompleteLinearOrder β] [OrderBot β] {f : Filter α} {F : ι → α → β} {s : Finset ι} (h₁ : ∀ i ∈ s, f.IsCoboundedUnder (· ≤ ·) (F i) := by exact fun _ _ ↦ by isBoundedDefault) (h₂ : ∀ i ∈ s, f.IsBoundedUnder (· ≤ ·) (F i) := by exact fun _ _ ↦ by isBoundedDefault) : limsup (fun a ↦ sup s (fun i ↦ F i a)) f = sup s (fun i ↦ limsup (F i) f) := by rcases eq_or_neBot f with (rfl | _) · simp [limsup_eq, csInf_univ] rcases Finset.eq_empty_or_nonempty s with (rfl | s_nemp) · simp only [sup_empty, limsup_const] rw [← Finset.sup'_eq_sup s_nemp fun i ↦ limsup (F i) f, ← limsup_finset_sup' s_nemp h₁ h₂] congr ext a exact Eq.symm (Finset.sup'_eq_sup s_nemp (fun i ↦ F i a)) theorem liminf_finset_inf' [ConditionallyCompleteLinearOrder β] {f : Filter α} {F : ι → α → β} {s : Finset ι} (hs : s.Nonempty) (h₁ : ∀ i ∈ s, f.IsCoboundedUnder (· ≥ ·) (F i) := by exact fun _ _ ↦ by isBoundedDefault) (h₂ : ∀ i ∈ s, f.IsBoundedUnder (· ≥ ·) (F i) := by exact fun _ _ ↦ by isBoundedDefault) : liminf (fun a ↦ inf' s hs (fun i ↦ F i a)) f = inf' s hs (fun i ↦ liminf (F i) f) := limsup_finset_sup' (β := βᵒᵈ) hs h₁ h₂ theorem liminf_finset_inf [ConditionallyCompleteLinearOrder β] [OrderTop β] {f : Filter α} {F : ι → α → β} {s : Finset ι} (h₁ : ∀ i ∈ s, f.IsCoboundedUnder (· ≥ ·) (F i) := by exact fun _ _ ↦ by isBoundedDefault) (h₂ : ∀ i ∈ s, f.IsBoundedUnder (· ≥ ·) (F i) := by exact fun _ _ ↦ by isBoundedDefault) : liminf (fun a ↦ inf s (fun i ↦ F i a)) f = inf s (fun i ↦ liminf (F i) f) := limsup_finset_sup (β := βᵒᵈ) h₁ h₂ end MinMax
.lake/packages/mathlib/Mathlib/Order/Antichain.lean
import Mathlib.Order.Bounds.Basic import Mathlib.Order.Preorder.Chain /-! # Antichains This file defines antichains. An antichain is a set where any two distinct elements are not related. If the relation is `(≤)`, this corresponds to incomparability and usual order antichains. If the relation is `G.Adj` for `G : SimpleGraph α`, this corresponds to independent sets of `G`. ## Definitions * `IsAntichain r s`: Any two elements of `s : Set α` are unrelated by `r : α → α → Prop`. * `IsStrongAntichain r s`: Any two elements of `s : Set α` are not related by `r : α → α → Prop` to a common element. * `IsMaxAntichain r s`: An antichain such that no antichain strictly including `s` exists. -/ assert_not_exists CompleteLattice open Function Set section General variable {α β : Type*} {r r₁ r₂ : α → α → Prop} {r' : β → β → Prop} {s t : Set α} {a b : α} protected theorem Symmetric.compl (h : Symmetric r) : Symmetric rᶜ := fun _ _ hr hr' => hr <| h hr' /-- An antichain is a set such that no two distinct elements are related. -/ def IsAntichain (r : α → α → Prop) (s : Set α) : Prop := s.Pairwise rᶜ namespace IsAntichain @[simp] protected theorem empty : IsAntichain r ∅ := pairwise_empty _ @[simp] protected theorem singleton : IsAntichain r {a} := pairwise_singleton _ _ protected theorem subset (hs : IsAntichain r s) (h : t ⊆ s) : IsAntichain r t := hs.mono h theorem mono (hs : IsAntichain r₁ s) (h : r₂ ≤ r₁) : IsAntichain r₂ s := hs.mono' <| compl_le_compl h theorem mono_on (hs : IsAntichain r₁ s) (h : s.Pairwise fun ⦃a b⦄ => r₂ a b → r₁ a b) : IsAntichain r₂ s := hs.imp_on <| h.imp fun _ _ h h₁ h₂ => h₁ <| h h₂ protected theorem eq (hs : IsAntichain r s) {a b : α} (ha : a ∈ s) (hb : b ∈ s) (h : r a b) : a = b := Set.Pairwise.eq hs ha hb <| not_not_intro h protected theorem eq' (hs : IsAntichain r s) {a b : α} (ha : a ∈ s) (hb : b ∈ s) (h : r b a) : a = b := (hs.eq hb ha h).symm protected theorem isAntisymm (h : IsAntichain r univ) : IsAntisymm α r := ⟨fun _ _ ha _ => h.eq trivial trivial ha⟩ protected theorem subsingleton [IsTrichotomous α r] (h : IsAntichain r s) : s.Subsingleton := by rintro a ha b hb obtain hab | hab | hab := trichotomous_of r a b · exact h.eq ha hb hab · exact hab · exact h.eq' ha hb hab protected theorem flip (hs : IsAntichain r s) : IsAntichain (flip r) s := fun _ ha _ hb h => hs hb ha h.symm theorem swap (hs : IsAntichain r s) : IsAntichain (swap r) s := hs.flip theorem image (hs : IsAntichain r s) (f : α → β) (h : ∀ ⦃a b⦄, r' (f a) (f b) → r a b) : IsAntichain r' (f '' s) := by rintro _ ⟨b, hb, rfl⟩ _ ⟨c, hc, rfl⟩ hbc hr exact hs hb hc (ne_of_apply_ne _ hbc) (h hr) theorem preimage (hs : IsAntichain r s) {f : β → α} (hf : Injective f) (h : ∀ ⦃a b⦄, r' a b → r (f a) (f b)) : IsAntichain r' (f ⁻¹' s) := fun _ hb _ hc hbc hr => hs hb hc (hf.ne hbc) <| h hr theorem _root_.isAntichain_insert : IsAntichain r (insert a s) ↔ IsAntichain r s ∧ ∀ ⦃b⦄, b ∈ s → a ≠ b → ¬r a b ∧ ¬r b a := Set.pairwise_insert protected theorem insert (hs : IsAntichain r s) (hl : ∀ ⦃b⦄, b ∈ s → a ≠ b → ¬r b a) (hr : ∀ ⦃b⦄, b ∈ s → a ≠ b → ¬r a b) : IsAntichain r (insert a s) := isAntichain_insert.2 ⟨hs, fun _ hb hab => ⟨hr hb hab, hl hb hab⟩⟩ theorem _root_.isAntichain_insert_of_symmetric (hr : Symmetric r) : IsAntichain r (insert a s) ↔ IsAntichain r s ∧ ∀ ⦃b⦄, b ∈ s → a ≠ b → ¬r a b := pairwise_insert_of_symmetric hr.compl theorem insert_of_symmetric (hs : IsAntichain r s) (hr : Symmetric r) (h : ∀ ⦃b⦄, b ∈ s → a ≠ b → ¬r a b) : IsAntichain r (insert a s) := (isAntichain_insert_of_symmetric hr).2 ⟨hs, h⟩ theorem image_relEmbedding (hs : IsAntichain r s) (φ : r ↪r r') : IsAntichain r' (φ '' s) := by intro b hb b' hb' h₁ h₂ rw [Set.mem_image] at hb hb' obtain ⟨⟨a, has, rfl⟩, ⟨a', has', rfl⟩⟩ := hb, hb' exact hs has has' (fun haa' => h₁ (by rw [haa'])) (φ.map_rel_iff.mp h₂) theorem preimage_relEmbedding {t : Set β} (ht : IsAntichain r' t) (φ : r ↪r r') : IsAntichain r (φ ⁻¹' t) := fun _ ha _s ha' hne hle => ht ha ha' (fun h => hne (φ.injective h)) (φ.map_rel_iff.mpr hle) theorem image_relIso (hs : IsAntichain r s) (φ : r ≃r r') : IsAntichain r' (φ '' s) := hs.image_relEmbedding φ.toRelEmbedding theorem preimage_relIso {t : Set β} (hs : IsAntichain r' t) (φ : r ≃r r') : IsAntichain r (φ ⁻¹' t) := hs.preimage_relEmbedding φ.toRelEmbedding theorem image_relEmbedding_iff {φ : r ↪r r'} : IsAntichain r' (φ '' s) ↔ IsAntichain r s := ⟨fun h => (φ.injective.preimage_image s).subst (h.preimage_relEmbedding φ), fun h => h.image_relEmbedding φ⟩ theorem image_relIso_iff {φ : r ≃r r'} : IsAntichain r' (φ '' s) ↔ IsAntichain r s := @image_relEmbedding_iff _ _ _ _ _ (φ : r ↪r r') theorem image_embedding [LE α] [LE β] (hs : IsAntichain (· ≤ ·) s) (φ : α ↪o β) : IsAntichain (· ≤ ·) (φ '' s) := image_relEmbedding hs _ theorem preimage_embedding [LE α] [LE β] {t : Set β} (ht : IsAntichain (· ≤ ·) t) (φ : α ↪o β) : IsAntichain (· ≤ ·) (φ ⁻¹' t) := preimage_relEmbedding ht _ theorem image_embedding_iff [LE α] [LE β] {φ : α ↪o β} : IsAntichain (· ≤ ·) (φ '' s) ↔ IsAntichain (· ≤ ·) s := image_relEmbedding_iff theorem image_iso [LE α] [LE β] (hs : IsAntichain (· ≤ ·) s) (φ : α ≃o β) : IsAntichain (· ≤ ·) (φ '' s) := image_relEmbedding hs _ theorem image_iso_iff [LE α] [LE β] {φ : α ≃o β} : IsAntichain (· ≤ ·) (φ '' s) ↔ IsAntichain (· ≤ ·) s := image_relEmbedding_iff theorem preimage_iso [LE α] [LE β] {t : Set β} (ht : IsAntichain (· ≤ ·) t) (φ : α ≃o β) : IsAntichain (· ≤ ·) (φ ⁻¹' t) := preimage_relEmbedding ht _ theorem preimage_iso_iff [LE α] [LE β] {t : Set β} {φ : α ≃o β} : IsAntichain (· ≤ ·) (φ ⁻¹' t) ↔ IsAntichain (· ≤ ·) t := ⟨fun h => (φ.image_preimage t).subst (h.image_iso φ), fun h => h.preimage_iso _⟩ theorem to_dual [LE α] (hs : IsAntichain (· ≤ ·) s) : @IsAntichain αᵒᵈ (· ≤ ·) s := fun _ ha _ hb hab => hs hb ha hab.symm theorem to_dual_iff [LE α] : IsAntichain (· ≤ ·) s ↔ @IsAntichain αᵒᵈ (· ≤ ·) s := ⟨to_dual, to_dual⟩ theorem image_compl [BooleanAlgebra α] (hs : IsAntichain (· ≤ ·) s) : IsAntichain (· ≤ ·) (compl '' s) := (hs.image_embedding (OrderIso.compl α).toOrderEmbedding).flip theorem preimage_compl [BooleanAlgebra α] (hs : IsAntichain (· ≤ ·) s) : IsAntichain (· ≤ ·) (compl ⁻¹' s) := fun _ ha _ ha' hne hle => hs ha' ha (fun h => hne (compl_inj_iff.mp h.symm)) (compl_le_compl hle) end IsAntichain theorem isAntichain_union : IsAntichain r (s ∪ t) ↔ IsAntichain r s ∧ IsAntichain r t ∧ ∀ a ∈ s, ∀ b ∈ t, a ≠ b → rᶜ a b ∧ rᶜ b a := by rw [IsAntichain, IsAntichain, IsAntichain, pairwise_union] @[deprecated (since := "2025-09-20")] alias isAntichain_singleton := IsAntichain.singleton theorem Set.Subsingleton.isAntichain (hs : s.Subsingleton) (r : α → α → Prop) : IsAntichain r s := hs.pairwise _ /-- A set which is simultaneously a chain and antichain is subsingleton. -/ lemma subsingleton_of_isChain_of_isAntichain (hs : IsChain r s) (ht : IsAntichain r s) : s.Subsingleton := by intro x hx y hy by_contra! hne cases hs hx hy hne with | inl h => exact ht hx hy hne h | inr h => exact ht hy hx hne.symm h lemma isChain_and_isAntichain_iff_subsingleton : IsChain r s ∧ IsAntichain r s ↔ s.Subsingleton := ⟨fun h ↦ subsingleton_of_isChain_of_isAntichain h.1 h.2, fun h ↦ ⟨h.isChain, h.isAntichain _⟩⟩ /-- The intersection of a chain and an antichain is subsingleton. -/ lemma inter_subsingleton_of_isChain_of_isAntichain (hs : IsChain r s) (ht : IsAntichain r t) : (s ∩ t).Subsingleton := subsingleton_of_isChain_of_isAntichain (hs.mono (by simp)) (ht.subset (by simp)) /-- The intersection of an antichain and a chain is subsingleton. -/ lemma inter_subsingleton_of_isAntichain_of_isChain (hs : IsAntichain r s) (ht : IsChain r t) : (s ∩ t).Subsingleton := inter_comm _ _ ▸ inter_subsingleton_of_isChain_of_isAntichain ht hs section Preorder variable [Preorder α] theorem IsAntichain.not_lt (hs : IsAntichain (· ≤ ·) s) (ha : a ∈ s) (hb : b ∈ s) : ¬a < b := fun h => hs ha hb h.ne h.le theorem isAntichain_and_least_iff : IsAntichain (· ≤ ·) s ∧ IsLeast s a ↔ s = {a} := ⟨fun h => eq_singleton_iff_unique_mem.2 ⟨h.2.1, fun _ hb => h.1.eq' hb h.2.1 (h.2.2 hb)⟩, by rintro rfl exact ⟨IsAntichain.singleton, isLeast_singleton⟩⟩ theorem isAntichain_and_greatest_iff : IsAntichain (· ≤ ·) s ∧ IsGreatest s a ↔ s = {a} := ⟨fun h => eq_singleton_iff_unique_mem.2 ⟨h.2.1, fun _ hb => h.1.eq hb h.2.1 (h.2.2 hb)⟩, by rintro rfl exact ⟨IsAntichain.singleton, isGreatest_singleton⟩⟩ theorem IsAntichain.least_iff (hs : IsAntichain (· ≤ ·) s) : IsLeast s a ↔ s = {a} := (and_iff_right hs).symm.trans isAntichain_and_least_iff theorem IsAntichain.greatest_iff (hs : IsAntichain (· ≤ ·) s) : IsGreatest s a ↔ s = {a} := (and_iff_right hs).symm.trans isAntichain_and_greatest_iff theorem IsLeast.antichain_iff (hs : IsLeast s a) : IsAntichain (· ≤ ·) s ↔ s = {a} := (and_iff_left hs).symm.trans isAntichain_and_least_iff theorem IsGreatest.antichain_iff (hs : IsGreatest s a) : IsAntichain (· ≤ ·) s ↔ s = {a} := (and_iff_left hs).symm.trans isAntichain_and_greatest_iff theorem IsAntichain.bot_mem_iff [OrderBot α] (hs : IsAntichain (· ≤ ·) s) : ⊥ ∈ s ↔ s = {⊥} := isLeast_bot_iff.symm.trans hs.least_iff theorem IsAntichain.top_mem_iff [OrderTop α] (hs : IsAntichain (· ≤ ·) s) : ⊤ ∈ s ↔ s = {⊤} := isGreatest_top_iff.symm.trans hs.greatest_iff theorem IsAntichain.minimal_mem_iff (hs : IsAntichain (· ≤ ·) s) : Minimal (· ∈ s) a ↔ a ∈ s := ⟨fun h ↦ h.prop, fun h ↦ ⟨h, fun _ hys hyx ↦ (hs.eq hys h hyx).symm.le⟩⟩ theorem IsAntichain.maximal_mem_iff (hs : IsAntichain (· ≤ ·) s) : Maximal (· ∈ s) a ↔ a ∈ s := hs.to_dual.minimal_mem_iff /-- If `t` is an antichain shadowing and including the set of maximal elements of `s`, then `t` *is* the set of maximal elements of `s`. -/ theorem IsAntichain.eq_setOf_maximal (ht : IsAntichain (· ≤ ·) t) (h : ∀ x, Maximal (· ∈ s) x → x ∈ t) (hs : ∀ a ∈ t, ∃ b, b ≤ a ∧ Maximal (· ∈ s) b) : {x | Maximal (· ∈ s) x} = t := by refine Set.ext fun x ↦ ⟨h _, fun hx ↦ ?_⟩ obtain ⟨y, hyx, hy⟩ := hs x hx rwa [← ht.eq (h y hy) hx hyx] /-- If `t` is an antichain shadowed by and including the set of minimal elements of `s`, then `t` *is* the set of minimal elements of `s`. -/ theorem IsAntichain.eq_setOf_minimal (ht : IsAntichain (· ≤ ·) t) (h : ∀ x, Minimal (· ∈ s) x → x ∈ t) (hs : ∀ a ∈ t, ∃ b, a ≤ b ∧ Minimal (· ∈ s) b) : {x | Minimal (· ∈ s) x} = t := ht.to_dual.eq_setOf_maximal h hs end Preorder section PartialOrder variable [PartialOrder α] [PartialOrder β] {f : α → β} {s : Set α} lemma IsAntichain.of_strictMonoOn_antitoneOn (hf : StrictMonoOn f s) (hf' : AntitoneOn f s) : IsAntichain (· ≤ ·) s := fun _a ha _b hb hab' hab ↦ (hf ha hb <| hab.lt_of_ne hab').not_ge (hf' ha hb hab) lemma IsAntichain.of_monotoneOn_strictAntiOn (hf : MonotoneOn f s) (hf' : StrictAntiOn f s) : IsAntichain (· ≤ ·) s := fun _a ha _b hb hab' hab ↦ (hf ha hb hab).not_gt (hf' ha hb <| hab.lt_of_ne hab') theorem isAntichain_iff_forall_not_lt : IsAntichain (· ≤ ·) s ↔ ∀ ⦃a⦄, a ∈ s → ∀ ⦃b⦄, b ∈ s → ¬a < b := ⟨fun hs _ ha _ => hs.not_lt ha, fun hs _ ha _ hb h h' => hs ha hb <| h'.lt_of_ne h⟩ theorem setOf_maximal_antichain (P : α → Prop) : IsAntichain (· ≤ ·) {x | Maximal P x} := fun _ hx _ ⟨hy, _⟩ hne hle ↦ hne (hle.antisymm <| hx.2 hy hle) theorem setOf_minimal_antichain (P : α → Prop) : IsAntichain (· ≤ ·) {x | Minimal P x} := (setOf_maximal_antichain (α := αᵒᵈ) P).swap end PartialOrder /-! ### Strong antichains -/ /-- A strong (upward) antichain is a set such that no two distinct elements are related to a common element. -/ def IsStrongAntichain (r : α → α → Prop) (s : Set α) : Prop := s.Pairwise fun a b => ∀ c, ¬r a c ∨ ¬r b c namespace IsStrongAntichain protected theorem subset (hs : IsStrongAntichain r s) (h : t ⊆ s) : IsStrongAntichain r t := hs.mono h theorem mono (hs : IsStrongAntichain r₁ s) (h : r₂ ≤ r₁) : IsStrongAntichain r₂ s := hs.mono' fun _ _ hab c => (hab c).imp (compl_le_compl h _ _) (compl_le_compl h _ _) theorem eq (hs : IsStrongAntichain r s) {a b c : α} (ha : a ∈ s) (hb : b ∈ s) (hac : r a c) (hbc : r b c) : a = b := (Set.Pairwise.eq hs ha hb) fun h => False.elim <| (h c).elim (not_not_intro hac) (not_not_intro hbc) protected theorem isAntichain [IsRefl α r] (h : IsStrongAntichain r s) : IsAntichain r s := h.imp fun _ b hab => (hab b).resolve_right (not_not_intro <| refl _) protected theorem subsingleton [IsDirected α r] (h : IsStrongAntichain r s) : s.Subsingleton := fun a ha b hb => let ⟨_, hac, hbc⟩ := directed_of r a b h.eq ha hb hac hbc protected theorem flip [IsSymm α r] (hs : IsStrongAntichain r s) : IsStrongAntichain (flip r) s := fun _ ha _ hb h c => (hs ha hb h c).imp (mt <| symm_of r) (mt <| symm_of r) theorem swap [IsSymm α r] (hs : IsStrongAntichain r s) : IsStrongAntichain (swap r) s := hs.flip theorem image (hs : IsStrongAntichain r s) {f : α → β} (hf : Surjective f) (h : ∀ a b, r' (f a) (f b) → r a b) : IsStrongAntichain r' (f '' s) := by rintro _ ⟨a, ha, rfl⟩ _ ⟨b, hb, rfl⟩ hab c obtain ⟨c, rfl⟩ := hf c exact (hs ha hb (ne_of_apply_ne _ hab) _).imp (mt <| h _ _) (mt <| h _ _) theorem preimage (hs : IsStrongAntichain r s) {f : β → α} (hf : Injective f) (h : ∀ a b, r' a b → r (f a) (f b)) : IsStrongAntichain r' (f ⁻¹' s) := fun _ ha _ hb hab _ => (hs ha hb (hf.ne hab) _).imp (mt <| h _ _) (mt <| h _ _) theorem _root_.isStrongAntichain_insert : IsStrongAntichain r (insert a s) ↔ IsStrongAntichain r s ∧ ∀ ⦃b⦄, b ∈ s → a ≠ b → ∀ c, ¬r a c ∨ ¬r b c := Set.pairwise_insert_of_symmetric fun _ _ h c => (h c).symm protected theorem insert (hs : IsStrongAntichain r s) (h : ∀ ⦃b⦄, b ∈ s → a ≠ b → ∀ c, ¬r a c ∨ ¬r b c) : IsStrongAntichain r (insert a s) := isStrongAntichain_insert.2 ⟨hs, h⟩ end IsStrongAntichain theorem Set.Subsingleton.isStrongAntichain (hs : s.Subsingleton) (r : α → α → Prop) : IsStrongAntichain r s := hs.pairwise _ /-! ### Maximal antichains -/ /-- An antichain `s` is a maximal antichain if there does not exists an antichain strictly including `s`. -/ def IsMaxAntichain (r : α → α → Prop) (s : Set α) : Prop := IsAntichain r s ∧ ∀ ⦃t⦄, IsAntichain r t → s ⊆ t → s = t namespace IsMaxAntichain theorem isAntichain (h : IsMaxAntichain r s) : IsAntichain r s := h.1 protected theorem image {s : β → β → Prop} (e : r ≃r s) {c : Set α} (hc : IsMaxAntichain r c) : IsMaxAntichain s (e '' c) where left := hc.isAntichain.image _ fun _ _ ↦ e.map_rel_iff'.mp right t ht hf := by rw [← e.coe_fn_toEquiv, ← e.toEquiv.eq_preimage_iff_image_eq, ← Equiv.image_symm_eq_preimage] exact hc.2 (ht.image _ fun _ _ ↦ e.symm.map_rel_iff.mp) ((e.toEquiv.subset_symm_image _ _).2 hf) protected theorem isEmpty_iff (h : IsMaxAntichain r s) : IsEmpty α ↔ s = ∅ := by refine ⟨fun _ ↦ s.eq_empty_of_isEmpty, fun h' ↦ ?_⟩ constructor intro x simp only [IsMaxAntichain, h', IsAntichain.empty, empty_subset, forall_const, true_and] at h exact singleton_ne_empty x (h IsAntichain.singleton).symm protected theorem nonempty_iff (h : IsMaxAntichain r s) : Nonempty α ↔ s ≠ ∅ := by grind [not_nonempty_iff, IsMaxAntichain.isEmpty_iff] protected theorem symm (h : IsMaxAntichain r s) : IsMaxAntichain (flip r) s := ⟨h.isAntichain.flip, fun _ ht₁ ht₂ ↦ h.2 ht₁.flip ht₂⟩ end IsMaxAntichain end General /-! ### Weak antichains -/ section Pi variable {ι : Type*} {α : ι → Type*} [∀ i, Preorder (α i)] {s t : Set (∀ i, α i)} {a b : ∀ i, α i} @[inherit_doc] local infixl:50 " ≺ " => StrongLT /-- A weak antichain in `Π i, α i` is a set such that no two distinct elements are strongly less than each other. -/ def IsWeakAntichain (s : Set (∀ i, α i)) : Prop := IsAntichain (· ≺ ·) s namespace IsWeakAntichain protected theorem subset (hs : IsWeakAntichain s) : t ⊆ s → IsWeakAntichain t := IsAntichain.subset hs protected theorem eq (hs : IsWeakAntichain s) : a ∈ s → b ∈ s → a ≺ b → a = b := IsAntichain.eq hs protected theorem insert (hs : IsWeakAntichain s) : (∀ ⦃b⦄, b ∈ s → a ≠ b → ¬b ≺ a) → (∀ ⦃b⦄, b ∈ s → a ≠ b → ¬a ≺ b) → IsWeakAntichain (insert a s) := IsAntichain.insert hs end IsWeakAntichain theorem _root_.isWeakAntichain_insert : IsWeakAntichain (insert a s) ↔ IsWeakAntichain s ∧ ∀ ⦃b⦄, b ∈ s → a ≠ b → ¬a ≺ b ∧ ¬b ≺ a := isAntichain_insert protected theorem IsAntichain.isWeakAntichain (hs : IsAntichain (· ≤ ·) s) : IsWeakAntichain s := hs.mono fun _ _ => le_of_strongLT theorem Set.Subsingleton.isWeakAntichain (hs : s.Subsingleton) : IsWeakAntichain s := hs.isAntichain _ end Pi
.lake/packages/mathlib/Mathlib/Order/Cofinal.lean
import Mathlib.Order.GaloisConnection.Basic import Mathlib.Order.Interval.Set.Basic import Mathlib.Order.WellFounded /-! # Cofinal sets A set `s` in an ordered type `α` is cofinal when for every `a : α` there exists an element of `s` greater or equal to it. This file provides a basic API for the `IsCofinal` predicate. For the cofinality of a set as a cardinal, see `Mathlib/SetTheory/Cardinal/Cofinality.lean`. ## TODO - Define `Order.cof` in terms of `Cofinal`. - Deprecate `Order.Cofinal` in favor of this predicate. -/ variable {α β : Type*} section LE variable [LE α] theorem IsCofinal.of_isEmpty [IsEmpty α] (s : Set α) : IsCofinal s := fun a ↦ isEmptyElim a theorem isCofinal_empty_iff : IsCofinal (∅ : Set α) ↔ IsEmpty α := by refine ⟨fun h ↦ ⟨fun a ↦ ?_⟩, fun h ↦ .of_isEmpty _⟩ simpa using h a theorem IsCofinal.singleton_top [OrderTop α] : IsCofinal {(⊤ : α)} := fun _ ↦ ⟨⊤, Set.mem_singleton _, le_top⟩ theorem IsCofinal.mono {s t : Set α} (h : s ⊆ t) (hs : IsCofinal s) : IsCofinal t := by intro a obtain ⟨b, hb, hb'⟩ := hs a exact ⟨b, h hb, hb'⟩ end LE section Preorder variable [Preorder α] theorem IsCofinal.univ : IsCofinal (@Set.univ α) := fun a ↦ ⟨a, ⟨⟩, le_rfl⟩ instance : Inhabited {s : Set α // IsCofinal s} := ⟨_, .univ⟩ /-- A cofinal subset of a cofinal subset is cofinal. -/ theorem IsCofinal.trans {s : Set α} {t : Set s} (hs : IsCofinal s) (ht : IsCofinal t) : IsCofinal (Subtype.val '' t) := by intro a obtain ⟨b, hb, hb'⟩ := hs a obtain ⟨c, hc, hc'⟩ := ht ⟨b, hb⟩ exact ⟨c, Set.mem_image_of_mem _ hc, hb'.trans hc'⟩ theorem GaloisConnection.map_cofinal [Preorder β] {f : β → α} {g : α → β} (h : GaloisConnection f g) {s : Set α} (hs : IsCofinal s) : IsCofinal (g '' s) := by intro a obtain ⟨b, hb, hb'⟩ := hs (f a) exact ⟨g b, Set.mem_image_of_mem _ hb, h.le_iff_le.1 hb'⟩ theorem OrderIso.map_cofinal [Preorder β] (e : α ≃o β) {s : Set α} (hs : IsCofinal s) : IsCofinal (e '' s) := e.symm.to_galoisConnection.map_cofinal hs end Preorder section PartialOrder variable [PartialOrder α] theorem IsCofinal.mem_of_isMax {s : Set α} {a : α} (ha : IsMax a) (hs : IsCofinal s) : a ∈ s := by obtain ⟨b, hb, hb'⟩ := hs a rwa [ha.eq_of_ge hb'] at hb theorem IsCofinal.top_mem [OrderTop α] {s : Set α} (hs : IsCofinal s) : ⊤ ∈ s := hs.mem_of_isMax isMax_top @[simp] theorem isCofinal_iff_top_mem [OrderTop α] {s : Set α} : IsCofinal s ↔ ⊤ ∈ s := ⟨IsCofinal.top_mem, fun hs _ ↦ ⟨⊤, hs, le_top⟩⟩ end PartialOrder section LinearOrder variable [LinearOrder α] theorem not_isCofinal_iff {s : Set α} : ¬ IsCofinal s ↔ ∃ x, ∀ y ∈ s, y < x := by simp [IsCofinal] theorem BddAbove.of_not_isCofinal {s : Set α} (h : ¬ IsCofinal s) : BddAbove s := by rw [not_isCofinal_iff] at h obtain ⟨x, h⟩ := h exact ⟨x, fun y hy ↦ (h y hy).le⟩ theorem IsCofinal.of_not_bddAbove {s : Set α} (h : ¬ BddAbove s) : IsCofinal s := by contrapose! h exact .of_not_isCofinal h /-- In a linear order with no maximum, cofinal sets are the same as unbounded sets. -/ theorem not_isCofinal_iff_bddAbove [NoMaxOrder α] {s : Set α} : ¬ IsCofinal s ↔ BddAbove s := by use .of_not_isCofinal rw [not_isCofinal_iff] rintro ⟨x, h⟩ obtain ⟨z, hz⟩ := exists_gt x exact ⟨z, fun y hy ↦ (h hy).trans_lt hz⟩ /-- In a linear order with no maximum, cofinal sets are the same as unbounded sets. -/ theorem not_bddAbove_iff_isCofinal [NoMaxOrder α] {s : Set α} : ¬ BddAbove s ↔ IsCofinal s := not_iff_comm.1 not_isCofinal_iff_bddAbove /-- The set of "records" (the smallest inputs yielding the highest values) with respect to a well-ordering of `α` is a cofinal set. -/ theorem isCofinal_setOf_imp_lt (r : α → α → Prop) [h : IsWellFounded α r] : IsCofinal { a | ∀ b, r b a → b < a } := by intro a obtain ⟨b, hb, hb'⟩ := h.wf.has_min (Set.Ici a) Set.nonempty_Ici refine ⟨b, fun c hc ↦ ?_, hb⟩ by_contra! hc' exact hb' c (hb.trans hc') hc end LinearOrder
.lake/packages/mathlib/Mathlib/Order/Closure.lean
import Mathlib.Data.Set.BooleanAlgebra import Mathlib.Data.SetLike.Basic import Mathlib.Order.Hom.Basic /-! # Closure operators between preorders We define (bundled) closure operators on a preorder as monotone (increasing), extensive (inflationary) and idempotent functions. We define closed elements for the operator as elements which are fixed by it. Lower adjoints to a function between preorders `u : β → α` allow to generalise closure operators to situations where the closure operator we are dealing with naturally decomposes as `u ∘ l` where `l` is a worthy function to have on its own. Typical examples include `l : Set G → Subgroup G := Subgroup.closure`, `u : Subgroup G → Set G := (↑)`, where `G` is a group. This shows there is a close connection between closure operators, lower adjoints and Galois connections/insertions: every Galois connection induces a lower adjoint which itself induces a closure operator by composition (see `GaloisConnection.lowerAdjoint` and `LowerAdjoint.closureOperator`), and every closure operator on a partial order induces a Galois insertion from the set of closed elements to the underlying type (see `ClosureOperator.gi`). ## Main definitions * `ClosureOperator`: A closure operator is a monotone function `f : α → α` such that `∀ x, x ≤ f x` and `∀ x, f (f x) = f x`. * `LowerAdjoint`: A lower adjoint to `u : β → α` is a function `l : α → β` such that `l` and `u` form a Galois connection. ## Implementation details Although `LowerAdjoint` is technically a generalisation of `ClosureOperator` (by defining `toFun := id`), it is desirable to have both as otherwise `id`s would be carried all over the place when using concrete closure operators such as `ConvexHull`. `LowerAdjoint` really is a semibundled `structure` version of `GaloisConnection`. ## References * https://en.wikipedia.org/wiki/Closure_operator#Closure_operators_on_partially_ordered_sets -/ open Set /-! ### Closure operator -/ variable (α : Type*) {ι : Sort*} {κ : ι → Sort*} /-- A closure operator on the preorder `α` is a monotone function which is extensive (every `x` is less than its closure) and idempotent. -/ structure ClosureOperator [Preorder α] extends α →o α where /-- An element is less than or equal its closure -/ le_closure' : ∀ x, x ≤ toFun x /-- Closures are idempotent -/ idempotent' : ∀ x, toFun (toFun x) = toFun x /-- Predicate for an element to be closed. By default, this is defined as `c.IsClosed x := (c x = x)` (see `isClosed_iff`). We allow an override to fix definitional equalities. -/ IsClosed (x : α) : Prop := toFun x = x isClosed_iff {x : α} : IsClosed x ↔ toFun x = x := by aesop namespace ClosureOperator instance [Preorder α] : FunLike (ClosureOperator α) α α where coe c := c.1 coe_injective' := by rintro ⟨⟩ ⟨⟩ h; obtain rfl := DFunLike.ext' h; congr with x; simp_all instance [Preorder α] : OrderHomClass (ClosureOperator α) α α where map_rel f _ _ h := f.mono h initialize_simps_projections ClosureOperator (toFun → apply, IsClosed → isClosed) /-- If `c` is a closure operator on `α` and `e` an order-isomorphism between `α` and `β` then `e ∘ c ∘ e⁻¹` is a closure operator on `β`. -/ @[simps apply] def conjBy {α β} [Preorder α] [Preorder β] (c : ClosureOperator α) (e : α ≃o β) : ClosureOperator β where toFun := e.conj c IsClosed b := c.IsClosed (e.symm b) monotone' _ _ h := (map_le_map_iff e).mpr <| c.monotone <| (map_le_map_iff e.symm).mpr h le_closure' _ := e.symm_apply_le.mp (c.le_closure' _) idempotent' _ := congrArg e <| Eq.trans (congrArg c (e.symm_apply_apply _)) (c.idempotent' _) isClosed_iff := Iff.trans c.isClosed_iff e.eq_symm_apply lemma conjBy_refl {α} [Preorder α] (c : ClosureOperator α) : c.conjBy (OrderIso.refl α) = c := rfl lemma conjBy_trans {α β γ} [Preorder α] [Preorder β] [Preorder γ] (e₁ : α ≃o β) (e₂ : β ≃o γ) (c : ClosureOperator α) : c.conjBy (e₁.trans e₂) = (c.conjBy e₁).conjBy e₂ := rfl section PartialOrder variable [PartialOrder α] /-- The identity function as a closure operator. -/ @[simps!] def id : ClosureOperator α where toOrderHom := OrderHom.id le_closure' _ := le_rfl idempotent' _ := rfl IsClosed _ := True instance : Inhabited (ClosureOperator α) := ⟨id α⟩ variable {α} variable (c : ClosureOperator α) @[ext] theorem ext : ∀ c₁ c₂ : ClosureOperator α, (∀ x, c₁ x = c₂ x) → c₁ = c₂ := DFunLike.ext /-- Constructor for a closure operator using the weaker idempotency axiom: `f (f x) ≤ f x`. -/ @[simps] def mk' (f : α → α) (hf₁ : Monotone f) (hf₂ : ∀ x, x ≤ f x) (hf₃ : ∀ x, f (f x) ≤ f x) : ClosureOperator α where toFun := f monotone' := hf₁ le_closure' := hf₂ idempotent' x := (hf₃ x).antisymm (hf₁ (hf₂ x)) /-- Convenience constructor for a closure operator using the weaker minimality axiom: `x ≤ f y → f x ≤ f y`, which is sometimes easier to prove in practice. -/ @[simps] def mk₂ (f : α → α) (hf : ∀ x, x ≤ f x) (hmin : ∀ ⦃x y⦄, x ≤ f y → f x ≤ f y) : ClosureOperator α where toFun := f monotone' _ y hxy := hmin (hxy.trans (hf y)) le_closure' := hf idempotent' _ := (hmin le_rfl).antisymm (hf _) /-- Construct a closure operator from an inflationary function `f` and a "closedness" predicate `p` witnessing minimality of `f x` among closed elements greater than `x`. -/ @[simps!] def ofPred (f : α → α) (p : α → Prop) (hf : ∀ x, x ≤ f x) (hfp : ∀ x, p (f x)) (hmin : ∀ ⦃x y⦄, x ≤ y → p y → f x ≤ y) : ClosureOperator α where __ := mk₂ f hf fun _ y hxy => hmin hxy (hfp y) IsClosed := p isClosed_iff := ⟨fun hx ↦ (hmin le_rfl hx).antisymm <| hf _, fun hx ↦ hx ▸ hfp _⟩ @[mono] theorem monotone : Monotone c := c.monotone' /-- Every element is less than its closure. This property is sometimes referred to as extensivity or inflationarity. -/ theorem le_closure (x : α) : x ≤ c x := c.le_closure' x @[simp] theorem idempotent (x : α) : c (c x) = c x := c.idempotent' x @[simp] lemma isClosed_closure (x : α) : c.IsClosed (c x) := c.isClosed_iff.2 <| c.idempotent x /-- The type of elements closed under a closure operator. -/ abbrev Closeds := {x // c.IsClosed x} /-- Send an element to a closed element (by taking the closure). -/ def toCloseds (x : α) : c.Closeds := ⟨c x, c.isClosed_closure x⟩ variable {c} {x y : α} theorem IsClosed.closure_eq : c.IsClosed x → c x = x := c.isClosed_iff.1 theorem isClosed_iff_closure_le : c.IsClosed x ↔ c x ≤ x := ⟨fun h ↦ h.closure_eq.le, fun h ↦ c.isClosed_iff.2 <| h.antisymm <| c.le_closure x⟩ /-- The set of closed elements for `c` is exactly its range. -/ theorem setOf_isClosed_eq_range_closure : {x | c.IsClosed x} = Set.range c := by ext x; exact ⟨fun hx ↦ ⟨x, hx.closure_eq⟩, by rintro ⟨y, rfl⟩; exact c.isClosed_closure _⟩ theorem le_closure_iff : x ≤ c y ↔ c x ≤ c y := ⟨fun h ↦ c.idempotent y ▸ c.monotone h, (c.le_closure x).trans⟩ @[simp] theorem IsClosed.closure_le_iff (hy : c.IsClosed y) : c x ≤ y ↔ x ≤ y := by rw [← hy.closure_eq, ← le_closure_iff] lemma closure_min (hxy : x ≤ y) (hy : c.IsClosed y) : c x ≤ y := hy.closure_le_iff.2 hxy lemma closure_isGLB (x : α) : IsGLB { y | x ≤ y ∧ c.IsClosed y } (c x) where left _ := and_imp.mpr closure_min right _ h := h ⟨c.le_closure x, c.isClosed_closure x⟩ theorem ext_isClosed (c₁ c₂ : ClosureOperator α) (h : ∀ x, c₁.IsClosed x ↔ c₂.IsClosed x) : c₁ = c₂ := ext c₁ c₂ <| fun x => IsGLB.unique (c₁.closure_isGLB x) <| (Set.ext (and_congr_right' <| h ·)).substr (c₂.closure_isGLB x) /-- A closure operator is equal to the closure operator obtained by feeding `c.closed` into the `ofPred` constructor. -/ theorem eq_ofPred_closed (c : ClosureOperator α) : c = ofPred c c.IsClosed c.le_closure c.isClosed_closure fun _ _ ↦ closure_min := by ext rfl end PartialOrder variable {α} section OrderTop variable [PartialOrder α] [OrderTop α] (c : ClosureOperator α) @[simp] theorem closure_top : c ⊤ = ⊤ := le_top.antisymm (c.le_closure _) @[simp] lemma isClosed_top : c.IsClosed ⊤ := c.isClosed_iff.2 c.closure_top end OrderTop theorem closure_inf_le [SemilatticeInf α] (c : ClosureOperator α) (x y : α) : c (x ⊓ y) ≤ c x ⊓ c y := c.monotone.map_inf_le _ _ section SemilatticeSup variable [SemilatticeSup α] (c : ClosureOperator α) theorem closure_sup_closure_le (x y : α) : c x ⊔ c y ≤ c (x ⊔ y) := c.monotone.le_map_sup _ _ theorem closure_sup_closure_left (x y : α) : c (c x ⊔ y) = c (x ⊔ y) := le_antisymm (le_closure_iff.1 (sup_le (c.monotone le_sup_left) (le_sup_right.trans (c.le_closure _)))) (by grw [← c.le_closure x]) theorem closure_sup_closure_right (x y : α) : c (x ⊔ c y) = c (x ⊔ y) := by rw [sup_comm, closure_sup_closure_left, sup_comm (a := x)] theorem closure_sup_closure (x y : α) : c (c x ⊔ c y) = c (x ⊔ y) := by rw [closure_sup_closure_left, closure_sup_closure_right] end SemilatticeSup section CompleteLattice variable [CompleteLattice α] (c : ClosureOperator α) /-- Define a closure operator from a predicate that's preserved under infima. -/ @[simps!] def ofCompletePred (p : α → Prop) (hsinf : ∀ s, (∀ a ∈ s, p a) → p (sInf s)) : ClosureOperator α := ofPred (fun a ↦ ⨅ b : {b // a ≤ b ∧ p b}, b) p (fun a ↦ by simp +contextual) (fun _ ↦ hsinf _ <| forall_mem_range.2 fun b ↦ b.2.2) (fun _ b hab hb ↦ iInf_le_of_le ⟨b, hab, hb⟩ le_rfl) theorem sInf_isClosed {c : ClosureOperator α} {S : Set α} (H : ∀ x ∈ S, c.IsClosed x) : c.IsClosed (sInf S) := isClosed_iff_closure_le.mpr <| le_of_le_of_eq c.monotone.map_sInf_le <| Eq.trans (biInf_congr (c.isClosed_iff.mp <| H · ·)) sInf_eq_iInf.symm @[simp] theorem closure_iSup_closure (f : ι → α) : c (⨆ i, c (f i)) = c (⨆ i, f i) := le_antisymm (le_closure_iff.1 <| iSup_le fun i => c.monotone <| le_iSup f i) <| c.monotone <| iSup_mono fun _ => c.le_closure _ @[simp] theorem closure_iSup₂_closure (f : ∀ i, κ i → α) : c (⨆ (i) (j), c (f i j)) = c (⨆ (i) (j), f i j) := le_antisymm (le_closure_iff.1 <| iSup₂_le fun i j => c.monotone <| le_iSup₂ i j) <| c.monotone <| iSup₂_mono fun _ _ => c.le_closure _ end CompleteLattice end ClosureOperator /-- Conjugating `ClosureOperators` on `α` and on `β` by a fixed isomorphism `e : α ≃o β` gives an equivalence `ClosureOperator α ≃ ClosureOperator β`. -/ @[simps apply symm_apply] def OrderIso.equivClosureOperator {α β} [Preorder α] [Preorder β] (e : α ≃o β) : ClosureOperator α ≃ ClosureOperator β where toFun c := c.conjBy e invFun c := c.conjBy e.symm left_inv c := Eq.trans (c.conjBy_trans _ _).symm <| Eq.trans (congrArg _ e.self_trans_symm) c.conjBy_refl right_inv c := Eq.trans (c.conjBy_trans _ _).symm <| Eq.trans (congrArg _ e.symm_trans_self) c.conjBy_refl /-! ### Lower adjoint -/ variable {α} {β : Type*} /-- A lower adjoint of `u` on the preorder `α` is a function `l` such that `l` and `u` form a Galois connection. It allows us to define closure operators whose output does not match the input. In practice, `u` is often `(↑) : β → α`. -/ structure LowerAdjoint [Preorder α] [Preorder β] (u : β → α) where /-- The underlying function -/ toFun : α → β /-- The underlying function is a lower adjoint. -/ gc' : GaloisConnection toFun u namespace LowerAdjoint variable (α) /-- The identity function as a lower adjoint to itself. -/ @[simps] protected def id [Preorder α] : LowerAdjoint (id : α → α) where toFun x := x gc' := GaloisConnection.id variable {α} instance [Preorder α] : Inhabited (LowerAdjoint (id : α → α)) := ⟨LowerAdjoint.id α⟩ section Preorder variable [Preorder α] [Preorder β] {u : β → α} (l : LowerAdjoint u) instance : CoeFun (LowerAdjoint u) fun _ => α → β where coe := toFun theorem gc : GaloisConnection l u := l.gc' @[ext] theorem ext : ∀ l₁ l₂ : LowerAdjoint u, (l₁ : α → β) = (l₂ : α → β) → l₁ = l₂ | ⟨l₁, _⟩, ⟨l₂, _⟩, h => by congr @[mono] theorem monotone : Monotone (u ∘ l) := l.gc.monotone_u.comp l.gc.monotone_l /-- Every element is less than its closure. This property is sometimes referred to as extensivity or inflationarity. -/ theorem le_closure (x : α) : x ≤ u (l x) := l.gc.le_u_l _ end Preorder section PartialOrder variable [PartialOrder α] [Preorder β] {u : β → α} (l : LowerAdjoint u) /-- Every lower adjoint induces a closure operator given by the composition. This is the partial order version of the statement that every adjunction induces a monad. -/ @[simps] def closureOperator : ClosureOperator α where toFun x := u (l x) monotone' := l.monotone le_closure' := l.le_closure idempotent' x := l.gc.u_l_u_eq_u (l x) theorem idempotent (x : α) : u (l (u (l x))) = u (l x) := l.closureOperator.idempotent _ theorem le_closure_iff (x y : α) : x ≤ u (l y) ↔ u (l x) ≤ u (l y) := l.closureOperator.le_closure_iff end PartialOrder section Preorder variable [Preorder α] [Preorder β] {u : β → α} (l : LowerAdjoint u) /-- An element `x` is closed for `l : LowerAdjoint u` if it is a fixed point: `u (l x) = x` -/ def closed : Set α := {x | u (l x) = x} theorem mem_closed_iff (x : α) : x ∈ l.closed ↔ u (l x) = x := Iff.rfl theorem closure_eq_self_of_mem_closed {x : α} (h : x ∈ l.closed) : u (l x) = x := h end Preorder section PartialOrder variable [PartialOrder α] [PartialOrder β] {u : β → α} (l : LowerAdjoint u) theorem mem_closed_iff_closure_le (x : α) : x ∈ l.closed ↔ u (l x) ≤ x := l.closureOperator.isClosed_iff_closure_le @[simp] theorem closure_is_closed (x : α) : u (l x) ∈ l.closed := l.idempotent x /-- The set of closed elements for `l` is the range of `u ∘ l`. -/ theorem closed_eq_range_close : l.closed = Set.range (u ∘ l) := l.closureOperator.setOf_isClosed_eq_range_closure /-- Send an `x` to an element of the set of closed elements (by taking the closure). -/ def toClosed (x : α) : l.closed := ⟨u (l x), l.closure_is_closed x⟩ @[simp] theorem closure_le_closed_iff_le (x : α) {y : α} (hy : l.closed y) : u (l x) ≤ y ↔ x ≤ y := (show l.closureOperator.IsClosed y from hy).closure_le_iff end PartialOrder theorem closure_top [PartialOrder α] [OrderTop α] [Preorder β] {u : β → α} (l : LowerAdjoint u) : u (l ⊤) = ⊤ := l.closureOperator.closure_top theorem closure_inf_le [SemilatticeInf α] [Preorder β] {u : β → α} (l : LowerAdjoint u) (x y : α) : u (l (x ⊓ y)) ≤ u (l x) ⊓ u (l y) := l.closureOperator.closure_inf_le x y section SemilatticeSup variable [SemilatticeSup α] [Preorder β] {u : β → α} (l : LowerAdjoint u) theorem closure_sup_closure_le (x y : α) : u (l x) ⊔ u (l y) ≤ u (l (x ⊔ y)) := l.closureOperator.closure_sup_closure_le x y theorem closure_sup_closure_left (x y : α) : u (l (u (l x) ⊔ y)) = u (l (x ⊔ y)) := l.closureOperator.closure_sup_closure_left x y theorem closure_sup_closure_right (x y : α) : u (l (x ⊔ u (l y))) = u (l (x ⊔ y)) := l.closureOperator.closure_sup_closure_right x y theorem closure_sup_closure (x y : α) : u (l (u (l x) ⊔ u (l y))) = u (l (x ⊔ y)) := l.closureOperator.closure_sup_closure x y end SemilatticeSup section CompleteLattice variable [CompleteLattice α] [Preorder β] {u : β → α} (l : LowerAdjoint u) theorem closure_iSup_closure (f : ι → α) : u (l (⨆ i, u (l (f i)))) = u (l (⨆ i, f i)) := l.closureOperator.closure_iSup_closure _ theorem closure_iSup₂_closure (f : ∀ i, κ i → α) : u (l <| ⨆ (i) (j), u (l <| f i j)) = u (l <| ⨆ (i) (j), f i j) := l.closureOperator.closure_iSup₂_closure _ end CompleteLattice -- Lemmas for `LowerAdjoint ((↑) : α → Set β)`, where `SetLike α β` section CoeToSet variable [SetLike α β] (l : LowerAdjoint ((↑) : α → Set β)) theorem subset_closure (s : Set β) : s ⊆ l s := l.le_closure s theorem notMem_of_notMem_closure {s : Set β} {P : β} (hP : P ∉ l s) : P ∉ s := fun h => hP (subset_closure _ s h) @[deprecated (since := "2025-05-23")] alias not_mem_of_not_mem_closure := notMem_of_notMem_closure theorem le_iff_subset (s : Set β) (S : α) : l s ≤ S ↔ s ⊆ S := l.gc s S theorem mem_iff (s : Set β) (x : β) : x ∈ l s ↔ ∀ S : α, s ⊆ S → x ∈ S := by simp_rw [← SetLike.mem_coe, ← Set.singleton_subset_iff, ← l.le_iff_subset] exact ⟨fun h S => h.trans, fun h => h _ le_rfl⟩ theorem eq_of_le {s : Set β} {S : α} (h₁ : s ⊆ S) (h₂ : S ≤ l s) : l s = S := ((l.le_iff_subset _ _).2 h₁).antisymm h₂ theorem closure_union_closure_subset (x y : α) : (l x : Set β) ∪ l y ⊆ l (x ∪ y) := l.closure_sup_closure_le x y @[simp] theorem closure_union_closure_left (x y : α) : l (l x ∪ y) = l (x ∪ y) := SetLike.coe_injective (l.closure_sup_closure_left x y) @[simp] theorem closure_union_closure_right (x y : α) : l (x ∪ l y) = l (x ∪ y) := SetLike.coe_injective (l.closure_sup_closure_right x y) theorem closure_union_closure (x y : α) : l (l x ∪ l y) = l (x ∪ y) := by rw [closure_union_closure_right, closure_union_closure_left] @[simp] theorem closure_iUnion_closure (f : ι → α) : l (⋃ i, l (f i)) = l (⋃ i, f i) := SetLike.coe_injective <| l.closure_iSup_closure _ @[simp] theorem closure_iUnion₂_closure (f : ∀ i, κ i → α) : l (⋃ (i) (j), l (f i j)) = l (⋃ (i) (j), f i j) := SetLike.coe_injective <| l.closure_iSup₂_closure _ end CoeToSet end LowerAdjoint /-! ### Translations between `GaloisConnection`, `LowerAdjoint`, `ClosureOperator` -/ /-- Every Galois connection induces a lower adjoint. -/ @[simps] def GaloisConnection.lowerAdjoint [Preorder α] [Preorder β] {l : α → β} {u : β → α} (gc : GaloisConnection l u) : LowerAdjoint u where toFun := l gc' := gc /-- Every Galois connection induces a closure operator given by the composition. This is the partial order version of the statement that every adjunction induces a monad. -/ @[simps!] def GaloisConnection.closureOperator [PartialOrder α] [Preorder β] {l : α → β} {u : β → α} (gc : GaloisConnection l u) : ClosureOperator α := gc.lowerAdjoint.closureOperator /-- The set of closed elements has a Galois insertion to the underlying type. -/ def ClosureOperator.gi [PartialOrder α] (c : ClosureOperator α) : GaloisInsertion c.toCloseds (↑) where choice x hx := ⟨x, isClosed_iff_closure_le.2 hx⟩ gc _ y := y.2.closure_le_iff le_l_u _ := c.le_closure _ choice_eq x hx := le_antisymm (c.le_closure x) hx /-- The Galois insertion associated to a closure operator can be used to reconstruct the closure operator. Note that the inverse in the opposite direction does not hold in general. -/ @[simp] theorem closureOperator_gi_self [PartialOrder α] (c : ClosureOperator α) : c.gi.gc.closureOperator = c := by ext x rfl
.lake/packages/mathlib/Mathlib/Order/ScottContinuity.lean
import Mathlib.Order.Bounds.Basic /-! # Scott continuity A function `f : α → β` between preorders is Scott continuous (referring to Dana Scott) if it distributes over `IsLUB`. Scott continuity corresponds to continuity in Scott topological spaces (defined in `Mathlib/Topology/Order/ScottTopology.lean`). It is distinct from the (more commonly used) continuity from topology (see `Mathlib/Topology/Basic.lean`). ## Implementation notes Given a set `D` of directed sets, we define say `f` is `ScottContinuousOn D` if it distributes over `IsLUB` for all elements of `D`. This allows us to consider Scott Continuity on all directed sets in this file, and ωScott Continuity on chains later in `Mathlib/Order/OmegaCompletePartialOrder.lean`. ## References * [Abramsky and Jung, *Domain Theory*][abramsky_gabbay_maibaum_1994] * [Gierz et al, *A Compendium of Continuous Lattices*][GierzEtAl1980] -/ open Set variable {α β : Type*} section ScottContinuous variable [Preorder α] [Preorder β] {D D₁ D₂ : Set (Set α)} {f : α → β} /-- A function between preorders is said to be Scott continuous on a set `D` of directed sets if it preserves `IsLUB` on elements of `D`. The dual notion ```lean ∀ ⦃d : Set α⦄, d ∈ D → d.Nonempty → DirectedOn (· ≥ ·) d → ∀ ⦃a⦄, IsGLB d a → IsGLB (f '' d) (f a) ``` does not appear to play a significant role in the literature, so is omitted here. -/ def ScottContinuousOn (D : Set (Set α)) (f : α → β) : Prop := ∀ ⦃d : Set α⦄, d ∈ D → d.Nonempty → DirectedOn (· ≤ ·) d → ∀ ⦃a⦄, IsLUB d a → IsLUB (f '' d) (f a) lemma ScottContinuousOn.mono (hD : D₁ ⊆ D₂) (hf : ScottContinuousOn D₂ f) : ScottContinuousOn D₁ f := fun _ hdD₁ hd₁ hd₂ _ hda => hf (hD hdD₁) hd₁ hd₂ hda protected theorem ScottContinuousOn.monotone (D : Set (Set α)) (hD : ∀ a b : α, a ≤ b → {a, b} ∈ D) (h : ScottContinuousOn D f) : Monotone f := by refine fun a b hab => (h (hD a b hab) (insert_nonempty _ _) (directedOn_pair le_refl hab) ?_).1 (mem_image_of_mem _ <| mem_insert _ _) rw [IsLUB, upperBounds_insert, upperBounds_singleton, inter_eq_self_of_subset_right (Ici_subset_Ici.2 hab)] exact isLeast_Ici @[simp] lemma ScottContinuousOn.id : ScottContinuousOn D (id : α → α) := by simp [ScottContinuousOn] variable {g : α → β} lemma ScottContinuousOn.prodMk (hD : ∀ a b : α, a ≤ b → {a, b} ∈ D) (hf : ScottContinuousOn D f) (hg : ScottContinuousOn D g) : ScottContinuousOn D fun x => (f x, g x) := fun d hd₁ hd₂ hd₃ a hda => by rw [IsLUB, IsLeast, upperBounds] constructor · simp only [mem_image, forall_exists_index, and_imp, forall_apply_eq_imp_iff₂, mem_setOf_eq, Prod.mk_le_mk] intro b hb exact ⟨hf.monotone D hD (hda.1 hb), hg.monotone D hD (hda.1 hb)⟩ · intro ⟨p₁, p₂⟩ hp simp only [mem_image, forall_exists_index, and_imp, forall_apply_eq_imp_iff₂, mem_setOf_eq, Prod.mk_le_mk] at hp constructor · rw [isLUB_le_iff (hf hd₁ hd₂ hd₃ hda), upperBounds] simp only [mem_image, forall_exists_index, and_imp, forall_apply_eq_imp_iff₂, mem_setOf_eq] intro _ hb exact (hp _ hb).1 · rw [isLUB_le_iff (hg hd₁ hd₂ hd₃ hda), upperBounds] simp only [mem_image, forall_exists_index, and_imp, forall_apply_eq_imp_iff₂, mem_setOf_eq] intro _ hb exact (hp _ hb).2 /-- A function between preorders is said to be Scott continuous if it preserves `IsLUB` on directed sets. It can be shown that a function is Scott continuous if and only if it is continuous w.r.t. the Scott topology. -/ def ScottContinuous (f : α → β) : Prop := ∀ ⦃d : Set α⦄, d.Nonempty → DirectedOn (· ≤ ·) d → ∀ ⦃a⦄, IsLUB d a → IsLUB (f '' d) (f a) @[simp] lemma scottContinuousOn_univ : ScottContinuousOn univ f ↔ ScottContinuous f := by simp [ScottContinuousOn, ScottContinuous] lemma ScottContinuous.scottContinuousOn {D : Set (Set α)} : ScottContinuous f → ScottContinuousOn D f := fun h _ _ d₂ d₃ _ hda => h d₂ d₃ hda protected theorem ScottContinuous.monotone (h : ScottContinuous f) : Monotone f := h.scottContinuousOn.monotone univ (fun _ _ _ ↦ mem_univ _) @[simp] lemma ScottContinuous.id : ScottContinuous (id : α → α) := by simp [ScottContinuous] end ScottContinuous section SemilatticeSup variable [SemilatticeSup β] /-- The join operation is Scott continuous -/ lemma ScottContinuous.sup₂ : ScottContinuous fun b : β × β => (b.1 ⊔ b.2 : β) := fun d _ _ ⟨p₁, p₂⟩ hdp => by simp only [IsLUB, IsLeast, upperBounds, Prod.forall, mem_setOf_eq, Prod.mk_le_mk] at hdp simp only [IsLUB, IsLeast, upperBounds, mem_image, Prod.exists, forall_exists_index, and_imp] have e1 : (p₁, p₂) ∈ lowerBounds {x | ∀ (b₁ b₂ : β), (b₁, b₂) ∈ d → (b₁, b₂) ≤ x} := hdp.2 simp only [lowerBounds, mem_setOf_eq, Prod.forall, Prod.mk_le_mk] at e1 refine ⟨fun a b₁ b₂ hbd hba => ?_,fun b hb => ?_⟩ · rw [← hba] exact sup_le_sup (hdp.1 _ _ hbd).1 (hdp.1 _ _ hbd).2 · rw [sup_le_iff] exact e1 _ _ fun b₁ b₂ hb' => sup_le_iff.mp (hb b₁ b₂ hb' rfl) lemma ScottContinuousOn.sup₂ {D : Set (Set (β × β))} : ScottContinuousOn D fun (a, b) => (a ⊔ b : β) := ScottContinuous.sup₂.scottContinuousOn end SemilatticeSup
.lake/packages/mathlib/Mathlib/Order/Restriction.lean
import Mathlib.Data.Finset.Update import Mathlib.Order.Interval.Finset.Basic /-! # Restriction of a function indexed by a preorder Given a preorder `α` and dependent function `f : (i : α) → π i` and `a : α`, one might want to consider the restriction of `f` to elements `≤ a`. This is defined in this file as `Preorder.restrictLe a f`. Similarly, if we have `a b : α`, `hab : a ≤ b` and `f : (i : ↑(Set.Iic b)) → π ↑i`, one might want to restrict it to elements `≤ a`. This is defined in this file as `Preorder.restrictLe₂ hab f`. We also provide versions where the intervals are seen as finite sets, see `Preorder.frestrictLe` and `Preorder.frestrictLe₂`. ## Main definitions * `Preorder.restrictLe a f`: Restricts the function `f` to the variables indexed by elements `≤ a`. -/ namespace Preorder variable {α : Type*} [Preorder α] {π : α → Type*} section Set open Set /-- Restrict domain of a function `f` indexed by `α` to elements `≤ a`. -/ def restrictLe (a : α) := (Iic a).restrict (π := π) @[simp] lemma restrictLe_apply (a : α) (f : (a : α) → π a) (i : Iic a) : restrictLe a f i = f i := rfl /-- If a function `f` indexed by `α` is restricted to elements `≤ π`, and `a ≤ b`, this is the restriction to elements `≤ a`. -/ def restrictLe₂ {a b : α} (hab : a ≤ b) := Set.restrict₂ (π := π) (Iic_subset_Iic.2 hab) @[simp] lemma restrictLe₂_apply {a b : α} (hab : a ≤ b) (f : (i : Iic b) → π i) (i : Iic a) : restrictLe₂ hab f i = f ⟨i.1, Iic_subset_Iic.2 hab i.2⟩ := rfl theorem restrictLe₂_comp_restrictLe {a b : α} (hab : a ≤ b) : (restrictLe₂ (π := π) hab) ∘ (restrictLe b) = restrictLe a := rfl theorem restrictLe₂_comp_restrictLe₂ {a b c : α} (hab : a ≤ b) (hbc : b ≤ c) : (restrictLe₂ (π := π) hab) ∘ (restrictLe₂ hbc) = restrictLe₂ (hab.trans hbc) := rfl lemma dependsOn_restrictLe (a : α) : DependsOn (restrictLe (π := π) a) (Iic a) := (Iic a).dependsOn_restrict end Set section Finset variable [LocallyFiniteOrderBot α] open Finset /-- Restrict domain of a function `f` indexed by `α` to elements `≤ a`, seen as a finite set. -/ def frestrictLe (a : α) := (Iic a).restrict (π := π) @[simp] lemma frestrictLe_apply (a : α) (f : (a : α) → π a) (i : Iic a) : frestrictLe a f i = f i := rfl /-- If a function `f` indexed by `α` is restricted to elements `≤ b`, and `a ≤ b`, this is the restriction to elements `≤ b`. Intervals are seen as finite sets. -/ def frestrictLe₂ {a b : α} (hab : a ≤ b) := restrict₂ (π := π) (Iic_subset_Iic.2 hab) @[simp] lemma frestrictLe₂_apply {a b : α} (hab : a ≤ b) (f : (i : Iic b) → π i) (i : Iic a) : frestrictLe₂ hab f i = f ⟨i.1, Iic_subset_Iic.2 hab i.2⟩ := rfl theorem frestrictLe₂_comp_frestrictLe {a b : α} (hab : a ≤ b) : (frestrictLe₂ (π := π) hab) ∘ (frestrictLe b) = frestrictLe a := rfl theorem frestrictLe₂_comp_frestrictLe₂ {a b c : α} (hab : a ≤ b) (hbc : b ≤ c) : (frestrictLe₂ (π := π) hab) ∘ (frestrictLe₂ hbc) = frestrictLe₂ (hab.trans hbc) := rfl theorem piCongrLeft_comp_restrictLe {a : α} : ((Equiv.IicFinsetSet a).symm.piCongrLeft (fun i : Iic a ↦ π i)) ∘ (restrictLe a) = frestrictLe a := rfl theorem piCongrLeft_comp_frestrictLe {a : α} : ((Equiv.IicFinsetSet a).piCongrLeft (fun i : Set.Iic a ↦ π i)) ∘ (frestrictLe a) = restrictLe a := rfl section updateFinset open Function variable [DecidableEq α] lemma frestrictLe_updateFinset_of_le {a b : α} (hab : a ≤ b) (x : Π c, π c) (y : Π c : Iic b, π c) : frestrictLe a (updateFinset x _ y) = frestrictLe₂ hab y := restrict_updateFinset_of_subset (Iic_subset_Iic.2 hab) .. lemma frestrictLe_updateFinset {a : α} (x : Π a, π a) (y : Π b : Iic a, π b) : frestrictLe a (updateFinset x _ y) = y := restrict_updateFinset .. @[simp] lemma updateFinset_frestrictLe (a : α) (x : Π a, π a) : updateFinset x _ (frestrictLe a x) = x := by simp [frestrictLe] end updateFinset lemma dependsOn_frestrictLe (a : α) : DependsOn (frestrictLe (π := π) a) (Set.Iic a) := coe_Iic a ▸ (Finset.Iic a).dependsOn_restrict end Finset end Preorder
.lake/packages/mathlib/Mathlib/Order/SetIsMax.lean
import Mathlib.Order.Max import Mathlib.Data.Set.CoeSort /-! # Maximal elements of subsets Let `S : Set J` and `m : S`. If `m` is not a maximal element of `S`, then `↑m : J` is not maximal in `J`. -/ universe u namespace Set variable {J : Type u} [Preorder J] {S : Set J} (m : S) lemma not_isMax_coe (hm : ¬ IsMax m) : ¬ IsMax m.1 := fun h ↦ hm (fun _ hb ↦ h hb) lemma not_isMin_coe (hm : ¬ IsMin m) : ¬ IsMin m.1 := fun h ↦ hm (fun _ hb ↦ h hb) end Set
.lake/packages/mathlib/Mathlib/Order/Cover.lean
import Mathlib.Order.Antisymmetrization import Mathlib.Order.Hom.WithTopBot import Mathlib.Order.Interval.Set.OrdConnected import Mathlib.Order.Interval.Set.WithBotTop /-! # The covering relation This file proves properties of the covering relation in an order. We say that `b` *covers* `a` if `a < b` and there is no element in between. We say that `b` *weakly covers* `a` if `a ≤ b` and there is no element between `a` and `b`. In a partial order this is equivalent to `a ⋖ b ∨ a = b`, in a preorder this is equivalent to `a ⋖ b ∨ (a ≤ b ∧ b ≤ a)` ## Notation * `a ⋖ b` means that `b` covers `a`. * `a ⩿ b` means that `b` weakly covers `a`. -/ open Set OrderDual variable {α β : Type*} section WeaklyCovers section Preorder variable [Preorder α] [Preorder β] {a b c : α} theorem WCovBy.le (h : a ⩿ b) : a ≤ b := h.1 theorem WCovBy.refl (a : α) : a ⩿ a := ⟨le_rfl, fun _ hc => hc.not_gt⟩ @[simp] lemma WCovBy.rfl : a ⩿ a := WCovBy.refl a protected theorem Eq.wcovBy (h : a = b) : a ⩿ b := h ▸ WCovBy.rfl theorem wcovBy_of_le_of_le (h1 : a ≤ b) (h2 : b ≤ a) : a ⩿ b := ⟨h1, fun _ hac hcb => (hac.trans hcb).not_ge h2⟩ alias LE.le.wcovBy_of_le := wcovBy_of_le_of_le theorem AntisymmRel.wcovBy (h : AntisymmRel (· ≤ ·) a b) : a ⩿ b := wcovBy_of_le_of_le h.1 h.2 theorem WCovBy.wcovBy_iff_le (hab : a ⩿ b) : b ⩿ a ↔ b ≤ a := ⟨fun h => h.le, fun h => h.wcovBy_of_le hab.le⟩ theorem wcovBy_of_eq_or_eq (hab : a ≤ b) (h : ∀ c, a ≤ c → c ≤ b → c = a ∨ c = b) : a ⩿ b := ⟨hab, fun c ha hb => (h c ha.le hb.le).elim ha.ne' hb.ne⟩ theorem AntisymmRel.trans_wcovBy (hab : AntisymmRel (· ≤ ·) a b) (hbc : b ⩿ c) : a ⩿ c := ⟨hab.1.trans hbc.le, fun _ had hdc => hbc.2 (hab.2.trans_lt had) hdc⟩ theorem wcovBy_congr_left (hab : AntisymmRel (· ≤ ·) a b) : a ⩿ c ↔ b ⩿ c := ⟨hab.symm.trans_wcovBy, hab.trans_wcovBy⟩ theorem WCovBy.trans_antisymm_rel (hab : a ⩿ b) (hbc : AntisymmRel (· ≤ ·) b c) : a ⩿ c := ⟨hab.le.trans hbc.1, fun _ had hdc => hab.2 had <| hdc.trans_le hbc.2⟩ theorem wcovBy_congr_right (hab : AntisymmRel (· ≤ ·) a b) : c ⩿ a ↔ c ⩿ b := ⟨fun h => h.trans_antisymm_rel hab, fun h => h.trans_antisymm_rel hab.symm⟩ /-- If `a ≤ b`, then `b` does not cover `a` iff there's an element in between. -/ theorem not_wcovBy_iff (h : a ≤ b) : ¬a ⩿ b ↔ ∃ c, a < c ∧ c < b := by simp_rw [WCovBy, h, true_and, not_forall, exists_prop, not_not] instance WCovBy.isRefl : IsRefl α (· ⩿ ·) := ⟨WCovBy.refl⟩ theorem WCovBy.Ioo_eq (h : a ⩿ b) : Ioo a b = ∅ := eq_empty_iff_forall_notMem.2 fun _ hx => h.2 hx.1 hx.2 theorem wcovBy_iff_Ioo_eq : a ⩿ b ↔ a ≤ b ∧ Ioo a b = ∅ := and_congr_right' <| by simp [eq_empty_iff_forall_notMem] lemma WCovBy.of_le_of_le (hac : a ⩿ c) (hab : a ≤ b) (hbc : b ≤ c) : b ⩿ c := ⟨hbc, fun _x hbx hxc ↦ hac.2 (hab.trans_lt hbx) hxc⟩ lemma WCovBy.of_le_of_le' (hac : a ⩿ c) (hab : a ≤ b) (hbc : b ≤ c) : a ⩿ b := ⟨hab, fun _x hax hxb ↦ hac.2 hax <| hxb.trans_le hbc⟩ theorem WCovBy.of_image (f : α ↪o β) (h : f a ⩿ f b) : a ⩿ b := ⟨f.le_iff_le.mp h.le, fun _ hac hcb => h.2 (f.lt_iff_lt.mpr hac) (f.lt_iff_lt.mpr hcb)⟩ theorem WCovBy.image (f : α ↪o β) (hab : a ⩿ b) (h : (range f).OrdConnected) : f a ⩿ f b := by refine ⟨f.monotone hab.le, fun c ha hb => ?_⟩ obtain ⟨c, rfl⟩ := h.out (mem_range_self _) (mem_range_self _) ⟨ha.le, hb.le⟩ rw [f.lt_iff_lt] at ha hb exact hab.2 ha hb theorem Set.OrdConnected.apply_wcovBy_apply_iff (f : α ↪o β) (h : (range f).OrdConnected) : f a ⩿ f b ↔ a ⩿ b := ⟨fun h2 => h2.of_image f, fun hab => hab.image f h⟩ @[simp] theorem apply_wcovBy_apply_iff {E : Type*} [EquivLike E α β] [OrderIsoClass E α β] (e : E) : e a ⩿ e b ↔ a ⩿ b := (ordConnected_range (e : α ≃o β)).apply_wcovBy_apply_iff ((e : α ≃o β) : α ↪o β) @[simp] theorem toDual_wcovBy_toDual_iff : toDual b ⩿ toDual a ↔ a ⩿ b := and_congr_right' <| forall_congr' fun _ => forall_swap @[simp] theorem ofDual_wcovBy_ofDual_iff {a b : αᵒᵈ} : ofDual a ⩿ ofDual b ↔ b ⩿ a := and_congr_right' <| forall_congr' fun _ => forall_swap alias ⟨_, WCovBy.toDual⟩ := toDual_wcovBy_toDual_iff alias ⟨_, WCovBy.ofDual⟩ := ofDual_wcovBy_ofDual_iff @[deprecated (since := "2025-11-07")] alias OrderEmbedding.wcovBy_of_apply := WCovBy.of_image @[deprecated (since := "2025-11-07")] alias OrderIso.map_wcovBy := apply_wcovBy_apply_iff end Preorder section PartialOrder variable [PartialOrder α] {a b c : α} theorem WCovBy.eq_or_eq (h : a ⩿ b) (h2 : a ≤ c) (h3 : c ≤ b) : c = a ∨ c = b := by rcases h2.eq_or_lt with (h2 | h2); · exact Or.inl h2.symm rcases h3.eq_or_lt with (h3 | h3); · exact Or.inr h3 exact (h.2 h2 h3).elim /-- An `iff` version of `WCovBy.eq_or_eq` and `wcovBy_of_eq_or_eq`. -/ theorem wcovBy_iff_le_and_eq_or_eq : a ⩿ b ↔ a ≤ b ∧ ∀ c, a ≤ c → c ≤ b → c = a ∨ c = b := ⟨fun h => ⟨h.le, fun _ => h.eq_or_eq⟩, And.rec wcovBy_of_eq_or_eq⟩ theorem WCovBy.le_and_le_iff (h : a ⩿ b) : a ≤ c ∧ c ≤ b ↔ c = a ∨ c = b := by refine ⟨fun h2 => h.eq_or_eq h2.1 h2.2, ?_⟩; rintro (rfl | rfl) exacts [⟨le_rfl, h.le⟩, ⟨h.le, le_rfl⟩] theorem WCovBy.Icc_eq (h : a ⩿ b) : Icc a b = {a, b} := by ext c exact h.le_and_le_iff theorem WCovBy.Ico_subset (h : a ⩿ b) : Ico a b ⊆ {a} := by rw [← Icc_diff_right, h.Icc_eq, diff_singleton_subset_iff, pair_comm] theorem WCovBy.Ioc_subset (h : a ⩿ b) : Ioc a b ⊆ {b} := by rw [← Icc_diff_left, h.Icc_eq, diff_singleton_subset_iff] end PartialOrder section SemilatticeSup variable [SemilatticeSup α] {a b c : α} theorem WCovBy.sup_eq (hac : a ⩿ c) (hbc : b ⩿ c) (hab : a ≠ b) : a ⊔ b = c := (sup_le hac.le hbc.le).eq_of_not_lt fun h => hab.lt_sup_or_lt_sup.elim (fun h' => hac.2 h' h) fun h' => hbc.2 h' h end SemilatticeSup section SemilatticeInf variable [SemilatticeInf α] {a b c : α} theorem WCovBy.inf_eq (hca : c ⩿ a) (hcb : c ⩿ b) (hab : a ≠ b) : a ⊓ b = c := (le_inf hca.le hcb.le).eq_of_not_lt' fun h => hab.inf_lt_or_inf_lt.elim (hca.2 h) (hcb.2 h) end SemilatticeInf end WeaklyCovers section LT variable [LT α] {a b : α} theorem CovBy.lt (h : a ⋖ b) : a < b := h.1 /-- If `a < b`, then `b` does not cover `a` iff there's an element in between. -/ theorem not_covBy_iff (h : a < b) : ¬a ⋖ b ↔ ∃ c, a < c ∧ c < b := by simp_rw [CovBy, h, true_and, not_forall, exists_prop, not_not] alias ⟨exists_lt_lt_of_not_covBy, _⟩ := not_covBy_iff alias LT.lt.exists_lt_lt := exists_lt_lt_of_not_covBy /-- In a dense order, nothing covers anything. -/ theorem not_covBy [DenselyOrdered α] : ¬a ⋖ b := fun h => let ⟨_, hc⟩ := exists_between h.1 h.2 hc.1 hc.2 theorem denselyOrdered_iff_forall_not_covBy : DenselyOrdered α ↔ ∀ a b : α, ¬a ⋖ b := ⟨fun h _ _ => @not_covBy _ _ _ _ h, fun h => ⟨fun _ _ hab => exists_lt_lt_of_not_covBy hab <| h _ _⟩⟩ @[simp] theorem toDual_covBy_toDual_iff : toDual b ⋖ toDual a ↔ a ⋖ b := and_congr_right' <| forall_congr' fun _ => forall_swap @[simp] theorem ofDual_covBy_ofDual_iff {a b : αᵒᵈ} : ofDual a ⋖ ofDual b ↔ b ⋖ a := and_congr_right' <| forall_congr' fun _ => forall_swap alias ⟨_, CovBy.toDual⟩ := toDual_covBy_toDual_iff alias ⟨_, CovBy.ofDual⟩ := ofDual_covBy_ofDual_iff end LT section Preorder variable [Preorder α] [Preorder β] {a b c : α} theorem CovBy.le (h : a ⋖ b) : a ≤ b := h.1.le protected theorem CovBy.ne (h : a ⋖ b) : a ≠ b := h.lt.ne theorem CovBy.ne' (h : a ⋖ b) : b ≠ a := h.lt.ne' protected theorem CovBy.wcovBy (h : a ⋖ b) : a ⩿ b := ⟨h.le, h.2⟩ theorem WCovBy.covBy_of_not_le (h : a ⩿ b) (h2 : ¬b ≤ a) : a ⋖ b := ⟨h.le.lt_of_not_ge h2, h.2⟩ theorem WCovBy.covBy_of_lt (h : a ⩿ b) (h2 : a < b) : a ⋖ b := ⟨h2, h.2⟩ lemma CovBy.of_le_of_lt (hac : a ⋖ c) (hab : a ≤ b) (hbc : b < c) : b ⋖ c := ⟨hbc, fun _x hbx hxc ↦ hac.2 (hab.trans_lt hbx) hxc⟩ lemma CovBy.of_lt_of_le (hac : a ⋖ c) (hab : a < b) (hbc : b ≤ c) : a ⋖ b := ⟨hab, fun _x hax hxb ↦ hac.2 hax <| hxb.trans_le hbc⟩ theorem not_covBy_of_lt_of_lt (h₁ : a < b) (h₂ : b < c) : ¬a ⋖ c := (not_covBy_iff (h₁.trans h₂)).2 ⟨b, h₁, h₂⟩ theorem covBy_iff_wcovBy_and_lt : a ⋖ b ↔ a ⩿ b ∧ a < b := ⟨fun h => ⟨h.wcovBy, h.lt⟩, fun h => h.1.covBy_of_lt h.2⟩ theorem covBy_iff_wcovBy_and_not_le : a ⋖ b ↔ a ⩿ b ∧ ¬b ≤ a := ⟨fun h => ⟨h.wcovBy, h.lt.not_ge⟩, fun h => h.1.covBy_of_not_le h.2⟩ theorem wcovBy_iff_covBy_or_le_and_le : a ⩿ b ↔ a ⋖ b ∨ a ≤ b ∧ b ≤ a := ⟨fun h => or_iff_not_imp_right.mpr fun h' => h.covBy_of_not_le fun hba => h' ⟨h.le, hba⟩, fun h' => h'.elim (fun h => h.wcovBy) fun h => h.1.wcovBy_of_le h.2⟩ alias ⟨WCovBy.covBy_or_le_and_le, _⟩ := wcovBy_iff_covBy_or_le_and_le theorem AntisymmRel.trans_covBy (hab : AntisymmRel (· ≤ ·) a b) (hbc : b ⋖ c) : a ⋖ c := ⟨hab.1.trans_lt hbc.lt, fun _ had hdc => hbc.2 (hab.2.trans_lt had) hdc⟩ theorem covBy_congr_left (hab : AntisymmRel (· ≤ ·) a b) : a ⋖ c ↔ b ⋖ c := ⟨hab.symm.trans_covBy, hab.trans_covBy⟩ theorem CovBy.trans_antisymmRel (hab : a ⋖ b) (hbc : AntisymmRel (· ≤ ·) b c) : a ⋖ c := ⟨hab.lt.trans_le hbc.1, fun _ had hdb => hab.2 had <| hdb.trans_le hbc.2⟩ theorem covBy_congr_right (hab : AntisymmRel (· ≤ ·) a b) : c ⋖ a ↔ c ⋖ b := ⟨fun h => h.trans_antisymmRel hab, fun h => h.trans_antisymmRel hab.symm⟩ instance : IsNonstrictStrictOrder α (· ⩿ ·) (· ⋖ ·) := ⟨fun _ _ => covBy_iff_wcovBy_and_not_le.trans <| and_congr_right fun h => h.wcovBy_iff_le.not.symm⟩ instance CovBy.isIrrefl : IsIrrefl α (· ⋖ ·) := ⟨fun _ ha => ha.ne rfl⟩ theorem CovBy.Ioo_eq (h : a ⋖ b) : Ioo a b = ∅ := h.wcovBy.Ioo_eq theorem covBy_iff_Ioo_eq : a ⋖ b ↔ a < b ∧ Ioo a b = ∅ := and_congr_right' <| by simp [eq_empty_iff_forall_notMem] theorem CovBy.of_image (f : α ↪o β) (h : f a ⋖ f b) : a ⋖ b := ⟨f.lt_iff_lt.mp h.lt, fun _ hac hcb => h.2 (f.lt_iff_lt.mpr hac) (f.lt_iff_lt.mpr hcb)⟩ theorem CovBy.image (f : α ↪o β) (hab : a ⋖ b) (h : (range f).OrdConnected) : f a ⋖ f b := (hab.wcovBy.image f h).covBy_of_lt <| f.strictMono hab.lt theorem Set.OrdConnected.apply_covBy_apply_iff (f : α ↪o β) (h : (range f).OrdConnected) : f a ⋖ f b ↔ a ⋖ b := ⟨CovBy.of_image f, fun hab => hab.image f h⟩ @[simp] theorem apply_covBy_apply_iff {E : Type*} [EquivLike E α β] [OrderIsoClass E α β] (e : E) : e a ⋖ e b ↔ a ⋖ b := (ordConnected_range (e : α ≃o β)).apply_covBy_apply_iff ((e : α ≃o β) : α ↪o β) theorem covBy_of_eq_or_eq (hab : a < b) (h : ∀ c, a ≤ c → c ≤ b → c = a ∨ c = b) : a ⋖ b := ⟨hab, fun c ha hb => (h c ha.le hb.le).elim ha.ne' hb.ne⟩ @[deprecated (since := "2025-11-07")] alias OrderEmbedding.covBy_of_apply := CovBy.of_image @[deprecated (since := "2025-11-07")] alias OrderIso.map_covBy := apply_covBy_apply_iff end Preorder section PartialOrder variable [PartialOrder α] {a b c : α} theorem WCovBy.covBy_of_ne (h : a ⩿ b) (h2 : a ≠ b) : a ⋖ b := ⟨h.le.lt_of_ne h2, h.2⟩ theorem covBy_iff_wcovBy_and_ne : a ⋖ b ↔ a ⩿ b ∧ a ≠ b := ⟨fun h => ⟨h.wcovBy, h.ne⟩, fun h => h.1.covBy_of_ne h.2⟩ theorem wcovBy_iff_covBy_or_eq : a ⩿ b ↔ a ⋖ b ∨ a = b := by rw [le_antisymm_iff, wcovBy_iff_covBy_or_le_and_le] theorem wcovBy_iff_eq_or_covBy : a ⩿ b ↔ a = b ∨ a ⋖ b := wcovBy_iff_covBy_or_eq.trans or_comm alias ⟨WCovBy.covBy_or_eq, _⟩ := wcovBy_iff_covBy_or_eq alias ⟨WCovBy.eq_or_covBy, _⟩ := wcovBy_iff_eq_or_covBy theorem CovBy.eq_or_eq (h : a ⋖ b) (h2 : a ≤ c) (h3 : c ≤ b) : c = a ∨ c = b := h.wcovBy.eq_or_eq h2 h3 /-- An `iff` version of `CovBy.eq_or_eq` and `covBy_of_eq_or_eq`. -/ theorem covBy_iff_lt_and_eq_or_eq : a ⋖ b ↔ a < b ∧ ∀ c, a ≤ c → c ≤ b → c = a ∨ c = b := ⟨fun h => ⟨h.lt, fun _ => h.eq_or_eq⟩, And.rec covBy_of_eq_or_eq⟩ theorem CovBy.Ico_eq (h : a ⋖ b) : Ico a b = {a} := by rw [← Ioo_union_left h.lt, h.Ioo_eq, empty_union] theorem CovBy.Ioc_eq (h : a ⋖ b) : Ioc a b = {b} := by rw [← Ioo_union_right h.lt, h.Ioo_eq, empty_union] theorem CovBy.Icc_eq (h : a ⋖ b) : Icc a b = {a, b} := h.wcovBy.Icc_eq end PartialOrder section LinearOrder variable [LinearOrder α] {a b c : α} theorem CovBy.Ioi_eq (h : a ⋖ b) : Ioi a = Ici b := by rw [← Ioo_union_Ici_eq_Ioi h.lt, h.Ioo_eq, empty_union] theorem CovBy.Iio_eq (h : a ⋖ b) : Iio b = Iic a := by rw [← Iic_union_Ioo_eq_Iio h.lt, h.Ioo_eq, union_empty] theorem WCovBy.le_of_lt (hab : a ⩿ b) (hcb : c < b) : c ≤ a := not_lt.1 fun hac => hab.2 hac hcb theorem WCovBy.ge_of_gt (hab : a ⩿ b) (hac : a < c) : b ≤ c := not_lt.1 <| hab.2 hac theorem CovBy.le_of_lt (hab : a ⋖ b) : c < b → c ≤ a := hab.wcovBy.le_of_lt theorem CovBy.ge_of_gt (hab : a ⋖ b) : a < c → b ≤ c := hab.wcovBy.ge_of_gt theorem CovBy.unique_left (ha : a ⋖ c) (hb : b ⋖ c) : a = b := (hb.le_of_lt ha.lt).antisymm <| ha.le_of_lt hb.lt theorem CovBy.unique_right (hb : a ⋖ b) (hc : a ⋖ c) : b = c := (hb.ge_of_gt hc.lt).antisymm <| hc.ge_of_gt hb.lt /-- If `a`, `b`, `c` are consecutive and `a < x < c` then `x = b`. -/ theorem CovBy.eq_of_between {x : α} (hab : a ⋖ b) (hbc : b ⋖ c) (hax : a < x) (hxc : x < c) : x = b := le_antisymm (le_of_not_gt fun h => hbc.2 h hxc) (le_of_not_gt <| hab.2 hax) theorem covBy_iff_lt_iff_le_left {x y : α} : x ⋖ y ↔ ∀ {z}, z < y ↔ z ≤ x where mp := fun hx _z ↦ ⟨hx.le_of_lt, fun hz ↦ hz.trans_lt hx.lt⟩ mpr := fun H ↦ ⟨H.2 le_rfl, fun _z hx hz ↦ (H.1 hz).not_gt hx⟩ theorem covBy_iff_le_iff_lt_left {x y : α} : x ⋖ y ↔ ∀ {z}, z ≤ x ↔ z < y := by simp_rw [covBy_iff_lt_iff_le_left, iff_comm] theorem covBy_iff_lt_iff_le_right {x y : α} : x ⋖ y ↔ ∀ {z}, x < z ↔ y ≤ z := by trans ∀ {z}, ¬ z ≤ x ↔ ¬ z < y · simp_rw [covBy_iff_le_iff_lt_left, not_iff_not] · simp theorem covBy_iff_le_iff_lt_right {x y : α} : x ⋖ y ↔ ∀ {z}, y ≤ z ↔ x < z := by simp_rw [covBy_iff_lt_iff_le_right, iff_comm] alias ⟨CovBy.lt_iff_le_left, _⟩ := covBy_iff_lt_iff_le_left alias ⟨CovBy.le_iff_lt_left, _⟩ := covBy_iff_le_iff_lt_left alias ⟨CovBy.lt_iff_le_right, _⟩ := covBy_iff_lt_iff_le_right alias ⟨CovBy.le_iff_lt_right, _⟩ := covBy_iff_le_iff_lt_right /-- If `a < b` then there exist `a' > a` and `b' < b` such that `Set.Iio a'` is strictly to the left of `Set.Ioi b'`. -/ lemma LT.lt.exists_disjoint_Iio_Ioi (h : a < b) : ∃ a' > a, ∃ b' < b, ∀ x < a', ∀ y > b', x < y := by grind end LinearOrder namespace Bool @[simp] theorem wcovBy_iff : ∀ {a b : Bool}, a ⩿ b ↔ a ≤ b := by unfold WCovBy; decide @[simp] theorem covBy_iff : ∀ {a b : Bool}, a ⋖ b ↔ a < b := by unfold CovBy; decide instance instDecidableRelWCovBy : DecidableRel (· ⩿ · : Bool → Bool → Prop) := fun _ _ ↦ decidable_of_iff _ wcovBy_iff.symm instance instDecidableRelCovBy : DecidableRel (· ⋖ · : Bool → Bool → Prop) := fun _ _ ↦ decidable_of_iff _ covBy_iff.symm end Bool namespace Set variable {s t : Set α} {a : α} @[simp] lemma wcovBy_insert (x : α) (s : Set α) : s ⩿ insert x s := by refine wcovBy_of_eq_or_eq (subset_insert x s) fun t hst h2t => ?_ by_cases h : x ∈ t · exact Or.inr (subset_antisymm h2t <| insert_subset_iff.mpr ⟨h, hst⟩) · refine Or.inl (subset_antisymm ?_ hst) rwa [← diff_singleton_eq_self h, diff_singleton_subset_iff] @[simp] lemma sdiff_singleton_wcovBy (s : Set α) (a : α) : s \ {a} ⩿ s := by by_cases ha : a ∈ s · convert wcovBy_insert a _ ext simp [ha] · simp [ha] @[simp] lemma covBy_insert (ha : a ∉ s) : s ⋖ insert a s := (wcovBy_insert _ _).covBy_of_lt <| ssubset_insert ha @[simp] lemma empty_covBy_singleton (a : α) : ∅ ⋖ ({a} : Set α) := insert_empty_eq (β := Set α) a ▸ covBy_insert <| notMem_empty a @[simp] lemma sdiff_singleton_covBy (ha : a ∈ s) : s \ {a} ⋖ s := ⟨sdiff_lt (singleton_subset_iff.2 ha) <| singleton_ne_empty _, (sdiff_singleton_wcovBy _ _).2⟩ lemma _root_.CovBy.exists_set_insert (h : s ⋖ t) : ∃ a ∉ s, insert a s = t := let ⟨a, ha, hst⟩ := ssubset_iff_insert.1 h.lt ⟨a, ha, (hst.eq_of_not_ssuperset <| h.2 <| ssubset_insert ha).symm⟩ lemma _root_.CovBy.exists_set_sdiff_singleton (h : s ⋖ t) : ∃ a ∈ t, t \ {a} = s := let ⟨a, ha, hst⟩ := ssubset_iff_sdiff_singleton.1 h.lt ⟨a, ha, (hst.eq_of_not_ssubset fun h' ↦ h.2 h' <| sdiff_lt (singleton_subset_iff.2 ha) <| singleton_ne_empty _).symm⟩ lemma covBy_iff_exists_insert : s ⋖ t ↔ ∃ a ∉ s, insert a s = t := ⟨CovBy.exists_set_insert, by rintro ⟨a, ha, rfl⟩; exact covBy_insert ha⟩ lemma covBy_iff_exists_sdiff_singleton : s ⋖ t ↔ ∃ a ∈ t, t \ {a} = s := ⟨CovBy.exists_set_sdiff_singleton, by rintro ⟨a, ha, rfl⟩; exact sdiff_singleton_covBy ha⟩ end Set section Relation open Relation lemma wcovBy_eq_reflGen_covBy [PartialOrder α] : (· ⩿ · : α → α → Prop) = ReflGen (· ⋖ ·) := by ext x y; simp_rw [wcovBy_iff_eq_or_covBy, @eq_comm _ x, reflGen_iff] lemma transGen_wcovBy_eq_reflTransGen_covBy [PartialOrder α] : TransGen (· ⩿ · : α → α → Prop) = ReflTransGen (· ⋖ ·) := by rw [wcovBy_eq_reflGen_covBy, transGen_reflGen] lemma reflTransGen_wcovBy_eq_reflTransGen_covBy [PartialOrder α] : ReflTransGen (· ⩿ · : α → α → Prop) = ReflTransGen (· ⋖ ·) := by rw [wcovBy_eq_reflGen_covBy, reflTransGen_reflGen] end Relation namespace Prod variable [PartialOrder α] [PartialOrder β] {a a₁ a₂ : α} {b b₁ b₂ : β} {x y : α × β} @[simp] theorem swap_wcovBy_swap : x.swap ⩿ y.swap ↔ x ⩿ y := apply_wcovBy_apply_iff (OrderIso.prodComm : α × β ≃o β × α) @[simp] theorem swap_covBy_swap : x.swap ⋖ y.swap ↔ x ⋖ y := apply_covBy_apply_iff (OrderIso.prodComm : α × β ≃o β × α) theorem fst_eq_or_snd_eq_of_wcovBy : x ⩿ y → x.1 = y.1 ∨ x.2 = y.2 := by refine fun h => of_not_not fun hab => ?_ push_neg at hab exact h.2 (mk_lt_mk.2 <| Or.inl ⟨hab.1.lt_of_le h.1.1, le_rfl⟩) (mk_lt_mk.2 <| Or.inr ⟨le_rfl, hab.2.lt_of_le h.1.2⟩) theorem _root_.WCovBy.fst (h : x ⩿ y) : x.1 ⩿ y.1 := ⟨h.1.1, fun _ h₁ h₂ => h.2 (mk_lt_mk_iff_left.2 h₁) ⟨⟨h₂.le, h.1.2⟩, fun hc => h₂.not_ge hc.1⟩⟩ theorem _root_.WCovBy.snd (h : x ⩿ y) : x.2 ⩿ y.2 := ⟨h.1.2, fun _ h₁ h₂ => h.2 (mk_lt_mk_iff_right.2 h₁) ⟨⟨h.1.1, h₂.le⟩, fun hc => h₂.not_ge hc.2⟩⟩ theorem mk_wcovBy_mk_iff_left : (a₁, b) ⩿ (a₂, b) ↔ a₁ ⩿ a₂ := by refine ⟨WCovBy.fst, (And.imp mk_le_mk_iff_left.2) fun h c h₁ h₂ => ?_⟩ have : c.2 = b := h₂.le.2.antisymm h₁.le.2 rw [← @Prod.mk.eta _ _ c, this, mk_lt_mk_iff_left] at h₁ h₂ exact h h₁ h₂ theorem mk_wcovBy_mk_iff_right : (a, b₁) ⩿ (a, b₂) ↔ b₁ ⩿ b₂ := swap_wcovBy_swap.trans mk_wcovBy_mk_iff_left theorem mk_covBy_mk_iff_left : (a₁, b) ⋖ (a₂, b) ↔ a₁ ⋖ a₂ := by simp_rw [covBy_iff_wcovBy_and_lt, mk_wcovBy_mk_iff_left, mk_lt_mk_iff_left] theorem mk_covBy_mk_iff_right : (a, b₁) ⋖ (a, b₂) ↔ b₁ ⋖ b₂ := by simp_rw [covBy_iff_wcovBy_and_lt, mk_wcovBy_mk_iff_right, mk_lt_mk_iff_right] theorem mk_wcovBy_mk_iff : (a₁, b₁) ⩿ (a₂, b₂) ↔ a₁ ⩿ a₂ ∧ b₁ = b₂ ∨ b₁ ⩿ b₂ ∧ a₁ = a₂ := by refine ⟨fun h => ?_, ?_⟩ · obtain rfl | rfl : a₁ = a₂ ∨ b₁ = b₂ := fst_eq_or_snd_eq_of_wcovBy h · exact Or.inr ⟨mk_wcovBy_mk_iff_right.1 h, rfl⟩ · exact Or.inl ⟨mk_wcovBy_mk_iff_left.1 h, rfl⟩ · rintro (⟨h, rfl⟩ | ⟨h, rfl⟩) · exact mk_wcovBy_mk_iff_left.2 h · exact mk_wcovBy_mk_iff_right.2 h theorem mk_covBy_mk_iff : (a₁, b₁) ⋖ (a₂, b₂) ↔ a₁ ⋖ a₂ ∧ b₁ = b₂ ∨ b₁ ⋖ b₂ ∧ a₁ = a₂ := by refine ⟨fun h => ?_, ?_⟩ · obtain rfl | rfl : a₁ = a₂ ∨ b₁ = b₂ := fst_eq_or_snd_eq_of_wcovBy h.wcovBy · exact Or.inr ⟨mk_covBy_mk_iff_right.1 h, rfl⟩ · exact Or.inl ⟨mk_covBy_mk_iff_left.1 h, rfl⟩ · rintro (⟨h, rfl⟩ | ⟨h, rfl⟩) · exact mk_covBy_mk_iff_left.2 h · exact mk_covBy_mk_iff_right.2 h theorem wcovBy_iff : x ⩿ y ↔ x.1 ⩿ y.1 ∧ x.2 = y.2 ∨ x.2 ⩿ y.2 ∧ x.1 = y.1 := by cases x cases y exact mk_wcovBy_mk_iff theorem covBy_iff : x ⋖ y ↔ x.1 ⋖ y.1 ∧ x.2 = y.2 ∨ x.2 ⋖ y.2 ∧ x.1 = y.1 := by cases x cases y exact mk_covBy_mk_iff end Prod namespace Pi section Preorder variable {ι : Type*} {α : ι → Type*} [∀ i, Preorder (α i)] {a b : (i : ι) → α i} lemma _root_.WCovBy.eval (h : a ⩿ b) (i : ι) : a i ⩿ b i := by classical refine ⟨h.1 i, fun ci h₁ h₂ ↦ ?_⟩ have hcb : Function.update a i ci ≤ b := by simpa [update_le_iff, h₂.le] using fun j hj ↦ h.1 j refine h.2 (by simpa) (lt_of_le_not_ge hcb ?_) simp [le_update_iff, h₂.not_ge] lemma exists_forall_antisymmRel_of_covBy (h : a ⋖ b) : ∃ i, ∀ j ≠ i, AntisymmRel (· ≤ ·) (a j) (b j) := by classical simp only [CovBy, Pi.lt_def, not_and, and_imp, forall_exists_index, not_exists] at h obtain ⟨⟨hab, ⟨i, hi⟩⟩, h⟩ := h refine ⟨i, fun j hj ↦ ?_⟩ let c : (i : ι) → α i := Function.update a i (b i) have h₁ : c ≤ b := by simpa [update_le_iff, c] using fun k hk ↦ hab k have h₂ : ¬ c j < b j := h (by simp [c, hi.le]) i (by simpa [c]) h₁ j exact ⟨hab j, by simpa [lt_iff_le_not_ge, hab j, c, hj] using h₂⟩ lemma exists_forall_antisymmRel_of_wcovBy [Nonempty ι] (h : a ⩿ b) : ∃ i, ∀ j ≠ i, AntisymmRel (· ≤ ·) (a j) (b j) := by rw [wcovBy_iff_covBy_or_le_and_le] at h obtain h | h := h · exact exists_forall_antisymmRel_of_covBy h · inhabit ι exact ⟨default, fun j hj ↦ ⟨h.left j, h.right j⟩⟩ /-- A characterisation of the `WCovBy` relation in products of preorders. See `Pi.wcovBy_iff` for the (more common) version in products of partial orders. -/ lemma wcovBy_iff_antisymmRel [Nonempty ι] : a ⩿ b ↔ ∃ i, a i ⩿ b i ∧ ∀ j ≠ i, AntisymmRel (· ≤ ·) (a j) (b j) := by constructor · intro h obtain ⟨i, hi⟩ := exists_forall_antisymmRel_of_wcovBy h exact ⟨i, h.eval _, hi⟩ rintro ⟨i, hab, h⟩ refine ⟨fun j ↦ (eq_or_ne j i).elim (· ▸ hab.1) (h j · |>.1), fun c hac hcb ↦ ?_⟩ have haci : a i < c i := by obtain ⟨hac, j, hj⟩ := Pi.lt_def.1 hac exact (eq_or_ne j i).elim (· ▸ hj) fun hj' ↦ ((lt_of_antisymmRel_of_lt (h j hj').symm hj).not_ge (hcb.le j)).elim have hcbi : c i < b i := by obtain ⟨hcb, j, hj⟩ := Pi.lt_def.1 hcb exact (eq_or_ne j i).elim (· ▸ hj) fun hj' ↦ ((lt_of_lt_of_antisymmRel hj (h j hj').symm).not_ge (hac.le j)).elim exact hab.2 haci hcbi /-- A characterisation of the `CovBy` relation in products of preorders. See `Pi.covBy_iff` for the (more common) version in products of partial orders. -/ lemma covBy_iff_antisymmRel : a ⋖ b ↔ ∃ i, a i ⋖ b i ∧ ∀ j ≠ i, AntisymmRel (· ≤ ·) (a j) (b j) := by constructor · intro h obtain ⟨j, hj⟩ := (Pi.lt_def.1 h.1).2 have : Nonempty ι := ⟨j⟩ obtain ⟨i, hi⟩ := exists_forall_antisymmRel_of_wcovBy h.wcovBy obtain rfl : i = j := by_contra fun this ↦ (hi j (Ne.symm this)).2.not_gt hj exact ⟨i, covBy_iff_wcovBy_and_lt.2 ⟨h.wcovBy.eval i, hj⟩, hi⟩ rintro ⟨i, hi, h⟩ have : Nonempty ι := ⟨i⟩ refine covBy_iff_wcovBy_and_lt.2 ⟨wcovBy_iff_antisymmRel.2 ⟨i, hi.wcovBy, h⟩, ?_⟩ exact Pi.lt_def.2 ⟨fun j ↦ (eq_or_ne j i).elim (· ▸ hi.1.le) (h j · |>.1), i, hi.1⟩ end Preorder section PartialOrder variable {ι : Type*} {α : ι → Type*} [∀ i, PartialOrder (α i)] {a b : (i : ι) → α i} lemma exists_forall_eq_of_covBy (h : a ⋖ b) : ∃ i, ∀ j ≠ i, a j = b j := by obtain ⟨i, hi⟩ := exists_forall_antisymmRel_of_covBy h exact ⟨i, fun j hj ↦ AntisymmRel.eq (hi _ hj)⟩ lemma exists_forall_eq_of_wcovBy [Nonempty ι] (h : a ⩿ b) : ∃ i, ∀ j ≠ i, a j = b j := by obtain ⟨i, hi⟩ := exists_forall_antisymmRel_of_wcovBy h exact ⟨i, fun j hj ↦ AntisymmRel.eq (hi _ hj)⟩ lemma wcovBy_iff [Nonempty ι] : a ⩿ b ↔ ∃ i, a i ⩿ b i ∧ ∀ j ≠ i, a j = b j := by simp [wcovBy_iff_antisymmRel] lemma covBy_iff : a ⋖ b ↔ ∃ i, a i ⋖ b i ∧ ∀ j ≠ i, a j = b j := by simp [covBy_iff_antisymmRel] lemma wcovBy_iff_exists_right_eq [Nonempty ι] [DecidableEq ι] : a ⩿ b ↔ ∃ i x, a i ⩿ x ∧ b = Function.update a i x := by rw [wcovBy_iff] constructor · rintro ⟨i, hi, h⟩ exact ⟨i, b i, hi, by simpa [Function.eq_update_iff, eq_comm] using h⟩ · rintro ⟨i, x, h, rfl⟩ exact ⟨i, by simpa +contextual⟩ lemma covBy_iff_exists_right_eq [DecidableEq ι] : a ⋖ b ↔ ∃ i x, a i ⋖ x ∧ b = Function.update a i x := by rw [covBy_iff] constructor · rintro ⟨i, hi, h⟩ exact ⟨i, b i, hi, by simpa [Function.eq_update_iff, eq_comm] using h⟩ · rintro ⟨i, x, h, rfl⟩ exact ⟨i, by simpa +contextual⟩ lemma wcovBy_iff_exists_left_eq [Nonempty ι] [DecidableEq ι] : a ⩿ b ↔ ∃ i x, x ⩿ b i ∧ a = Function.update b i x := by rw [wcovBy_iff] constructor · rintro ⟨i, hi, h⟩ exact ⟨i, a i, hi, by simpa [Function.eq_update_iff, eq_comm] using h⟩ · rintro ⟨i, x, h, rfl⟩ exact ⟨i, by simpa +contextual⟩ lemma covBy_iff_exists_left_eq [DecidableEq ι] : a ⋖ b ↔ ∃ i x, x ⋖ b i ∧ a = Function.update b i x := by rw [covBy_iff] constructor · rintro ⟨i, hi, h⟩ exact ⟨i, a i, hi, by simpa [Function.eq_update_iff, eq_comm] using h⟩ · rintro ⟨i, x, h, rfl⟩ exact ⟨i, by simpa +contextual⟩ end PartialOrder end Pi namespace WithTop variable [Preorder α] {a b : α} @[simp, norm_cast] lemma coe_wcovBy_coe : (a : WithTop α) ⩿ b ↔ a ⩿ b := Set.OrdConnected.apply_wcovBy_apply_iff WithTop.coeOrderHom <| by simp [WithTop.range_coe, ordConnected_Iio] @[simp, norm_cast] lemma coe_covBy_coe : (a : WithTop α) ⋖ b ↔ a ⋖ b := Set.OrdConnected.apply_covBy_apply_iff WithTop.coeOrderHom <| by simp [WithTop.range_coe, ordConnected_Iio] @[simp] lemma coe_covBy_top : (a : WithTop α) ⋖ ⊤ ↔ IsMax a := by simp only [covBy_iff_Ioo_eq, ← image_coe_Ioi, coe_lt_top, image_eq_empty, true_and, Ioi_eq_empty_iff] @[simp] lemma coe_wcovBy_top : (a : WithTop α) ⩿ ⊤ ↔ IsMax a := by simp only [wcovBy_iff_Ioo_eq, ← image_coe_Ioi, le_top, image_eq_empty, true_and, Ioi_eq_empty_iff] end WithTop namespace WithBot variable [Preorder α] {a b : α} @[simp, norm_cast] lemma coe_wcovBy_coe : (a : WithBot α) ⩿ b ↔ a ⩿ b := Set.OrdConnected.apply_wcovBy_apply_iff WithBot.coeOrderHom <| by simp [WithBot.range_coe, ordConnected_Ioi] @[simp, norm_cast] lemma coe_covBy_coe : (a : WithBot α) ⋖ b ↔ a ⋖ b := Set.OrdConnected.apply_covBy_apply_iff WithBot.coeOrderHom <| by simp [WithBot.range_coe, ordConnected_Ioi] @[simp] lemma bot_covBy_coe : ⊥ ⋖ (a : WithBot α) ↔ IsMin a := by simp only [covBy_iff_Ioo_eq, ← image_coe_Iio, bot_lt_coe, image_eq_empty, true_and, Iio_eq_empty_iff] @[simp] lemma bot_wcovBy_coe : ⊥ ⩿ (a : WithBot α) ↔ IsMin a := by simp only [wcovBy_iff_Ioo_eq, ← image_coe_Iio, bot_le, image_eq_empty, true_and, Iio_eq_empty_iff] end WithBot section WellFounded variable [Preorder α] lemma exists_covBy_of_wellFoundedLT [wf : WellFoundedLT α] ⦃a : α⦄ (h : ¬ IsMax a) : ∃ a', a ⋖ a' := by rw [not_isMax_iff] at h exact ⟨_, wellFounded_lt.min_mem _ h, fun a' ↦ wf.wf.not_lt_min _ h⟩ lemma exists_covBy_of_wellFoundedGT [wf : WellFoundedGT α] ⦃a : α⦄ (h : ¬ IsMin a) : ∃ a', a' ⋖ a := by rw [not_isMin_iff] at h exact ⟨_, wf.wf.min_mem _ h, fun a' h₁ h₂ ↦ wf.wf.not_lt_min _ h h₂ h₁⟩ end WellFounded
.lake/packages/mathlib/Mathlib/Order/BooleanAlgebra.lean
import Mathlib.Order.BooleanAlgebra.Defs import Mathlib.Order.BooleanAlgebra.Basic import Mathlib.Tactic.Linter.DeprecatedModule deprecated_module (since := "2025-06-19")
.lake/packages/mathlib/Mathlib/Order/Sublocale.lean
import Mathlib.Order.Nucleus import Mathlib.Order.SupClosed /-! # Sublocale Locales are the dual concept to frames. Locale theory is a branch of point-free topology, where intuitively locales are like topological spaces which may or may not have enough points. Sublocales of a locale generalize the concept of subspaces in topology to the point-free setting. ## TODO Create separate definitions for `sInf_mem` and `HImpClosed` (also useful for `CompleteSublattice`) ## References * [J. Picada A. Pultr, *Frames and Locales*][picado2012] * https://ncatlab.org/nlab/show/sublocale * https://ncatlab.org/nlab/show/nucleus -/ variable {X : Type*} [Order.Frame X] open Set /-- A sublocale of a locale `X` is a set `S` which is closed under all meets and such that `x ⇨ s ∈ S` for all `x : X` and `s ∈ S`. Note that locales are the same thing as frames, but with reverse morphisms, which is why we assume `Frame X`. We only need to define locales categorically. See `Locale`. -/ structure Sublocale (X : Type*) [Order.Frame X] where /-- The set corresponding to the sublocale. -/ carrier : Set X /-- A sublocale is closed under all meets. Do NOT use directly. Use `Sublocale.sInf_mem` instead. -/ sInf_mem' : ∀ s ⊆ carrier, sInf s ∈ carrier /-- A sublocale is closed under heyting implication. Do NOT use directly. Use `Sublocale.himp_mem` instead. -/ himp_mem' : ∀ a b, b ∈ carrier → a ⇨ b ∈ carrier namespace Sublocale variable {ι : Sort*} {S T : Sublocale X} {s : Set X} {f : ι → X} {a b : X} instance instSetLike : SetLike (Sublocale X) X where coe x := x.carrier coe_injective' s1 s2 h := by cases s1; congr @[simp] lemma mem_carrier : a ∈ S.carrier ↔ a ∈ S := .rfl @[simp] lemma mem_mk (carrier : Set X) (sInf_mem' himp_mem') : a ∈ mk carrier sInf_mem' himp_mem' ↔ a ∈ carrier := .rfl @[simp] lemma mk_le_mk (carrier₁ carrier₂ : Set X) (sInf_mem'₁ sInf_mem'₂ himp_mem'₁ himp_mem'₂) : mk carrier₁ sInf_mem'₁ himp_mem'₁ ≤ mk carrier₂ sInf_mem'₂ himp_mem'₂ ↔ carrier₁ ⊆ carrier₂ := .rfl @[gcongr] alias ⟨_, _root_.GCongr.Sublocale.mk_le_mk⟩ := mk_le_mk initialize_simps_projections Sublocale (carrier → coe, as_prefix coe) @[ext] lemma ext (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := SetLike.ext h lemma sInf_mem (hs : s ⊆ S) : sInf s ∈ S := S.sInf_mem' _ hs lemma iInf_mem (hf : ∀ i, f i ∈ S) : ⨅ i, f i ∈ S := S.sInf_mem <| by simpa [range_subset_iff] lemma infClosed : InfClosed (S : Set X) := by rintro a ha b hb; rw [← sInf_pair]; exact S.sInf_mem (pair_subset ha hb) lemma inf_mem (ha : a ∈ S) (hb : b ∈ S) : a ⊓ b ∈ S := S.infClosed ha hb lemma top_mem : ⊤ ∈ S := by simpa using S.sInf_mem <| empty_subset _ lemma himp_mem (hb : b ∈ S) : a ⇨ b ∈ S := S.himp_mem' _ _ hb instance carrier.instSemilatticeInf : SemilatticeInf S := Subtype.semilatticeInf fun _ _ ↦ inf_mem instance carrier.instOrderTop : OrderTop S := Subtype.orderTop top_mem instance carrier.instHImp : HImp S where himp a b := ⟨a ⇨ b, S.himp_mem b.2⟩ instance carrier.instInfSet : InfSet S where sInf x := ⟨sInf (Subtype.val '' x), S.sInf_mem' _ (by simp_rw [image_subset_iff, subset_def]; simp)⟩ @[simp, norm_cast] lemma coe_inf (a b : S) : (a ⊓ b).val = ↑a ⊓ ↑b := rfl @[simp, norm_cast] lemma coe_sInf (s : Set S) : (sInf s).val = sInf (Subtype.val '' s) := rfl @[simp, norm_cast] lemma coe_iInf (f : ι → S) : (⨅ i, f i).val = ⨅ i, (f i).val := by simp [iInf, ← range_comp, Function.comp_def] instance carrier.instCompleteLattice : CompleteLattice S where __ := instSemilatticeInf __ := instOrderTop __ := completeLatticeOfInf S <| by simp [isGLB_iff_le_iff, lowerBounds, ← Subtype.coe_le_coe] @[simp, norm_cast] lemma coe_himp (a b : S) : (a ⇨ b).val = a.val ⇨ b.val := rfl instance carrier.instHeytingAlgebra : HeytingAlgebra S where le_himp_iff a b c := by simp [← Subtype.coe_le_coe, ← @Sublocale.coe_inf, himp] compl a := a ⇨ ⊥ himp_bot _ := rfl instance carrier.instFrame : Order.Frame S where __ := carrier.instHeytingAlgebra __ := carrier.instCompleteLattice /-- See `Sublocale.restrict` for the public-facing version. -/ private def restrictAux (S : Sublocale X) (a : X) : S := sInf {s : S | a ≤ s} private lemma le_restrictAux : a ≤ S.restrictAux a := by simp +contextual [restrictAux] /-- See `Sublocale.giRestrict` for the public-facing version. -/ private def giAux (S : Sublocale X) : GaloisInsertion S.restrictAux Subtype.val where choice x hx := ⟨x, by rw [le_antisymm le_restrictAux hx] exact S.sInf_mem <| by simp +contextual [Set.subset_def]⟩ gc a b := by constructor <;> intro h · exact le_trans (by simp +contextual [restrictAux]) h · exact sInf_le (by simp [h]) le_l_u x := by simp [restrictAux] choice_eq a h := by simp [le_antisymm_iff, restrictAux, sInf_le] /-- The restriction from a locale X into the sublocale S. -/ def restrict (S : Sublocale X) : FrameHom X S where toFun x := sInf {s : S | x ≤ s} map_inf' a b := by change Sublocale.restrictAux S (a ⊓ b) = Sublocale.restrictAux S a ⊓ Sublocale.restrictAux S b refine eq_of_forall_ge_iff (fun s ↦ Iff.symm ?_) calc _ ↔ S.restrictAux a ≤ S.restrictAux b ⇨ s := by simp _ ↔ S.restrictAux b ≤ a ⇨ s := by rw [S.giAux.gc.le_iff_le, @le_himp_comm, coe_himp] _ ↔ b ≤ a ⇨ s := by set c : S := ⟨a ⇨ s, S.himp_mem s.coe_prop⟩ change Sublocale.restrictAux S b ≤ c.val ↔ b ≤ c rw [S.giAux.u_le_u_iff, S.giAux.gc.le_iff_le] _ ↔ S.restrictAux (a ⊓ b) ≤ s := by simp [inf_comm, S.giAux.gc.le_iff_le] map_sSup' s := by change Sublocale.restrictAux S (sSup s) = _ rw [S.giAux.gc.l_sSup, sSup_image] rfl map_top' := by refine le_antisymm le_top ?_ change _ ≤ restrictAux S ⊤ rw [← Subtype.coe_le_coe, S.giAux.gc.u_top] simp [restrictAux, sInf] /-- The restriction corresponding to a sublocale forms a Galois insertion with the forgetful map from the sublocale to the original locale. -/ def giRestrict (S : Sublocale X) : GaloisInsertion S.restrict Subtype.val := S.giAux @[simp] lemma restrict_of_mem (ha : a ∈ S) : S.restrict a = ⟨a, ha⟩ := S.giRestrict.l_u_eq ⟨a, ha⟩ /-- The restriction from the locale X into a sublocale is a nucleus. -/ @[simps] def toNucleus (S : Sublocale X) : Nucleus X where toFun x := S.restrict x map_inf' _ _ := by simp [S.giRestrict.gc.u_inf] idempotent' _ := by rw [S.giRestrict.gc.l_u_l_eq_l] le_apply' _ := S.giRestrict.gc.le_u_l _ @[simp] lemma range_toNucleus : range S.toNucleus = S := by ext x constructor · simp +contextual [eq_comm] · intro hx exact ⟨x, by simp_all⟩ @[simp] lemma toNucleus_le_toNucleus : S.toNucleus ≤ T.toNucleus ↔ T ≤ S := by simp [← Nucleus.range_subset_range] end Sublocale namespace Nucleus /-- The range of a nucleus is a sublocale. -/ @[simps] def toSublocale (n : Nucleus X) : Sublocale X where carrier := range n sInf_mem' a h := by rw [mem_range] refine le_antisymm (le_sInf_iff.mpr (fun b h1 ↦ ?_)) le_apply simp_rw [subset_def, mem_range] at h rw [← h b h1] exact n.monotone (sInf_le h1) himp_mem' a b h := by rw [mem_range, ← h, map_himp_apply] at * @[simp] lemma mem_toSublocale {n : Nucleus X} {x : X} : x ∈ n.toSublocale ↔ ∃ y, n y = x := .rfl @[simp] lemma toSublocale_le_toSublocale {m n : Nucleus X} : m.toSublocale ≤ n.toSublocale ↔ n ≤ m := by simp [← SetLike.coe_subset_coe] @[gcongr] alias ⟨_, _root_.GCongr.Nucleus.toSublocale_le_toSublocale⟩ := toSublocale_le_toSublocale @[simp] lemma restrict_toSublocale (n : Nucleus X) (x : X) : n.toSublocale.restrict x = ⟨n x, x, rfl⟩ := by ext simpa [Sublocale.restrict, sInf_image, le_antisymm_iff (a := iInf _)] using ⟨iInf₂_le_of_le ⟨n x, x, rfl⟩ n.le_apply le_rfl, fun y hxy ↦ by simpa using n.monotone hxy⟩ end Nucleus /-- The nuclei on a frame corresponds exactly to the sublocales on this frame. The sublocales are ordered dually to the nuclei. -/ def nucleusIsoSublocale : (Nucleus X)ᵒᵈ ≃o Sublocale X where toFun n := n.ofDual.toSublocale invFun s := .toDual s.toNucleus left_inv := by simp [Function.LeftInverse, Nucleus.ext_iff] right_inv S := by ext x; simpa using ⟨by simp +contextual [eq_comm], fun hx ↦ ⟨x, by simp [hx]⟩⟩ map_rel_iff' := by simp lemma nucleusIsoSublocale.eq_toSublocale : Nucleus.toSublocale = @nucleusIsoSublocale X _ := rfl lemma nucleusIsoSublocale.symm_eq_toNucleus : Sublocale.toNucleus = (@nucleusIsoSublocale X _).symm := rfl instance Sublocale.instCompleteLattice : CompleteLattice (Sublocale X) := nucleusIsoSublocale.toGaloisInsertion.liftCompleteLattice instance Sublocale.instCoframeMinimalAxioms : Order.Coframe.MinimalAxioms (Sublocale X) where iInf_sup_le_sup_sInf a s := by simp [← toNucleus_le_toNucleus, nucleusIsoSublocale.symm_eq_toNucleus, nucleusIsoSublocale.symm.map_sup, nucleusIsoSublocale.symm.map_sInf, sup_iInf_eq, nucleusIsoSublocale.symm.map_iInf] instance Sublocale.instCoframe : Order.Coframe (Sublocale X) := .ofMinimalAxioms instCoframeMinimalAxioms
.lake/packages/mathlib/Mathlib/Order/Basic.lean
import Mathlib.Data.Subtype import Mathlib.Order.Defs.LinearOrder import Mathlib.Order.Notation import Mathlib.Tactic.GRewrite import Mathlib.Tactic.Spread import Mathlib.Tactic.Convert import Mathlib.Tactic.Inhabit import Mathlib.Tactic.SimpRw /-! # Basic definitions about `≤` and `<` This file proves basic results about orders, provides extensive dot notation, defines useful order classes and allows to transfer order instances. ## Type synonyms * `OrderDual α` : A type synonym reversing the meaning of all inequalities, with notation `αᵒᵈ`. * `AsLinearOrder α`: A type synonym to promote `PartialOrder α` to `LinearOrder α` using `IsTotal α (≤)`. ### Transferring orders - `Order.Preimage`, `Preorder.lift`: Transfers a (pre)order on `β` to an order on `α` using a function `f : α → β`. - `PartialOrder.lift`, `LinearOrder.lift`: Transfers a partial (resp., linear) order on `β` to a partial (resp., linear) order on `α` using an injective function `f`. ### Extra class * `DenselyOrdered`: An order with no gap, i.e. for any two elements `a < b` there exists `c` such that `a < c < b`. ## Notes `≤` and `<` are highly favored over `≥` and `>` in mathlib. The reason is that we can formulate all lemmas using `≤`/`<`, and `rw` has trouble unifying `≤` and `≥`. Hence choosing one direction spares us useless duplication. This is enforced by a linter. See Note [nolint_ge] for more infos. Dot notation is particularly useful on `≤` (`LE.le`) and `<` (`LT.lt`). To that end, we provide many aliases to dot notation-less lemmas. For example, `le_trans` is aliased with `LE.le.trans` and can be used to construct `hab.trans hbc : a ≤ c` when `hab : a ≤ b`, `hbc : b ≤ c`, `lt_of_le_of_lt` is aliased as `LE.le.trans_lt` and can be used to construct `hab.trans hbc : a < c` when `hab : a ≤ b`, `hbc : b < c`. ## TODO - expand module docs - automatic construction of dual definitions / theorems ## Tags preorder, order, partial order, poset, linear order, chain -/ open Function variable {ι α β : Type*} {π : ι → Type*} /-! ### Bare relations -/ attribute [ext] LE section LE variable [LE α] {a b c : α} protected lemma LE.le.ge (h : a ≤ b) : b ≥ a := h protected lemma GE.ge.le (h : a ≥ b) : b ≤ a := h theorem le_of_le_of_eq' : b ≤ c → a = b → a ≤ c := flip le_of_eq_of_le theorem le_of_eq_of_le' : b = c → a ≤ b → a ≤ c := flip le_of_le_of_eq alias LE.le.trans_eq := le_of_le_of_eq alias LE.le.trans_eq' := le_of_le_of_eq' alias Eq.trans_le := le_of_eq_of_le alias Eq.trans_ge := le_of_eq_of_le' end LE section LT variable [LT α] {a b c : α} protected lemma LT.lt.gt (h : a < b) : b > a := h protected lemma GT.gt.lt (h : a > b) : b < a := h theorem lt_of_lt_of_eq' : b < c → a = b → a < c := flip lt_of_eq_of_lt theorem lt_of_eq_of_lt' : b = c → a < b → a < c := flip lt_of_lt_of_eq alias LT.lt.trans_eq := lt_of_lt_of_eq alias LT.lt.trans_eq' := lt_of_lt_of_eq' alias Eq.trans_lt := lt_of_eq_of_lt alias Eq.trans_gt := lt_of_eq_of_lt' end LT /-- Given a relation `R` on `β` and a function `f : α → β`, the preimage relation on `α` is defined by `x ≤ y ↔ f x ≤ f y`. It is the unique relation on `α` making `f` a `RelEmbedding` (assuming `f` is injective). -/ @[simp] def Order.Preimage (f : α → β) (s : β → β → Prop) (x y : α) : Prop := s (f x) (f y) @[inherit_doc] infixl:80 " ⁻¹'o " => Order.Preimage /-- The preimage of a decidable order is decidable. -/ instance Order.Preimage.decidable (f : α → β) (s : β → β → Prop) [H : DecidableRel s] : DecidableRel (f ⁻¹'o s) := fun _ _ ↦ H _ _ /-! ### Preorders -/ section Preorder variable [Preorder α] {a b c d : α} theorem not_lt_iff_not_le_or_ge : ¬a < b ↔ ¬a ≤ b ∨ b ≤ a := by rw [lt_iff_le_not_ge, Classical.not_and_iff_not_or_not, Classical.not_not] -- Unnecessary brackets are here for readability lemma not_lt_iff_le_imp_ge : ¬ a < b ↔ (a ≤ b → b ≤ a) := by simp [not_lt_iff_not_le_or_ge, or_iff_not_imp_left] @[deprecated (since := "2025-05-11")] alias not_lt_iff_le_imp_le := not_lt_iff_le_imp_ge @[simp] lemma lt_self_iff_false (x : α) : x < x ↔ False := ⟨lt_irrefl x, False.elim⟩ alias le_trans' := ge_trans alias lt_trans' := gt_trans alias LE.le.trans := le_trans alias LE.le.trans' := le_trans' alias LT.lt.trans := lt_trans alias LT.lt.trans' := lt_trans' alias LE.le.trans_lt := lt_of_le_of_lt alias LE.le.trans_lt' := lt_of_le_of_lt' alias LT.lt.trans_le := lt_of_lt_of_le alias LT.lt.trans_le' := lt_of_lt_of_le' alias LE.le.lt_of_not_ge := lt_of_le_not_ge alias LT.lt.le := le_of_lt alias LT.lt.ne := ne_of_lt alias Eq.le := le_of_eq alias Eq.ge := ge_of_eq alias LT.lt.asymm := lt_asymm alias LT.lt.not_gt := lt_asymm @[deprecated (since := "2025-05-11")] alias LE.le.lt_of_not_le := LE.le.lt_of_not_ge @[deprecated (since := "2025-06-07")] alias LT.lt.not_lt := LT.lt.not_gt theorem ne_of_not_le (h : ¬a ≤ b) : a ≠ b := fun hab ↦ h (le_of_eq hab) protected lemma Eq.not_lt (hab : a = b) : ¬a < b := fun h' ↦ h'.ne hab protected lemma Eq.not_gt (hab : a = b) : ¬b < a := hab.symm.not_lt @[simp] lemma le_of_subsingleton [Subsingleton α] : a ≤ b := (Subsingleton.elim a b).le -- Making this a @[simp] lemma causes confluence problems downstream. @[nontriviality] lemma not_lt_of_subsingleton [Subsingleton α] : ¬a < b := (Subsingleton.elim a b).not_lt namespace LT.lt protected theorem false : a < a → False := lt_irrefl a theorem ne' (h : a < b) : b ≠ a := h.ne.symm end LT.lt theorem le_of_forall_le (H : ∀ c, c ≤ a → c ≤ b) : a ≤ b := H _ le_rfl theorem le_of_forall_ge (H : ∀ c, a ≤ c → b ≤ c) : b ≤ a := H _ le_rfl theorem forall_le_iff_le : (∀ ⦃c⦄, c ≤ a → c ≤ b) ↔ a ≤ b := ⟨le_of_forall_le, fun h _ hca ↦ le_trans hca h⟩ theorem forall_ge_iff_le : (∀ ⦃c⦄, a ≤ c → b ≤ c) ↔ b ≤ a := ⟨le_of_forall_ge, fun h _ hca ↦ le_trans h hca⟩ @[deprecated (since := "2025-07-27")] alias forall_le_iff_ge := forall_ge_iff_le /-- monotonicity of `≤` with respect to `→` -/ @[gcongr] theorem le_imp_le_of_le_of_le (h₁ : c ≤ a) (h₂ : b ≤ d) : a ≤ b → c ≤ d := fun hab ↦ (h₁.trans hab).trans h₂ @[deprecated (since := "2025-07-31")] alias le_implies_le_of_le_of_le := le_imp_le_of_le_of_le /-- monotonicity of `<` with respect to `→` -/ @[gcongr] theorem lt_imp_lt_of_le_of_le (h₁ : c ≤ a) (h₂ : b ≤ d) : a < b → c < d := fun hab ↦ (h₁.trans_lt hab).trans_le h₂ namespace Mathlib.Tactic.GCongr /-- See if the term is `a < b` and the goal is `a ≤ b`. -/ @[gcongr_forward] def exactLeOfLt : ForwardExt where eval h goal := do goal.assignIfDefEq (← Lean.Meta.mkAppM ``le_of_lt #[h]) end Mathlib.Tactic.GCongr end Preorder /-! ### Partial order -/ section PartialOrder variable [PartialOrder α] {a b : α} theorem Ne.lt_of_le : a ≠ b → a ≤ b → a < b := flip lt_of_le_of_ne theorem Ne.lt_of_le' : b ≠ a → a ≤ b → a < b := flip lt_of_le_of_ne' alias LE.le.antisymm := le_antisymm alias LE.le.antisymm' := ge_antisymm alias LE.le.lt_of_ne := lt_of_le_of_ne alias LE.le.lt_of_ne' := lt_of_le_of_ne' -- Unnecessary brackets are here for readability lemma le_imp_eq_iff_le_imp_ge' : (a ≤ b → b = a) ↔ (a ≤ b → b ≤ a) where mp h hab := (h hab).le mpr h hab := (h hab).antisymm hab @[deprecated (since := "2025-05-11")] alias le_imp_eq_iff_le_imp_le := le_imp_eq_iff_le_imp_ge' -- Unnecessary brackets are here for readability lemma le_imp_eq_iff_le_imp_ge : (a ≤ b → a = b) ↔ (a ≤ b → b ≤ a) where mp h hab := (h hab).ge mpr h hab := hab.antisymm (h hab) @[deprecated (since := "2025-05-11")] alias ge_imp_eq_iff_le_imp_le := le_imp_eq_iff_le_imp_ge namespace LE.le theorem lt_iff_ne (h : a ≤ b) : a < b ↔ a ≠ b := ⟨fun h ↦ h.ne, h.lt_of_ne⟩ theorem lt_iff_ne' (h : a ≤ b) : a < b ↔ b ≠ a := ⟨fun h ↦ h.ne.symm, h.lt_of_ne'⟩ theorem not_lt_iff_eq (h : a ≤ b) : ¬a < b ↔ a = b := h.lt_iff_ne.not_left theorem not_lt_iff_eq' (h : a ≤ b) : ¬a < b ↔ b = a := h.lt_iff_ne'.not_left theorem ge_iff_eq (h : a ≤ b) : b ≤ a ↔ a = b := ⟨h.antisymm, Eq.ge⟩ theorem ge_iff_eq' (h : a ≤ b) : b ≤ a ↔ b = a := ⟨fun h' ↦ h'.antisymm h, Eq.le⟩ @[deprecated (since := "2025-06-08")] alias gt_iff_ne := lt_iff_ne' @[deprecated (since := "2025-06-08")] alias le_iff_eq := ge_iff_eq' @[deprecated (since := "2025-06-08")] alias not_gt_iff_eq := not_lt_iff_eq' end LE.le -- See Note [decidable namespace] protected theorem Decidable.le_iff_eq_or_lt [DecidableLE α] : a ≤ b ↔ a = b ∨ a < b := Decidable.le_iff_lt_or_eq.trans or_comm theorem le_iff_eq_or_lt : a ≤ b ↔ a = b ∨ a < b := le_iff_lt_or_eq.trans or_comm theorem lt_iff_le_and_ne : a < b ↔ a ≤ b ∧ a ≠ b := ⟨fun h ↦ ⟨le_of_lt h, ne_of_lt h⟩, fun ⟨h1, h2⟩ ↦ h1.lt_of_ne h2⟩ @[deprecated LE.le.not_lt_iff_eq (since := "2025-06-08")] lemma eq_iff_not_lt_of_le (hab : a ≤ b) : a = b ↔ ¬ a < b := hab.not_lt_iff_eq.symm @[deprecated (since := "2025-06-08")] alias LE.le.eq_iff_not_lt := eq_iff_not_lt_of_le -- See Note [decidable namespace] protected theorem Decidable.eq_iff_le_not_lt [DecidableLE α] : a = b ↔ a ≤ b ∧ ¬a < b := ⟨fun h ↦ ⟨h.le, h ▸ lt_irrefl _⟩, fun ⟨h₁, h₂⟩ ↦ h₁.antisymm <| Decidable.byContradiction fun h₃ ↦ h₂ (h₁.lt_of_not_ge h₃)⟩ theorem eq_iff_le_not_lt : a = b ↔ a ≤ b ∧ ¬a < b := open scoped Classical in Decidable.eq_iff_le_not_lt -- See Note [decidable namespace] protected theorem Decidable.eq_or_lt_of_le [DecidableLE α] (h : a ≤ b) : a = b ∨ a < b := (Decidable.lt_or_eq_of_le h).symm theorem eq_or_lt_of_le (h : a ≤ b) : a = b ∨ a < b := (lt_or_eq_of_le h).symm theorem eq_or_lt_of_le' (h : a ≤ b) : b = a ∨ a < b := (eq_or_lt_of_le h).imp Eq.symm id alias LE.le.lt_or_eq_dec := Decidable.lt_or_eq_of_le alias LE.le.eq_or_lt_dec := Decidable.eq_or_lt_of_le alias LE.le.lt_or_eq := lt_or_eq_of_le alias LE.le.eq_or_lt := eq_or_lt_of_le alias LE.le.eq_or_lt' := eq_or_lt_of_le' alias LE.le.lt_or_eq' := lt_or_eq_of_le' @[deprecated (since := "2025-06-08")] alias eq_or_gt_of_le := eq_or_lt_of_le' @[deprecated (since := "2025-06-08")] alias gt_or_eq_of_le := lt_or_eq_of_le' @[deprecated (since := "2025-06-08")] alias LE.le.eq_or_gt := LE.le.eq_or_lt' @[deprecated (since := "2025-06-08")] alias LE.le.gt_or_eq := LE.le.lt_or_eq' theorem eq_of_le_of_not_lt (h₁ : a ≤ b) (h₂ : ¬a < b) : a = b := h₁.eq_or_lt.resolve_right h₂ theorem eq_of_le_of_not_lt' (h₁ : a ≤ b) (h₂ : ¬a < b) : b = a := (eq_of_le_of_not_lt h₁ h₂).symm alias LE.le.eq_of_not_lt := eq_of_le_of_not_lt alias LE.le.eq_of_not_lt' := eq_of_le_of_not_lt' @[deprecated (since := "2025-06-08")] alias eq_of_ge_of_not_gt := eq_of_le_of_not_lt' @[deprecated (since := "2025-06-08")] alias LE.le.eq_of_not_gt := LE.le.eq_of_not_lt' theorem Ne.le_iff_lt (h : a ≠ b) : a ≤ b ↔ a < b := ⟨fun h' ↦ lt_of_le_of_ne h' h, fun h ↦ h.le⟩ theorem Ne.not_le_or_not_ge (h : a ≠ b) : ¬a ≤ b ∨ ¬b ≤ a := not_and_or.1 <| le_antisymm_iff.not.1 h @[deprecated (since := "2025-06-07")] alias Ne.not_le_or_not_le := Ne.not_le_or_not_ge -- See Note [decidable namespace] protected theorem Decidable.ne_iff_lt_iff_le [DecidableEq α] : (a ≠ b ↔ a < b) ↔ a ≤ b := ⟨fun h ↦ Decidable.byCases le_of_eq (le_of_lt ∘ h.mp), fun h ↦ ⟨lt_of_le_of_ne h, ne_of_lt⟩⟩ @[simp] theorem ne_iff_lt_iff_le : (a ≠ b ↔ a < b) ↔ a ≤ b := haveI := Classical.dec Decidable.ne_iff_lt_iff_le lemma eq_of_forall_le_iff (H : ∀ c, c ≤ a ↔ c ≤ b) : a = b := ((H _).1 le_rfl).antisymm ((H _).2 le_rfl) lemma eq_of_forall_ge_iff (H : ∀ c, a ≤ c ↔ b ≤ c) : a = b := ((H _).2 le_rfl).antisymm ((H _).1 le_rfl) /-- To prove commutativity of a binary operation `○`, we only to check `a ○ b ≤ b ○ a` for all `a`, `b`. -/ lemma commutative_of_le {f : β → β → α} (comm : ∀ a b, f a b ≤ f b a) : ∀ a b, f a b = f b a := fun _ _ ↦ (comm _ _).antisymm <| comm _ _ /-- To prove associativity of a commutative binary operation `○`, we only to check `(a ○ b) ○ c ≤ a ○ (b ○ c)` for all `a`, `b`, `c`. -/ lemma associative_of_commutative_of_le {f : α → α → α} (comm : Std.Commutative f) (assoc : ∀ a b c, f (f a b) c ≤ f a (f b c)) : Std.Associative f where assoc a b c := le_antisymm (assoc _ _ _) <| by rw [comm.comm, comm.comm b, comm.comm _ c, comm.comm a] exact assoc .. end PartialOrder section LinearOrder variable [LinearOrder α] {a b : α} namespace LE.le lemma gt_or_le (h : a ≤ b) (c : α) : a < c ∨ c ≤ b := (lt_or_ge a c).imp id h.trans' lemma ge_or_lt (h : a ≤ b) (c : α) : a ≤ c ∨ c < b := (le_or_gt a c).imp id h.trans_lt' lemma ge_or_le (h : a ≤ b) (c : α) : a ≤ c ∨ c ≤ b := (h.gt_or_le c).imp le_of_lt id @[deprecated (since := "2025-05-11")] alias lt_or_le := gt_or_le @[deprecated (since := "2025-05-11")] alias le_or_lt := ge_or_lt @[deprecated (since := "2025-05-11")] alias le_or_le := ge_or_le end LE.le namespace LT.lt lemma gt_or_lt (h : a < b) (c : α) : a < c ∨ c < b := (le_or_gt b c).imp h.trans_le id @[deprecated (since := "2025-06-07")] alias lt_or_lt := gt_or_lt end LT.lt -- Variant of `min_def` with the branches reversed. theorem min_def' (a b : α) : min a b = if b ≤ a then b else a := by grind -- Variant of `min_def` with the branches reversed. -- This is sometimes useful as it used to be the default. theorem max_def' (a b : α) : max a b = if b ≤ a then a else b := by grind @[deprecated (since := "2025-05-11")] alias lt_of_not_le := lt_of_not_ge @[deprecated (since := "2025-05-11")] alias lt_iff_not_le := lt_iff_not_ge theorem Ne.lt_or_gt (h : a ≠ b) : a < b ∨ b < a := lt_or_gt_of_ne h @[deprecated (since := "2025-06-07")] alias Ne.lt_or_lt := Ne.lt_or_gt /-- A version of `ne_iff_lt_or_gt` with LHS and RHS reversed. -/ @[simp] theorem lt_or_lt_iff_ne : a < b ∨ b < a ↔ a ≠ b := ne_iff_lt_or_gt.symm theorem not_lt_iff_eq_or_lt : ¬a < b ↔ a = b ∨ b < a := not_lt.trans <| Decidable.le_iff_eq_or_lt.trans <| or_congr eq_comm Iff.rfl theorem exists_ge_of_linear (a b : α) : ∃ c, a ≤ c ∧ b ≤ c := match le_total a b with | Or.inl h => ⟨_, h, le_rfl⟩ | Or.inr h => ⟨_, le_rfl, h⟩ lemma exists_forall_ge_and {p q : α → Prop} : (∃ i, ∀ j ≥ i, p j) → (∃ i, ∀ j ≥ i, q j) → ∃ i, ∀ j ≥ i, p j ∧ q j | ⟨a, ha⟩, ⟨b, hb⟩ => let ⟨c, hac, hbc⟩ := exists_ge_of_linear a b ⟨c, fun _d hcd ↦ ⟨ha _ <| hac.trans hcd, hb _ <| hbc.trans hcd⟩⟩ theorem le_of_forall_lt (H : ∀ c, c < a → c < b) : a ≤ b := le_of_not_gt fun h ↦ lt_irrefl _ (H _ h) theorem forall_lt_iff_le : (∀ ⦃c⦄, c < a → c < b) ↔ a ≤ b := ⟨le_of_forall_lt, fun h _ hca ↦ lt_of_lt_of_le hca h⟩ theorem le_of_forall_gt (H : ∀ c, a < c → b < c) : b ≤ a := le_of_not_gt fun h ↦ lt_irrefl _ (H _ h) theorem forall_gt_iff_le : (∀ ⦃c⦄, a < c → b < c) ↔ b ≤ a := ⟨le_of_forall_gt, fun h _ hac ↦ lt_of_le_of_lt h hac⟩ @[deprecated (since := "2025-06-07")] alias le_of_forall_lt' := le_of_forall_gt @[deprecated (since := "2025-06-07")] alias forall_lt_iff_le' := forall_gt_iff_le theorem eq_of_forall_lt_iff (h : ∀ c, c < a ↔ c < b) : a = b := (le_of_forall_lt fun _ ↦ (h _).1).antisymm <| le_of_forall_lt fun _ ↦ (h _).2 theorem eq_of_forall_gt_iff (h : ∀ c, a < c ↔ b < c) : a = b := (le_of_forall_gt fun _ ↦ (h _).2).antisymm <| le_of_forall_gt fun _ ↦ (h _).1 section ltByCases variable {P : Sort*} {x y : α} lemma eq_iff_eq_of_lt_iff_lt_of_gt_iff_gt {x' y' : α} (ltc : (x < y) ↔ (x' < y')) (gtc : (y < x) ↔ (y' < x')) : x = y ↔ x' = y' := by grind variable {p q r s : P} end ltByCases /-! #### `min`/`max` recursors -/ section MinMaxRec variable {p : α → Prop} lemma min_rec (ha : a ≤ b → p a) (hb : b ≤ a → p b) : p (min a b) := by obtain hab | hba := le_total a b <;> simp [min_eq_left, min_eq_right, *] lemma max_rec (ha : b ≤ a → p a) (hb : a ≤ b → p b) : p (max a b) := by obtain hab | hba := le_total a b <;> simp [max_eq_left, max_eq_right, *] lemma min_rec' (p : α → Prop) (ha : p a) (hb : p b) : p (min a b) := min_rec (fun _ ↦ ha) fun _ ↦ hb lemma max_rec' (p : α → Prop) (ha : p a) (hb : p b) : p (max a b) := max_rec (fun _ ↦ ha) fun _ ↦ hb lemma min_def_lt (a b : α) : min a b = if a < b then a else b := by rw [min_comm, min_def, ← ite_not]; simp only [not_le] lemma max_def_lt (a b : α) : max a b = if a < b then b else a := by rw [max_comm, max_def, ← ite_not]; simp only [not_le] end MinMaxRec end LinearOrder /-! ### Implications -/ lemma lt_imp_lt_of_le_imp_le {β} [LinearOrder α] [Preorder β] {a b : α} {c d : β} (H : a ≤ b → c ≤ d) (h : d < c) : b < a := lt_of_not_ge fun h' ↦ (H h').not_gt h lemma le_imp_le_iff_lt_imp_lt {β} [LinearOrder α] [LinearOrder β] {a b : α} {c d : β} : a ≤ b → c ≤ d ↔ d < c → b < a := ⟨lt_imp_lt_of_le_imp_le, le_imp_le_of_lt_imp_lt⟩ lemma lt_iff_lt_of_le_iff_le' {β} [Preorder α] [Preorder β] {a b : α} {c d : β} (H : a ≤ b ↔ c ≤ d) (H' : b ≤ a ↔ d ≤ c) : b < a ↔ d < c := lt_iff_le_not_ge.trans <| (and_congr H' (not_congr H)).trans lt_iff_le_not_ge.symm lemma lt_iff_lt_of_le_iff_le {β} [LinearOrder α] [LinearOrder β] {a b : α} {c d : β} (H : a ≤ b ↔ c ≤ d) : b < a ↔ d < c := not_le.symm.trans <| (not_congr H).trans <| not_le lemma le_iff_le_iff_lt_iff_lt {β} [LinearOrder α] [LinearOrder β] {a b : α} {c d : β} : (a ≤ b ↔ c ≤ d) ↔ (b < a ↔ d < c) := ⟨lt_iff_lt_of_le_iff_le, fun H ↦ not_lt.symm.trans <| (not_congr H).trans <| not_lt⟩ /-- A symmetric relation implies two values are equal, when it implies they're less-equal. -/ lemma rel_imp_eq_of_rel_imp_le [PartialOrder β] (r : α → α → Prop) [IsSymm α r] {f : α → β} (h : ∀ a b, r a b → f a ≤ f b) {a b : α} : r a b → f a = f b := fun hab ↦ le_antisymm (h a b hab) (h b a <| symm hab) /-! ### Extensionality lemmas -/ @[ext] lemma Preorder.toLE_injective : Function.Injective (@Preorder.toLE α) := fun | { lt := A_lt, lt_iff_le_not_ge := A_iff, .. }, { lt := B_lt, lt_iff_le_not_ge := B_iff, .. } => by rintro ⟨⟩ have : A_lt = B_lt := by funext a b rw [A_iff, B_iff] cases this congr @[ext] lemma PartialOrder.toPreorder_injective : Function.Injective (@PartialOrder.toPreorder α) := by rintro ⟨⟩ ⟨⟩ ⟨⟩; congr @[ext] lemma LinearOrder.toPartialOrder_injective : Function.Injective (@LinearOrder.toPartialOrder α) := fun | { le := A_le, lt := A_lt, toDecidableLE := A_decidableLE, toDecidableEq := A_decidableEq, toDecidableLT := A_decidableLT min := A_min, max := A_max, min_def := A_min_def, max_def := A_max_def, compare := A_compare, compare_eq_compareOfLessAndEq := A_compare_canonical, .. }, { le := B_le, lt := B_lt, toDecidableLE := B_decidableLE, toDecidableEq := B_decidableEq, toDecidableLT := B_decidableLT min := B_min, max := B_max, min_def := B_min_def, max_def := B_max_def, compare := B_compare, compare_eq_compareOfLessAndEq := B_compare_canonical, .. } => by rintro ⟨⟩ obtain rfl : A_decidableLE = B_decidableLE := Subsingleton.elim _ _ obtain rfl : A_decidableEq = B_decidableEq := Subsingleton.elim _ _ obtain rfl : A_decidableLT = B_decidableLT := Subsingleton.elim _ _ have : A_min = B_min := by funext a b exact (A_min_def _ _).trans (B_min_def _ _).symm cases this have : A_max = B_max := by funext a b exact (A_max_def _ _).trans (B_max_def _ _).symm cases this have : A_compare = B_compare := by funext a b exact (A_compare_canonical _ _).trans (B_compare_canonical _ _).symm congr lemma Preorder.ext {A B : Preorder α} (H : ∀ x y : α, (haveI := A; x ≤ y) ↔ x ≤ y) : A = B := by ext x y; exact H x y lemma PartialOrder.ext {A B : PartialOrder α} (H : ∀ x y : α, (haveI := A; x ≤ y) ↔ x ≤ y) : A = B := by ext x y; exact H x y lemma PartialOrder.ext_lt {A B : PartialOrder α} (H : ∀ x y : α, (haveI := A; x < y) ↔ x < y) : A = B := by ext x y; rw [le_iff_lt_or_eq, @le_iff_lt_or_eq _ A, H] lemma LinearOrder.ext {A B : LinearOrder α} (H : ∀ x y : α, (haveI := A; x ≤ y) ↔ x ≤ y) : A = B := by ext x y; exact H x y lemma LinearOrder.ext_lt {A B : LinearOrder α} (H : ∀ x y : α, (haveI := A; x < y) ↔ x < y) : A = B := LinearOrder.toPartialOrder_injective (PartialOrder.ext_lt H) /-! ### Order dual -/ /-- Type synonym to equip a type with the dual order: `≤` means `≥` and `<` means `>`. `αᵒᵈ` is notation for `OrderDual α`. -/ def OrderDual (α : Type*) : Type _ := α @[inherit_doc] notation:max α "ᵒᵈ" => OrderDual α namespace OrderDual instance (α : Type*) [h : Nonempty α] : Nonempty αᵒᵈ := h instance (α : Type*) [h : Subsingleton α] : Subsingleton αᵒᵈ := h instance (α : Type*) [LE α] : LE αᵒᵈ := ⟨fun x y : α ↦ y ≤ x⟩ instance (α : Type*) [LT α] : LT αᵒᵈ := ⟨fun x y : α ↦ y < x⟩ instance instOrd (α : Type*) [Ord α] : Ord αᵒᵈ where compare := fun (a b : α) ↦ compare b a instance instSup (α : Type*) [Min α] : Max αᵒᵈ := ⟨((· ⊓ ·) : α → α → α)⟩ instance instInf (α : Type*) [Max α] : Min αᵒᵈ := ⟨((· ⊔ ·) : α → α → α)⟩ instance instIsTransLE [LE α] [T : IsTrans α LE.le] : IsTrans αᵒᵈ LE.le where trans := fun _ _ _ hab hbc ↦ T.trans _ _ _ hbc hab instance instIsTransLT [LT α] [T : IsTrans α LT.lt] : IsTrans αᵒᵈ LT.lt where trans := fun _ _ _ hab hbc ↦ T.trans _ _ _ hbc hab instance instPreorder (α : Type*) [Preorder α] : Preorder αᵒᵈ where le_refl := fun _ ↦ le_refl _ le_trans := fun _ _ _ hab hbc ↦ hbc.trans hab lt_iff_le_not_ge := fun _ _ ↦ lt_iff_le_not_ge instance instPartialOrder (α : Type*) [PartialOrder α] : PartialOrder αᵒᵈ where __ := inferInstanceAs (Preorder αᵒᵈ) le_antisymm := fun a b hab hba ↦ @le_antisymm α _ a b hba hab instance instLinearOrder (α : Type*) [LinearOrder α] : LinearOrder αᵒᵈ where __ := inferInstanceAs (PartialOrder αᵒᵈ) __ := inferInstanceAs (Ord αᵒᵈ) le_total := fun a b : α ↦ le_total b a max := fun a b ↦ (min a b : α) min := fun a b ↦ (max a b : α) min_def := fun a b ↦ show (max .. : α) = _ by rw [max_comm, max_def]; rfl max_def := fun a b ↦ show (min .. : α) = _ by rw [min_comm, min_def]; rfl toDecidableLE := (inferInstance : DecidableRel (fun a b : α ↦ b ≤ a)) toDecidableLT := (inferInstance : DecidableRel (fun a b : α ↦ b < a)) toDecidableEq := (inferInstance : DecidableEq α) compare_eq_compareOfLessAndEq a b := by simp only [compare, LinearOrder.compare_eq_compareOfLessAndEq, compareOfLessAndEq, eq_comm] rfl /-- The opposite linear order to a given linear order -/ def _root_.LinearOrder.swap (α : Type*) (_ : LinearOrder α) : LinearOrder α := inferInstanceAs <| LinearOrder (OrderDual α) instance : ∀ [Inhabited α], Inhabited αᵒᵈ := fun [x : Inhabited α] => x theorem Ord.dual_dual (α : Type*) [H : Ord α] : OrderDual.instOrd αᵒᵈ = H := rfl theorem Preorder.dual_dual (α : Type*) [H : Preorder α] : OrderDual.instPreorder αᵒᵈ = H := rfl theorem instPartialOrder.dual_dual (α : Type*) [H : PartialOrder α] : OrderDual.instPartialOrder αᵒᵈ = H := rfl theorem instLinearOrder.dual_dual (α : Type*) [H : LinearOrder α] : OrderDual.instLinearOrder αᵒᵈ = H := rfl end OrderDual /-! ### `HasCompl` -/ instance Prop.hasCompl : HasCompl Prop := ⟨Not⟩ instance Pi.hasCompl [∀ i, HasCompl (π i)] : HasCompl (∀ i, π i) := ⟨fun x i ↦ (x i)ᶜ⟩ @[push ←] theorem Pi.compl_def [∀ i, HasCompl (π i)] (x : ∀ i, π i) : xᶜ = fun i ↦ (x i)ᶜ := rfl @[simp] theorem Pi.compl_apply [∀ i, HasCompl (π i)] (x : ∀ i, π i) (i : ι) : xᶜ i = (x i)ᶜ := rfl instance IsIrrefl.compl (r) [IsIrrefl α r] : IsRefl α rᶜ := ⟨@irrefl α r _⟩ instance IsRefl.compl (r) [IsRefl α r] : IsIrrefl α rᶜ := ⟨fun a ↦ not_not_intro (refl a)⟩ theorem compl_lt [LinearOrder α] : (· < · : α → α → _)ᶜ = (· ≥ ·) := by simp [compl] theorem compl_le [LinearOrder α] : (· ≤ · : α → α → _)ᶜ = (· > ·) := by simp [compl] theorem compl_gt [LinearOrder α] : (· > · : α → α → _)ᶜ = (· ≤ ·) := by simp [compl] theorem compl_ge [LinearOrder α] : (· ≥ · : α → α → _)ᶜ = (· < ·) := by simp [compl] instance Ne.instIsEquiv_compl : IsEquiv α (· ≠ ·)ᶜ := by convert eq_isEquiv α simp [compl] /-! ### Order instances on the function space -/ instance Pi.hasLe [∀ i, LE (π i)] : LE (∀ i, π i) where le x y := ∀ i, x i ≤ y i theorem Pi.le_def [∀ i, LE (π i)] {x y : ∀ i, π i} : x ≤ y ↔ ∀ i, x i ≤ y i := Iff.rfl instance Pi.preorder [∀ i, Preorder (π i)] : Preorder (∀ i, π i) where __ := inferInstanceAs (LE (∀ i, π i)) le_refl := fun a i ↦ le_refl (a i) le_trans := fun _ _ _ h₁ h₂ i ↦ le_trans (h₁ i) (h₂ i) theorem Pi.lt_def [∀ i, Preorder (π i)] {x y : ∀ i, π i} : x < y ↔ x ≤ y ∧ ∃ i, x i < y i := by simp +contextual [lt_iff_le_not_ge, Pi.le_def] instance Pi.partialOrder [∀ i, PartialOrder (π i)] : PartialOrder (∀ i, π i) where __ := Pi.preorder le_antisymm := fun _ _ h1 h2 ↦ funext fun b ↦ (h1 b).antisymm (h2 b) namespace Sum variable {α₁ α₂ : Type*} [LE β] @[simp] lemma elim_le_elim_iff {u₁ v₁ : α₁ → β} {u₂ v₂ : α₂ → β} : Sum.elim u₁ u₂ ≤ Sum.elim v₁ v₂ ↔ u₁ ≤ v₁ ∧ u₂ ≤ v₂ := Sum.forall lemma const_le_elim_iff {b : β} {v₁ : α₁ → β} {v₂ : α₂ → β} : Function.const _ b ≤ Sum.elim v₁ v₂ ↔ Function.const _ b ≤ v₁ ∧ Function.const _ b ≤ v₂ := elim_const_const b ▸ elim_le_elim_iff .. lemma elim_le_const_iff {b : β} {u₁ : α₁ → β} {u₂ : α₂ → β} : Sum.elim u₁ u₂ ≤ Function.const _ b ↔ u₁ ≤ Function.const _ b ∧ u₂ ≤ Function.const _ b := elim_const_const b ▸ elim_le_elim_iff .. end Sum section Pi /-- A function `a` is strongly less than a function `b` if `a i < b i` for all `i`. -/ def StrongLT [∀ i, LT (π i)] (a b : ∀ i, π i) : Prop := ∀ i, a i < b i @[inherit_doc] local infixl:50 " ≺ " => StrongLT variable [∀ i, Preorder (π i)] {a b c : ∀ i, π i} theorem le_of_strongLT (h : a ≺ b) : a ≤ b := fun _ ↦ (h _).le theorem lt_of_strongLT [Nonempty ι] (h : a ≺ b) : a < b := by inhabit ι exact Pi.lt_def.2 ⟨le_of_strongLT h, default, h _⟩ theorem strongLT_of_strongLT_of_le (hab : a ≺ b) (hbc : b ≤ c) : a ≺ c := fun _ ↦ (hab _).trans_le <| hbc _ theorem strongLT_of_le_of_strongLT (hab : a ≤ b) (hbc : b ≺ c) : a ≺ c := fun _ ↦ (hab _).trans_lt <| hbc _ alias StrongLT.le := le_of_strongLT alias StrongLT.lt := lt_of_strongLT alias StrongLT.trans_le := strongLT_of_strongLT_of_le alias LE.le.trans_strongLT := strongLT_of_le_of_strongLT end Pi section Function variable [DecidableEq ι] [∀ i, Preorder (π i)] {x y : ∀ i, π i} {i : ι} {a b : π i} theorem le_update_iff : x ≤ Function.update y i a ↔ x i ≤ a ∧ ∀ (j) (_ : j ≠ i), x j ≤ y j := Function.forall_update_iff _ fun j z ↦ x j ≤ z theorem update_le_iff : Function.update x i a ≤ y ↔ a ≤ y i ∧ ∀ (j) (_ : j ≠ i), x j ≤ y j := Function.forall_update_iff _ fun j z ↦ z ≤ y j theorem update_le_update_iff : Function.update x i a ≤ Function.update y i b ↔ a ≤ b ∧ ∀ (j) (_ : j ≠ i), x j ≤ y j := by simp +contextual [update_le_iff] @[simp] theorem update_le_update_iff' : update x i a ≤ update x i b ↔ a ≤ b := by simp [update_le_update_iff] @[simp] theorem update_lt_update_iff : update x i a < update x i b ↔ a < b := lt_iff_lt_of_le_iff_le' update_le_update_iff' update_le_update_iff' @[simp] theorem le_update_self_iff : x ≤ update x i a ↔ x i ≤ a := by simp [le_update_iff] @[simp] theorem update_le_self_iff : update x i a ≤ x ↔ a ≤ x i := by simp [update_le_iff] @[simp] theorem lt_update_self_iff : x < update x i a ↔ x i < a := by simp [lt_iff_le_not_ge] @[simp] theorem update_lt_self_iff : update x i a < x ↔ a < x i := by simp [lt_iff_le_not_ge] end Function instance Pi.sdiff [∀ i, SDiff (π i)] : SDiff (∀ i, π i) := ⟨fun x y i ↦ x i \ y i⟩ @[push ←] theorem Pi.sdiff_def [∀ i, SDiff (π i)] (x y : ∀ i, π i) : x \ y = fun i ↦ x i \ y i := rfl @[simp] theorem Pi.sdiff_apply [∀ i, SDiff (π i)] (x y : ∀ i, π i) (i : ι) : (x \ y) i = x i \ y i := rfl namespace Function variable [Preorder α] [Nonempty β] {a b : α} @[simp] theorem const_le_const : const β a ≤ const β b ↔ a ≤ b := by simp [Pi.le_def] @[simp] theorem const_lt_const : const β a < const β b ↔ a < b := by simpa [Pi.lt_def] using le_of_lt end Function /-! ### Pullbacks of order instances -/ /-- Pull back a `Preorder` instance along an injective function. See note [reducible non-instances]. -/ abbrev Function.Injective.preorder [Preorder β] [LE α] [LT α] (f : α → β) (le : ∀ {x y}, f x ≤ f y ↔ x ≤ y) (lt : ∀ {x y}, f x < f y ↔ x < y) : Preorder α where le_refl _ := le.1 <| le_refl _ le_trans _ _ _ h₁ h₂ := le.1 <| le_trans (le.2 h₁) (le.2 h₂) lt_iff_le_not_ge _ _ := by rw [← le, ← le, ← lt, lt_iff_le_not_ge] /-- Pull back a `PartialOrder` instance along an injective function. See note [reducible non-instances]. -/ abbrev Function.Injective.partialOrder [PartialOrder β] [LE α] [LT α] (f : α → β) (hf : Function.Injective f) (le : ∀ {x y}, f x ≤ f y ↔ x ≤ y) (lt : ∀ {x y}, f x < f y ↔ x < y) : PartialOrder α where __ := Function.Injective.preorder f le lt le_antisymm _ _ h₁ h₂ := hf <| le_antisymm (le.2 h₁) (le.2 h₂) /-- Pull back a `LinearOrder` instance along an injective function. See note [reducible non-instances]. -/ abbrev Function.Injective.linearOrder [LinearOrder β] [LE α] [LT α] [Max α] [Min α] [Ord α] [DecidableEq α] [DecidableLE α] [DecidableLT α] (f : α → β) (hf : Function.Injective f) (le : ∀ {x y}, f x ≤ f y ↔ x ≤ y) (lt : ∀ {x y}, f x < f y ↔ x < y) (min : ∀ x y, f (x ⊓ y) = f x ⊓ f y) (max : ∀ x y, f (x ⊔ y) = f x ⊔ f y) (compare : ∀ x y, compare (f x) (f y) = compare x y) : LinearOrder α where toPartialOrder := hf.partialOrder _ le lt toDecidableLE := ‹_› toDecidableEq := ‹_› toDecidableLT := ‹_› le_total _ _ := by simp only [← le, le_total] min_def _ _ := by simp_rw [← hf.eq_iff, ← le, apply_ite f, ← min_def, min] max_def _ _ := by simp_rw [← hf.eq_iff, ← le, apply_ite f, ← max_def, max] compare_eq_compareOfLessAndEq _ _ := by simp_rw [← compare, LinearOrder.compare_eq_compareOfLessAndEq, compareOfLessAndEq, ← lt, hf.eq_iff] /-! ### Lifts of order instances Unlike the constructions above, these construct new data fields. They should be avoided if the types already define any order or decidability instances. -/ /-- Transfer a `Preorder` on `β` to a `Preorder` on `α` using a function `f : α → β`. See also `Function.Injective.preorder` when only the proof fields need to be transferred. See note [reducible non-instances]. -/ abbrev Preorder.lift [Preorder β] (f : α → β) : Preorder α := letI _instLE : LE α := ⟨fun a b ↦ f a ≤ f b⟩ letI _instLT : LT α := ⟨fun a b ↦ f a < f b⟩ Function.Injective.preorder f .rfl .rfl /-- Transfer a `PartialOrder` on `β` to a `PartialOrder` on `α` using an injective function `f : α → β`. See also `Function.Injective.partialOrder` when only the proof fields need to be transferred. See note [reducible non-instances]. -/ abbrev PartialOrder.lift [PartialOrder β] (f : α → β) (inj : Injective f) : PartialOrder α := letI _instLE : LE α := ⟨fun a b ↦ f a ≤ f b⟩ letI _instLT : LT α := ⟨fun a b ↦ f a < f b⟩ Function.Injective.partialOrder f inj .rfl .rfl theorem compare_of_injective_eq_compareOfLessAndEq (a b : α) [LinearOrder β] [DecidableEq α] (f : α → β) (inj : Injective f) [Decidable (LT.lt (self := PartialOrder.lift f inj |>.toLT) a b)] : compare (f a) (f b) = @compareOfLessAndEq _ a b (PartialOrder.lift f inj |>.toLT) _ _ := by have h := LinearOrder.compare_eq_compareOfLessAndEq (f a) (f b) simp only [h, compareOfLessAndEq] split_ifs <;> try (first | rfl | contradiction) · have : ¬ f a = f b := by rename_i h; exact inj.ne h contradiction · grind /-- Transfer a `LinearOrder` on `β` to a `LinearOrder` on `α` using an injective function `f : α → β`. This version takes `[Max α]` and `[Min α]` as arguments, then uses them for `max` and `min` fields. See `LinearOrder.lift'` for a version that autogenerates `min` and `max` fields, and `LinearOrder.liftWithOrd` for one that does not auto-generate `compare` fields. See also `Function.Injective.linearOrder` when only the proof fields need to be transferred. See note [reducible non-instances]. -/ abbrev LinearOrder.lift [LinearOrder β] [Max α] [Min α] (f : α → β) (inj : Injective f) (hsup : ∀ x y, f (x ⊔ y) = max (f x) (f y)) (hinf : ∀ x y, f (x ⊓ y) = min (f x) (f y)) : LinearOrder α := letI _instLE : LE α := ⟨fun a b ↦ f a ≤ f b⟩ letI _instLT : LT α := ⟨fun a b ↦ f a < f b⟩ letI _instOrdα : Ord α := ⟨fun a b ↦ compare (f a) (f b)⟩ letI _decidableLE := fun x y ↦ (inferInstance : Decidable (f x ≤ f y)) letI _decidableLT := fun x y ↦ (inferInstance : Decidable (f x < f y)) letI _decidableEq := fun x y ↦ decidable_of_iff (f x = f y) inj.eq_iff inj.linearOrder _ .rfl .rfl hinf hsup (fun _ _ => rfl) /-- Transfer a `LinearOrder` on `β` to a `LinearOrder` on `α` using an injective function `f : α → β`. This version autogenerates `min` and `max` fields. See `LinearOrder.lift` for a version that takes `[Max α]` and `[Min α]`, then uses them as `max` and `min`. See `LinearOrder.liftWithOrd'` for a version which does not auto-generate `compare` fields. See note [reducible non-instances]. -/ abbrev LinearOrder.lift' [LinearOrder β] (f : α → β) (inj : Injective f) : LinearOrder α := @LinearOrder.lift α β _ ⟨fun x y ↦ if f x ≤ f y then y else x⟩ ⟨fun x y ↦ if f x ≤ f y then x else y⟩ f inj (fun _ _ ↦ (apply_ite f _ _ _).trans (max_def _ _).symm) fun _ _ ↦ (apply_ite f _ _ _).trans (min_def _ _).symm /-- Transfer a `LinearOrder` on `β` to a `LinearOrder` on `α` using an injective function `f : α → β`. This version takes `[Max α]` and `[Min α]` as arguments, then uses them for `max` and `min` fields. It also takes `[Ord α]` as an argument and uses them for `compare` fields. See `LinearOrder.lift` for a version that autogenerates `compare` fields, and `LinearOrder.liftWithOrd'` for one that auto-generates `min` and `max` fields. fields. See note [reducible non-instances]. -/ abbrev LinearOrder.liftWithOrd [LinearOrder β] [Max α] [Min α] [Ord α] (f : α → β) (inj : Injective f) (hsup : ∀ x y, f (x ⊔ y) = max (f x) (f y)) (hinf : ∀ x y, f (x ⊓ y) = min (f x) (f y)) (compare_f : ∀ a b : α, compare a b = compare (f a) (f b)) : LinearOrder α := letI _instLE : LE α := ⟨fun a b ↦ f a ≤ f b⟩ letI _instLE : LT α := ⟨fun a b ↦ f a < f b⟩ letI _decidableLE := fun x y ↦ (inferInstance : Decidable (f x ≤ f y)) letI _decidableLT := fun x y ↦ (inferInstance : Decidable (f x < f y)) letI _decidableEq := fun x y ↦ decidable_of_iff (f x = f y) inj.eq_iff inj.linearOrder _ .rfl .rfl hinf hsup (fun _ _ => (compare_f _ _).symm) /-- Transfer a `LinearOrder` on `β` to a `LinearOrder` on `α` using an injective function `f : α → β`. This version auto-generates `min` and `max` fields. It also takes `[Ord α]` as an argument and uses them for `compare` fields. See `LinearOrder.lift` for a version that autogenerates `compare` fields, and `LinearOrder.liftWithOrd` for one that doesn't auto-generate `min` and `max` fields. fields. See note [reducible non-instances]. -/ abbrev LinearOrder.liftWithOrd' [LinearOrder β] [Ord α] (f : α → β) (inj : Injective f) (compare_f : ∀ a b : α, compare a b = compare (f a) (f b)) : LinearOrder α := @LinearOrder.liftWithOrd α β _ ⟨fun x y ↦ if f x ≤ f y then y else x⟩ ⟨fun x y ↦ if f x ≤ f y then x else y⟩ _ f inj (fun _ _ ↦ (apply_ite f _ _ _).trans (max_def _ _).symm) (fun _ _ ↦ (apply_ite f _ _ _).trans (min_def _ _).symm) compare_f /-! ### Subtype of an order -/ namespace Subtype @[simp] theorem mk_le_mk [LE α] {p : α → Prop} {x y : α} {hx : p x} {hy : p y} : (⟨x, hx⟩ : Subtype p) ≤ ⟨y, hy⟩ ↔ x ≤ y := Iff.rfl @[gcongr] alias ⟨_, GCongr.mk_le_mk⟩ := mk_le_mk @[simp] theorem mk_lt_mk [LT α] {p : α → Prop} {x y : α} {hx : p x} {hy : p y} : (⟨x, hx⟩ : Subtype p) < ⟨y, hy⟩ ↔ x < y := Iff.rfl @[gcongr] alias ⟨_, GCongr.mk_lt_mk⟩ := mk_lt_mk @[simp, norm_cast] theorem coe_le_coe [LE α] {p : α → Prop} {x y : Subtype p} : (x : α) ≤ y ↔ x ≤ y := Iff.rfl @[gcongr] alias ⟨_, GCongr.coe_le_coe⟩ := coe_le_coe @[simp, norm_cast] theorem coe_lt_coe [LT α] {p : α → Prop} {x y : Subtype p} : (x : α) < y ↔ x < y := Iff.rfl @[gcongr] alias ⟨_, GCongr.coe_lt_coe⟩ := coe_lt_coe instance preorder [Preorder α] (p : α → Prop) : Preorder (Subtype p) := Preorder.lift (fun (a : Subtype p) ↦ (a : α)) instance partialOrder [PartialOrder α] (p : α → Prop) : PartialOrder (Subtype p) := PartialOrder.lift (fun (a : Subtype p) ↦ (a : α)) Subtype.coe_injective instance decidableLE [Preorder α] [h : DecidableLE α] {p : α → Prop} : DecidableLE (Subtype p) := fun a b ↦ h a b instance decidableLT [Preorder α] [h : DecidableLT α] {p : α → Prop} : DecidableLT (Subtype p) := fun a b ↦ h a b /-- A subtype of a linear order is a linear order. We explicitly give the proofs of decidable equality and decidable order in order to ensure the decidability instances are all definitionally equal. -/ instance instLinearOrder [LinearOrder α] (p : α → Prop) : LinearOrder (Subtype p) := @LinearOrder.lift (Subtype p) _ _ ⟨fun x y ↦ ⟨max x y, max_rec' _ x.2 y.2⟩⟩ ⟨fun x y ↦ ⟨min x y, min_rec' _ x.2 y.2⟩⟩ (fun (a : Subtype p) ↦ (a : α)) Subtype.coe_injective (fun _ _ ↦ rfl) fun _ _ ↦ rfl end Subtype /-! ### Pointwise order on `α × β` The lexicographic order is defined in `Data.Prod.Lex`, and the instances are available via the type synonym `α ×ₗ β = α × β`. -/ namespace Prod section LE variable [LE α] [LE β] {x y : α × β} {a a₁ a₂ : α} {b b₁ b₂ : β} instance : LE (α × β) where le p q := p.1 ≤ q.1 ∧ p.2 ≤ q.2 instance instDecidableLE [Decidable (x.1 ≤ y.1)] [Decidable (x.2 ≤ y.2)] : Decidable (x ≤ y) := inferInstanceAs (Decidable (x.1 ≤ y.1 ∧ x.2 ≤ y.2)) lemma le_def : x ≤ y ↔ x.1 ≤ y.1 ∧ x.2 ≤ y.2 := .rfl @[simp] lemma mk_le_mk : (a₁, b₁) ≤ (a₂, b₂) ↔ a₁ ≤ a₂ ∧ b₁ ≤ b₂ := .rfl @[gcongr] lemma GCongr.mk_le_mk (ha : a₁ ≤ a₂) (hb : b₁ ≤ b₂) : (a₁, b₁) ≤ (a₂, b₂) := ⟨ha, hb⟩ @[simp] lemma swap_le_swap : x.swap ≤ y.swap ↔ x ≤ y := and_comm @[simp] lemma swap_le_mk : x.swap ≤ (b, a) ↔ x ≤ (a, b) := and_comm @[simp] lemma mk_le_swap : (b, a) ≤ x.swap ↔ (a, b) ≤ x := and_comm end LE section Preorder variable [Preorder α] [Preorder β] {a a₁ a₂ : α} {b b₁ b₂ : β} {x y : α × β} instance : Preorder (α × β) where __ := inferInstanceAs (LE (α × β)) le_refl := fun ⟨a, b⟩ ↦ ⟨le_refl a, le_refl b⟩ le_trans := fun ⟨_, _⟩ ⟨_, _⟩ ⟨_, _⟩ ⟨hac, hbd⟩ ⟨hce, hdf⟩ ↦ ⟨le_trans hac hce, le_trans hbd hdf⟩ @[simp] theorem swap_lt_swap : x.swap < y.swap ↔ x < y := and_congr swap_le_swap (not_congr swap_le_swap) @[simp] lemma swap_lt_mk : x.swap < (b, a) ↔ x < (a, b) := by rw [← swap_lt_swap]; simp @[simp] lemma mk_lt_swap : (b, a) < x.swap ↔ (a, b) < x := by rw [← swap_lt_swap]; simp theorem mk_le_mk_iff_left : (a₁, b) ≤ (a₂, b) ↔ a₁ ≤ a₂ := and_iff_left le_rfl theorem mk_le_mk_iff_right : (a, b₁) ≤ (a, b₂) ↔ b₁ ≤ b₂ := and_iff_right le_rfl @[gcongr] alias ⟨_, GCongr.mk_le_mk_left⟩ := mk_le_mk_iff_left @[gcongr] alias ⟨_, GCongr.mk_le_mk_right⟩ := mk_le_mk_iff_right theorem mk_lt_mk_iff_left : (a₁, b) < (a₂, b) ↔ a₁ < a₂ := lt_iff_lt_of_le_iff_le' mk_le_mk_iff_left mk_le_mk_iff_left theorem mk_lt_mk_iff_right : (a, b₁) < (a, b₂) ↔ b₁ < b₂ := lt_iff_lt_of_le_iff_le' mk_le_mk_iff_right mk_le_mk_iff_right theorem lt_iff : x < y ↔ x.1 < y.1 ∧ x.2 ≤ y.2 ∨ x.1 ≤ y.1 ∧ x.2 < y.2 := by refine ⟨fun h ↦ ?_, ?_⟩ · by_cases h₁ : y.1 ≤ x.1 · exact Or.inr ⟨h.1.1, LE.le.lt_of_not_ge h.1.2 fun h₂ ↦ h.2 ⟨h₁, h₂⟩⟩ · exact Or.inl ⟨LE.le.lt_of_not_ge h.1.1 h₁, h.1.2⟩ · rintro (⟨h₁, h₂⟩ | ⟨h₁, h₂⟩) · exact ⟨⟨h₁.le, h₂⟩, fun h ↦ h₁.not_ge h.1⟩ · exact ⟨⟨h₁, h₂.le⟩, fun h ↦ h₂.not_ge h.2⟩ @[simp] theorem mk_lt_mk : (a₁, b₁) < (a₂, b₂) ↔ a₁ < a₂ ∧ b₁ ≤ b₂ ∨ a₁ ≤ a₂ ∧ b₁ < b₂ := lt_iff protected lemma lt_of_lt_of_le (h₁ : x.1 < y.1) (h₂ : x.2 ≤ y.2) : x < y := by simp [lt_iff, *] protected lemma lt_of_le_of_lt (h₁ : x.1 ≤ y.1) (h₂ : x.2 < y.2) : x < y := by simp [lt_iff, *] lemma mk_lt_mk_of_lt_of_le (h₁ : a₁ < a₂) (h₂ : b₁ ≤ b₂) : (a₁, b₁) < (a₂, b₂) := by simp [lt_iff, *] lemma mk_lt_mk_of_le_of_lt (h₁ : a₁ ≤ a₂) (h₂ : b₁ < b₂) : (a₁, b₁) < (a₂, b₂) := by simp [lt_iff, *] end Preorder /-- The pointwise partial order on a product. (The lexicographic ordering is defined in `Order.Lexicographic`, and the instances are available via the type synonym `α ×ₗ β = α × β`.) -/ instance instPartialOrder (α β : Type*) [PartialOrder α] [PartialOrder β] : PartialOrder (α × β) where __ := inferInstanceAs (Preorder (α × β)) le_antisymm := fun _ _ ⟨hac, hbd⟩ ⟨hca, hdb⟩ ↦ Prod.ext (hac.antisymm hca) (hbd.antisymm hdb) end Prod /-! ### Additional order classes -/ /-- An order is dense if there is an element between any pair of distinct comparable elements. -/ class DenselyOrdered (α : Type*) [LT α] : Prop where /-- An order is dense if there is an element between any pair of distinct elements. -/ dense : ∀ a₁ a₂ : α, a₁ < a₂ → ∃ a, a₁ < a ∧ a < a₂ theorem exists_between [LT α] [DenselyOrdered α] : ∀ {a₁ a₂ : α}, a₁ < a₂ → ∃ a, a₁ < a ∧ a < a₂ := DenselyOrdered.dense _ _ instance OrderDual.denselyOrdered (α : Type*) [LT α] [h : DenselyOrdered α] : DenselyOrdered αᵒᵈ := ⟨fun _ _ ha ↦ (@exists_between α _ h _ _ ha).imp fun _ ↦ And.symm⟩ @[simp] theorem denselyOrdered_orderDual [LT α] : DenselyOrdered αᵒᵈ ↔ DenselyOrdered α := ⟨by convert @OrderDual.denselyOrdered αᵒᵈ _, @OrderDual.denselyOrdered α _⟩ /-- Any ordered subsingleton is densely ordered. Not an instance to avoid a heavy subsingleton typeclass search. -/ lemma Subsingleton.instDenselyOrdered {X : Type*} [Subsingleton X] [LT X] : DenselyOrdered X := ⟨fun _ _ h ↦ ⟨_, h.trans_eq (Subsingleton.elim _ _), h⟩⟩ instance [Preorder α] [Preorder β] [DenselyOrdered α] [DenselyOrdered β] : DenselyOrdered (α × β) := ⟨fun a b ↦ by simp_rw [Prod.lt_iff] rintro (⟨h₁, h₂⟩ | ⟨h₁, h₂⟩) · obtain ⟨c, ha, hb⟩ := exists_between h₁ exact ⟨(c, _), Or.inl ⟨ha, h₂⟩, Or.inl ⟨hb, le_rfl⟩⟩ · obtain ⟨c, ha, hb⟩ := exists_between h₂ exact ⟨(_, c), Or.inr ⟨h₁, ha⟩, Or.inr ⟨le_rfl, hb⟩⟩⟩ instance [∀ i, Preorder (π i)] [∀ i, DenselyOrdered (π i)] : DenselyOrdered (∀ i, π i) := ⟨fun a b ↦ by classical simp_rw [Pi.lt_def] rintro ⟨hab, i, hi⟩ obtain ⟨c, ha, hb⟩ := exists_between hi exact ⟨Function.update a i c, ⟨le_update_iff.2 ⟨ha.le, fun _ _ ↦ le_rfl⟩, i, by rwa [update_self]⟩, update_le_iff.2 ⟨hb.le, fun _ _ ↦ hab _⟩, i, by rwa [update_self]⟩⟩ section LinearOrder variable [LinearOrder α] [DenselyOrdered α] {a₁ a₂ : α} theorem le_of_forall_gt_imp_ge_of_dense (h : ∀ a, a₂ < a → a₁ ≤ a) : a₁ ≤ a₂ := le_of_not_gt fun ha ↦ let ⟨a, ha₁, ha₂⟩ := exists_between ha lt_irrefl a <| lt_of_lt_of_le ‹a < a₁› (h _ ‹a₂ < a›) lemma forall_gt_imp_ge_iff_le_of_dense : (∀ a, a₂ < a → a₁ ≤ a) ↔ a₁ ≤ a₂ := ⟨le_of_forall_gt_imp_ge_of_dense, fun ha _a ha₂ ↦ ha.trans ha₂.le⟩ lemma eq_of_le_of_forall_lt_imp_le_of_dense (h₁ : a₂ ≤ a₁) (h₂ : ∀ a, a₂ < a → a₁ ≤ a) : a₁ = a₂ := le_antisymm (le_of_forall_gt_imp_ge_of_dense h₂) h₁ theorem le_of_forall_lt_imp_le_of_dense (h : ∀ a < a₁, a ≤ a₂) : a₁ ≤ a₂ := le_of_not_gt fun ha ↦ let ⟨a, ha₁, ha₂⟩ := exists_between ha lt_irrefl a <| lt_of_le_of_lt (h _ ‹a < a₁›) ‹a₂ < a› lemma forall_lt_imp_le_iff_le_of_dense : (∀ a < a₁, a ≤ a₂) ↔ a₁ ≤ a₂ := ⟨le_of_forall_lt_imp_le_of_dense, fun ha _a ha₁ ↦ ha₁.le.trans ha⟩ theorem eq_of_le_of_forall_gt_imp_ge_of_dense (h₁ : a₂ ≤ a₁) (h₂ : ∀ a < a₁, a ≤ a₂) : a₁ = a₂ := (le_of_forall_lt_imp_le_of_dense h₂).antisymm h₁ end LinearOrder theorem dense_or_discrete [LinearOrder α] (a₁ a₂ : α) : (∃ a, a₁ < a ∧ a < a₂) ∨ (∀ a, a₁ < a → a₂ ≤ a) ∧ ∀ a < a₂, a ≤ a₁ := or_iff_not_imp_left.2 fun h ↦ ⟨fun a ha₁ ↦ le_of_not_gt fun ha₂ ↦ h ⟨a, ha₁, ha₂⟩, fun a ha₂ ↦ le_of_not_gt fun ha₁ ↦ h ⟨a, ha₁, ha₂⟩⟩ /-- If a linear order has no elements `x < y < z`, then it has at most two elements. -/ lemma eq_or_eq_or_eq_of_forall_not_lt_lt [LinearOrder α] (h : ∀ ⦃x y z : α⦄, x < y → y < z → False) (x y z : α) : x = y ∨ y = z ∨ x = z := by by_contra hne simp only [not_or, ← Ne.eq_def] at hne rcases hne.1.lt_or_gt with h₁ | h₁ <;> rcases hne.2.1.lt_or_gt with h₂ | h₂ <;> rcases hne.2.2.lt_or_gt with h₃ | h₃ exacts [h h₁ h₂, h h₂ h₃, h h₃ h₂, h h₃ h₁, h h₁ h₃, h h₂ h₃, h h₁ h₃, h h₂ h₁] namespace PUnit variable (a b : PUnit) instance instLinearOrder : LinearOrder PUnit where le := fun _ _ ↦ True lt := fun _ _ ↦ False max := fun _ _ ↦ unit min := fun _ _ ↦ unit toDecidableEq := inferInstance toDecidableLE := fun _ _ ↦ Decidable.isTrue trivial toDecidableLT := fun _ _ ↦ Decidable.isFalse id le_refl := by intros; trivial le_trans := by intros; trivial le_total := by intros; exact Or.inl trivial le_antisymm := by intros; rfl lt_iff_le_not_ge := by simp only [not_true, and_false, forall_const] theorem max_eq : max a b = unit := rfl theorem min_eq : min a b = unit := rfl protected theorem le : a ≤ b := trivial theorem not_lt : ¬a < b := not_false instance : DenselyOrdered PUnit := ⟨fun _ _ ↦ False.elim⟩ end PUnit section «Prop» /-- Propositions form a complete Boolean algebra, where the `≤` relation is given by implication. -/ instance Prop.le : LE Prop := ⟨(· → ·)⟩ @[simp] theorem le_Prop_eq : ((· ≤ ·) : Prop → Prop → Prop) = (· → ·) := rfl theorem subrelation_iff_le {r s : α → α → Prop} : Subrelation r s ↔ r ≤ s := Iff.rfl instance Prop.partialOrder : PartialOrder Prop where __ := Prop.le le_refl _ := id le_trans _ _ _ f g := g ∘ f le_antisymm _ _ Hab Hba := propext ⟨Hab, Hba⟩ end «Prop» /-! ### Linear order from a total partial order -/ /-- Type synonym to create an instance of `LinearOrder` from a `PartialOrder` and `IsTotal α (≤)` -/ def AsLinearOrder (α : Type*) := α instance [Inhabited α] : Inhabited (AsLinearOrder α) := ⟨(default : α)⟩ noncomputable instance AsLinearOrder.linearOrder [PartialOrder α] [IsTotal α (· ≤ ·)] : LinearOrder (AsLinearOrder α) where __ := inferInstanceAs (PartialOrder α) le_total := @total_of α (· ≤ ·) _ toDecidableLE := Classical.decRel _
.lake/packages/mathlib/Mathlib/Order/BooleanGenerators.lean
import Mathlib.Order.CompactlyGenerated.Basic /-! # Generators for Boolean algebras In this file, we provide an alternative constructor for Boolean algebras. A set of *Boolean generators* in a compactly generated complete lattice is a subset `S` such that * the elements of `S` are all atoms, and * the set `S` satisfies an atomicity condition: any compact element below the supremum of a subset `s` of generators is equal to the supremum of a subset of `s`. ## Main declarations * `IsCompactlyGenerated.BooleanGenerators`: the predicate described above. * `IsCompactlyGenerated.BooleanGenerators.complementedLattice_of_sSup_eq_top`: if `S` generates the entire lattice, then it is complemented. * `IsCompactlyGenerated.BooleanGenerators.distribLattice_of_sSup_eq_top`: if `S` generates the entire lattice, then it is distributive. * `IsCompactlyGenerated.BooleanGenerators.booleanAlgebra_of_sSup_eq_top`: if `S` generates the entire lattice, then it is a Boolean algebra. -/ namespace IsCompactlyGenerated open CompleteLattice variable {α : Type*} [CompleteLattice α] /-- An alternative constructor for Boolean algebras. A set of *Boolean generators* in a compactly generated complete lattice is a subset `S` such that * the elements of `S` are all atoms, and * the set `S` satisfies an atomicity condition: any compact element below the supremum of a finite subset `s` of generators is equal to the supremum of a subset of `s`. If the supremum of `S` is the whole lattice, then the lattice is a Boolean algebra (see `IsCompactlyGenerated.BooleanGenerators.booleanAlgebra_of_sSup_eq_top`). -/ structure BooleanGenerators (S : Set α) : Prop where /-- The elements in a collection of Boolean generators are all atoms. -/ isAtom : ∀ I ∈ S, IsAtom I /-- The elements in a collection of Boolean generators satisfy an atomicity condition: any compact element below the supremum of a finite subset `s` of generators is equal to the supremum of a subset of `s`. -/ finitelyAtomistic : ∀ (s : Finset α) (a : α), ↑s ⊆ S → IsCompactElement a → a ≤ s.sup id → ∃ t ⊆ s, a = t.sup id namespace BooleanGenerators variable {S : Set α} lemma mono (hS : BooleanGenerators S) {T : Set α} (hTS : T ⊆ S) : BooleanGenerators T where isAtom I hI := hS.isAtom I (hTS hI) finitelyAtomistic := fun s a hs ↦ hS.finitelyAtomistic s a (le_trans hs hTS) variable [IsCompactlyGenerated α] lemma atomistic (hS : BooleanGenerators S) (a : α) (ha : a ≤ sSup S) : ∃ T ⊆ S, a = sSup T := by obtain ⟨C, hC, rfl⟩ := IsCompactlyGenerated.exists_sSup_eq a have aux : ∀ b : α, IsCompactElement b → b ≤ sSup S → ∃ T ⊆ S, b = sSup T := by intro b hb hbS obtain ⟨s, hs₁, hs₂⟩ := hb S hbS obtain ⟨t, ht, rfl⟩ := hS.finitelyAtomistic s b hs₁ hb hs₂ refine ⟨t, ?_, Finset.sup_id_eq_sSup t⟩ refine Set.Subset.trans ?_ hs₁ simpa only [Finset.coe_subset] using ht choose T hT₁ hT₂ using aux use sSup {T c h₁ h₂ | (c ∈ C) (h₁ : IsCompactElement c) (h₂ : c ≤ sSup S)} constructor · apply _root_.sSup_le rintro _ ⟨c, -, h₁, h₂, rfl⟩ apply hT₁ · apply le_antisymm · apply _root_.sSup_le intro c hc rw [hT₂ c (hC _ hc) ((le_sSup hc).trans ha)] apply sSup_le_sSup apply _root_.le_sSup use c, hc, hC _ hc, (le_sSup hc).trans ha · simp only [Set.sSup_eq_sUnion, sSup_le_iff, Set.mem_sUnion, Set.mem_setOf_eq, forall_exists_index, and_imp] rintro a T b hbC hb hbS rfl haT apply (le_sSup haT).trans rw [← hT₂] exact le_sSup hbC lemma isAtomistic_of_sSup_eq_top (hS : BooleanGenerators S) (h : sSup S = ⊤) : IsAtomistic α := by refine CompleteLattice.isAtomistic_iff.2 fun a ↦ ?_ obtain ⟨s, hs, hs'⟩ := hS.atomistic a (h ▸ le_top) exact ⟨s, hs', fun I hI ↦ hS.isAtom I (hs hI)⟩ lemma mem_of_isAtom_of_le_sSup_atoms (hS : BooleanGenerators S) (a : α) (ha : IsAtom a) (haS : a ≤ sSup S) : a ∈ S := by obtain ⟨T, hT, rfl⟩ := hS.atomistic a haS obtain rfl | ⟨a, haT⟩ := T.eq_empty_or_nonempty · simp only [sSup_empty] at ha exact (ha.1 rfl).elim suffices sSup T = a from this ▸ hT haT have : a ≤ sSup T := le_sSup haT rwa [ha.le_iff_eq, eq_comm] at this exact (hS.isAtom a (hT haT)).1 lemma sSup_inter (hS : BooleanGenerators S) {T₁ T₂ : Set α} (hT₁ : T₁ ⊆ S) (hT₂ : T₂ ⊆ S) : sSup (T₁ ∩ T₂) = (sSup T₁) ⊓ (sSup T₂) := by apply le_antisymm · apply le_inf · apply sSup_le_sSup Set.inter_subset_left · apply sSup_le_sSup Set.inter_subset_right obtain ⟨X, hX, hX'⟩ := hS.atomistic (sSup T₁ ⊓ sSup T₂) (inf_le_left.trans (sSup_le_sSup hT₁)) rw [hX'] apply _root_.sSup_le intro I hI apply _root_.le_sSup constructor · apply (hS.mono hT₁).mem_of_isAtom_of_le_sSup_atoms _ _ _ · exact (hS.mono hX).isAtom I hI · exact (_root_.le_sSup hI).trans (hX'.ge.trans inf_le_left) · apply (hS.mono hT₂).mem_of_isAtom_of_le_sSup_atoms _ _ _ · exact (hS.mono hX).isAtom I hI · exact (_root_.le_sSup hI).trans (hX'.ge.trans inf_le_right) /-- A lattice generated by Boolean generators is a distributive lattice. -/ def distribLattice_of_sSup_eq_top (hS : BooleanGenerators S) (h : sSup S = ⊤) : DistribLattice α where le_sup_inf a b c := by obtain ⟨Ta, hTa, rfl⟩ := hS.atomistic a (h ▸ le_top) obtain ⟨Tb, hTb, rfl⟩ := hS.atomistic b (h ▸ le_top) obtain ⟨Tc, hTc, rfl⟩ := hS.atomistic c (h ▸ le_top) apply le_of_eq rw [← sSup_union, ← sSup_union, ← hS.sSup_inter hTb hTc, ← hS.sSup_inter, ← sSup_union] on_goal 1 => congr 1; ext all_goals simp only [Set.union_subset_iff, Set.mem_inter_iff, Set.mem_union] tauto lemma complementedLattice_of_sSup_eq_top (hS : BooleanGenerators S) (h : sSup S = ⊤) : ComplementedLattice α := by let _i := hS.distribLattice_of_sSup_eq_top h have _i₁ := isAtomistic_of_sSup_eq_top hS h apply complementedLattice_of_isAtomistic /-- A compactly generated complete lattice generated by Boolean generators is a Boolean algebra. -/ noncomputable def booleanAlgebra_of_sSup_eq_top (hS : BooleanGenerators S) (h : sSup S = ⊤) : BooleanAlgebra α := let _i := hS.distribLattice_of_sSup_eq_top h have := hS.complementedLattice_of_sSup_eq_top h DistribLattice.booleanAlgebraOfComplemented α lemma sSup_le_sSup_iff_of_atoms (hS : BooleanGenerators S) (X Y : Set α) (hX : X ⊆ S) (hY : Y ⊆ S) : sSup X ≤ sSup Y ↔ X ⊆ Y := by refine ⟨?_, sSup_le_sSup⟩ intro h a ha apply (hS.mono hY).mem_of_isAtom_of_le_sSup_atoms _ _ ((le_sSup ha).trans h) exact (hS.mono hX).isAtom a ha lemma eq_atoms_of_sSup_eq_top (hS : BooleanGenerators S) (h : sSup S = ⊤) : S = {a : α | IsAtom a} := by apply le_antisymm · exact hS.isAtom intro a ha obtain ⟨T, hT, rfl⟩ := hS.atomistic a (le_top.trans h.ge) exact hS.mem_of_isAtom_of_le_sSup_atoms _ ha (sSup_le_sSup hT) end BooleanGenerators end IsCompactlyGenerated
.lake/packages/mathlib/Mathlib/Order/Disjoint.lean
import Aesop import Mathlib.Order.BoundedOrder.Lattice /-! # Disjointness and complements This file defines `Disjoint`, `Codisjoint`, and the `IsCompl` predicate. ## Main declarations * `Disjoint x y`: two elements of a lattice are disjoint if their `inf` is the bottom element. * `Codisjoint x y`: two elements of a lattice are codisjoint if their `join` is the top element. * `IsCompl x y`: In a bounded lattice, predicate for "`x` is a complement of `y`". Note that in a non-distributive lattice, an element can have several complements. * `ComplementedLattice α`: Typeclass stating that any element of a lattice has a complement. -/ open Function variable {α : Type*} section Disjoint section PartialOrderBot variable [PartialOrder α] [OrderBot α] {a b c d : α} /-- Two elements of a lattice are disjoint if their inf is the bottom element. (This generalizes disjoint sets, viewed as members of the subset lattice.) Note that we define this without reference to `⊓`, as this allows us to talk about orders where the infimum is not unique, or where implementing `Inf` would require additional `Decidable` arguments. -/ def Disjoint (a b : α) : Prop := ∀ ⦃x⦄, x ≤ a → x ≤ b → x ≤ ⊥ @[simp] theorem disjoint_of_subsingleton [Subsingleton α] : Disjoint a b := fun x _ _ ↦ le_of_eq (Subsingleton.elim x ⊥) theorem disjoint_comm : Disjoint a b ↔ Disjoint b a := forall_congr' fun _ ↦ forall_swap @[symm] theorem Disjoint.symm ⦃a b : α⦄ : Disjoint a b → Disjoint b a := disjoint_comm.1 theorem symmetric_disjoint : Symmetric (Disjoint : α → α → Prop) := Disjoint.symm @[simp] theorem disjoint_bot_left : Disjoint ⊥ a := fun _ hbot _ ↦ hbot @[simp] theorem disjoint_bot_right : Disjoint a ⊥ := fun _ _ hbot ↦ hbot @[gcongr] theorem Disjoint.mono (h₁ : a ≤ b) (h₂ : c ≤ d) : Disjoint b d → Disjoint a c := fun h _ ha hc ↦ h (ha.trans h₁) (hc.trans h₂) theorem Disjoint.mono_left (h : a ≤ b) : Disjoint b c → Disjoint a c := Disjoint.mono h le_rfl theorem Disjoint.mono_right (h : b ≤ c) : Disjoint a c → Disjoint a b := Disjoint.mono le_rfl h @[simp] theorem disjoint_self : Disjoint a a ↔ a = ⊥ := ⟨fun hd ↦ bot_unique <| hd le_rfl le_rfl, fun h _ ha _ ↦ ha.trans_eq h⟩ /- TODO: Rename `Disjoint.eq_bot` to `Disjoint.inf_eq` and `Disjoint.eq_bot_of_self` to `Disjoint.eq_bot` -/ alias ⟨Disjoint.eq_bot_of_self, _⟩ := disjoint_self theorem Disjoint.ne (ha : a ≠ ⊥) (hab : Disjoint a b) : a ≠ b := fun h ↦ ha <| disjoint_self.1 <| by rwa [← h] at hab theorem Disjoint.eq_bot_of_le (hab : Disjoint a b) (h : a ≤ b) : a = ⊥ := eq_bot_iff.2 <| hab le_rfl h theorem Disjoint.eq_bot_of_ge (hab : Disjoint a b) : b ≤ a → b = ⊥ := hab.symm.eq_bot_of_le lemma Disjoint.eq_iff (hab : Disjoint a b) : a = b ↔ a = ⊥ ∧ b = ⊥ := by aesop lemma Disjoint.ne_iff (hab : Disjoint a b) : a ≠ b ↔ a ≠ ⊥ ∨ b ≠ ⊥ := hab.eq_iff.not.trans not_and_or theorem disjoint_of_le_iff_left_eq_bot (h : a ≤ b) : Disjoint a b ↔ a = ⊥ := ⟨fun hd ↦ hd.eq_bot_of_le h, fun h ↦ h ▸ disjoint_bot_left⟩ end PartialOrderBot section PartialBoundedOrder variable [PartialOrder α] [BoundedOrder α] {a : α} @[simp] theorem disjoint_top : Disjoint a ⊤ ↔ a = ⊥ := ⟨fun h ↦ bot_unique <| h le_rfl le_top, fun h _ ha _ ↦ ha.trans_eq h⟩ @[simp] theorem top_disjoint : Disjoint ⊤ a ↔ a = ⊥ := ⟨fun h ↦ bot_unique <| h le_top le_rfl, fun h _ _ ha ↦ ha.trans_eq h⟩ end PartialBoundedOrder section SemilatticeInfBot variable [SemilatticeInf α] [OrderBot α] {a b c : α} theorem disjoint_iff_inf_le : Disjoint a b ↔ a ⊓ b ≤ ⊥ := ⟨fun hd ↦ hd inf_le_left inf_le_right, fun h _ ha hb ↦ (le_inf ha hb).trans h⟩ theorem disjoint_iff : Disjoint a b ↔ a ⊓ b = ⊥ := disjoint_iff_inf_le.trans le_bot_iff theorem Disjoint.le_bot : Disjoint a b → a ⊓ b ≤ ⊥ := disjoint_iff_inf_le.mp theorem Disjoint.eq_bot : Disjoint a b → a ⊓ b = ⊥ := bot_unique ∘ Disjoint.le_bot theorem disjoint_assoc : Disjoint (a ⊓ b) c ↔ Disjoint a (b ⊓ c) := by rw [disjoint_iff_inf_le, disjoint_iff_inf_le, inf_assoc] theorem disjoint_left_comm : Disjoint a (b ⊓ c) ↔ Disjoint b (a ⊓ c) := by simp_rw [disjoint_iff_inf_le, inf_left_comm] theorem disjoint_right_comm : Disjoint (a ⊓ b) c ↔ Disjoint (a ⊓ c) b := by simp_rw [disjoint_iff_inf_le, inf_right_comm] variable (c) theorem Disjoint.inf_left (h : Disjoint a b) : Disjoint (a ⊓ c) b := h.mono_left inf_le_left theorem Disjoint.inf_left' (h : Disjoint a b) : Disjoint (c ⊓ a) b := h.mono_left inf_le_right theorem Disjoint.inf_right (h : Disjoint a b) : Disjoint a (b ⊓ c) := h.mono_right inf_le_left theorem Disjoint.inf_right' (h : Disjoint a b) : Disjoint a (c ⊓ b) := h.mono_right inf_le_right variable {c} theorem Disjoint.of_disjoint_inf_of_le (h : Disjoint (a ⊓ b) c) (hle : a ≤ c) : Disjoint a b := disjoint_iff.2 <| h.eq_bot_of_le <| inf_le_of_left_le hle theorem Disjoint.of_disjoint_inf_of_le' (h : Disjoint (a ⊓ b) c) (hle : b ≤ c) : Disjoint a b := disjoint_iff.2 <| h.eq_bot_of_le <| inf_le_of_right_le hle end SemilatticeInfBot theorem Disjoint.right_lt_sup_of_left_ne_bot [SemilatticeSup α] [OrderBot α] {a b : α} (h : Disjoint a b) (ha : a ≠ ⊥) : b < a ⊔ b := le_sup_right.lt_of_ne fun eq ↦ ha (le_bot_iff.mp <| h le_rfl <| sup_eq_right.mp eq.symm) section DistribLatticeBot variable [DistribLattice α] [OrderBot α] {a b c : α} @[simp] theorem disjoint_sup_left : Disjoint (a ⊔ b) c ↔ Disjoint a c ∧ Disjoint b c := by simp only [disjoint_iff, inf_sup_right, sup_eq_bot_iff] @[simp] theorem disjoint_sup_right : Disjoint a (b ⊔ c) ↔ Disjoint a b ∧ Disjoint a c := by simp only [disjoint_iff, inf_sup_left, sup_eq_bot_iff] theorem Disjoint.sup_left (ha : Disjoint a c) (hb : Disjoint b c) : Disjoint (a ⊔ b) c := disjoint_sup_left.2 ⟨ha, hb⟩ theorem Disjoint.sup_right (hb : Disjoint a b) (hc : Disjoint a c) : Disjoint a (b ⊔ c) := disjoint_sup_right.2 ⟨hb, hc⟩ theorem Disjoint.left_le_of_le_sup_right (h : a ≤ b ⊔ c) (hd : Disjoint a c) : a ≤ b := le_of_inf_le_sup_le (le_trans hd.le_bot bot_le) <| sup_le h le_sup_right theorem Disjoint.left_le_of_le_sup_left (h : a ≤ c ⊔ b) (hd : Disjoint a c) : a ≤ b := hd.left_le_of_le_sup_right <| by rwa [sup_comm] end DistribLatticeBot end Disjoint section Codisjoint section PartialOrderTop variable [PartialOrder α] [OrderTop α] {a b c d : α} /-- Two elements of a lattice are codisjoint if their sup is the top element. Note that we define this without reference to `⊔`, as this allows us to talk about orders where the supremum is not unique, or where implementing `Sup` would require additional `Decidable` arguments. -/ def Codisjoint (a b : α) : Prop := ∀ ⦃x⦄, a ≤ x → b ≤ x → ⊤ ≤ x theorem codisjoint_comm : Codisjoint a b ↔ Codisjoint b a := forall_congr' fun _ ↦ forall_swap @[symm] theorem Codisjoint.symm ⦃a b : α⦄ : Codisjoint a b → Codisjoint b a := codisjoint_comm.1 theorem symmetric_codisjoint : Symmetric (Codisjoint : α → α → Prop) := Codisjoint.symm @[simp] theorem codisjoint_top_left : Codisjoint ⊤ a := fun _ htop _ ↦ htop @[simp] theorem codisjoint_top_right : Codisjoint a ⊤ := fun _ _ htop ↦ htop @[gcongr] theorem Codisjoint.mono (h₁ : a ≤ b) (h₂ : c ≤ d) : Codisjoint a c → Codisjoint b d := fun h _ ha hc ↦ h (h₁.trans ha) (h₂.trans hc) theorem Codisjoint.mono_left (h : a ≤ b) : Codisjoint a c → Codisjoint b c := Codisjoint.mono h le_rfl theorem Codisjoint.mono_right : b ≤ c → Codisjoint a b → Codisjoint a c := Codisjoint.mono le_rfl @[simp] theorem codisjoint_self : Codisjoint a a ↔ a = ⊤ := ⟨fun hd ↦ top_unique <| hd le_rfl le_rfl, fun h _ ha _ ↦ h.symm.trans_le ha⟩ /- TODO: Rename `Codisjoint.eq_top` to `Codisjoint.sup_eq` and `Codisjoint.eq_top_of_self` to `Codisjoint.eq_top` -/ alias ⟨Codisjoint.eq_top_of_self, _⟩ := codisjoint_self theorem Codisjoint.ne (ha : a ≠ ⊤) (hab : Codisjoint a b) : a ≠ b := fun h ↦ ha <| codisjoint_self.1 <| by rwa [← h] at hab theorem Codisjoint.eq_top_of_le (hab : Codisjoint a b) (h : b ≤ a) : a = ⊤ := eq_top_iff.2 <| hab le_rfl h theorem Codisjoint.eq_top_of_ge (hab : Codisjoint a b) : a ≤ b → b = ⊤ := hab.symm.eq_top_of_le lemma Codisjoint.eq_iff (hab : Codisjoint a b) : a = b ↔ a = ⊤ ∧ b = ⊤ := by aesop lemma Codisjoint.ne_iff (hab : Codisjoint a b) : a ≠ b ↔ a ≠ ⊤ ∨ b ≠ ⊤ := hab.eq_iff.not.trans not_and_or end PartialOrderTop section PartialBoundedOrder variable [PartialOrder α] [BoundedOrder α] {a b : α} @[simp] theorem codisjoint_bot : Codisjoint a ⊥ ↔ a = ⊤ := ⟨fun h ↦ top_unique <| h le_rfl bot_le, fun h _ ha _ ↦ h.symm.trans_le ha⟩ @[simp] theorem bot_codisjoint : Codisjoint ⊥ a ↔ a = ⊤ := ⟨fun h ↦ top_unique <| h bot_le le_rfl, fun h _ _ ha ↦ h.symm.trans_le ha⟩ lemma Codisjoint.ne_bot_of_ne_top (h : Codisjoint a b) (ha : a ≠ ⊤) : b ≠ ⊥ := by rintro rfl; exact ha <| by simpa using h @[deprecated ne_bot_of_ne_top (since := "2025-11-07")] lemma Codisjoint.ne_bot_of_ne_top' (h : Codisjoint a b) (hb : b ≠ ⊤) : a ≠ ⊥ := ne_bot_of_ne_top h.symm hb end PartialBoundedOrder section SemilatticeSupTop variable [SemilatticeSup α] [OrderTop α] {a b c : α} theorem codisjoint_iff_le_sup : Codisjoint a b ↔ ⊤ ≤ a ⊔ b := @disjoint_iff_inf_le αᵒᵈ _ _ _ _ theorem codisjoint_iff : Codisjoint a b ↔ a ⊔ b = ⊤ := @disjoint_iff αᵒᵈ _ _ _ _ theorem Codisjoint.top_le : Codisjoint a b → ⊤ ≤ a ⊔ b := @Disjoint.le_bot αᵒᵈ _ _ _ _ theorem Codisjoint.eq_top : Codisjoint a b → a ⊔ b = ⊤ := @Disjoint.eq_bot αᵒᵈ _ _ _ _ theorem codisjoint_assoc : Codisjoint (a ⊔ b) c ↔ Codisjoint a (b ⊔ c) := @disjoint_assoc αᵒᵈ _ _ _ _ _ theorem codisjoint_left_comm : Codisjoint a (b ⊔ c) ↔ Codisjoint b (a ⊔ c) := @disjoint_left_comm αᵒᵈ _ _ _ _ _ theorem codisjoint_right_comm : Codisjoint (a ⊔ b) c ↔ Codisjoint (a ⊔ c) b := @disjoint_right_comm αᵒᵈ _ _ _ _ _ variable (c) theorem Codisjoint.sup_left (h : Codisjoint a b) : Codisjoint (a ⊔ c) b := h.mono_left le_sup_left theorem Codisjoint.sup_left' (h : Codisjoint a b) : Codisjoint (c ⊔ a) b := h.mono_left le_sup_right theorem Codisjoint.sup_right (h : Codisjoint a b) : Codisjoint a (b ⊔ c) := h.mono_right le_sup_left theorem Codisjoint.sup_right' (h : Codisjoint a b) : Codisjoint a (c ⊔ b) := h.mono_right le_sup_right variable {c} theorem Codisjoint.of_codisjoint_sup_of_le (h : Codisjoint (a ⊔ b) c) (hle : c ≤ a) : Codisjoint a b := @Disjoint.of_disjoint_inf_of_le αᵒᵈ _ _ _ _ _ h hle theorem Codisjoint.of_codisjoint_sup_of_le' (h : Codisjoint (a ⊔ b) c) (hle : c ≤ b) : Codisjoint a b := @Disjoint.of_disjoint_inf_of_le' αᵒᵈ _ _ _ _ _ h hle end SemilatticeSupTop section DistribLatticeTop variable [DistribLattice α] [OrderTop α] {a b c : α} @[simp] theorem codisjoint_inf_left : Codisjoint (a ⊓ b) c ↔ Codisjoint a c ∧ Codisjoint b c := by simp only [codisjoint_iff, sup_inf_right, inf_eq_top_iff] @[simp] theorem codisjoint_inf_right : Codisjoint a (b ⊓ c) ↔ Codisjoint a b ∧ Codisjoint a c := by simp only [codisjoint_iff, sup_inf_left, inf_eq_top_iff] theorem Codisjoint.inf_left (ha : Codisjoint a c) (hb : Codisjoint b c) : Codisjoint (a ⊓ b) c := codisjoint_inf_left.2 ⟨ha, hb⟩ theorem Codisjoint.inf_right (hb : Codisjoint a b) (hc : Codisjoint a c) : Codisjoint a (b ⊓ c) := codisjoint_inf_right.2 ⟨hb, hc⟩ theorem Codisjoint.left_le_of_le_inf_right (h : a ⊓ b ≤ c) (hd : Codisjoint b c) : a ≤ c := @Disjoint.left_le_of_le_sup_right αᵒᵈ _ _ _ _ _ h hd.symm theorem Codisjoint.left_le_of_le_inf_left (h : b ⊓ a ≤ c) (hd : Codisjoint b c) : a ≤ c := hd.left_le_of_le_inf_right <| by rwa [inf_comm] end DistribLatticeTop end Codisjoint open OrderDual theorem Disjoint.dual [PartialOrder α] [OrderBot α] {a b : α} : Disjoint a b → Codisjoint (toDual a) (toDual b) := id theorem Codisjoint.dual [PartialOrder α] [OrderTop α] {a b : α} : Codisjoint a b → Disjoint (toDual a) (toDual b) := id @[simp] theorem disjoint_toDual_iff [PartialOrder α] [OrderTop α] {a b : α} : Disjoint (toDual a) (toDual b) ↔ Codisjoint a b := Iff.rfl @[simp] theorem disjoint_ofDual_iff [PartialOrder α] [OrderBot α] {a b : αᵒᵈ} : Disjoint (ofDual a) (ofDual b) ↔ Codisjoint a b := Iff.rfl @[simp] theorem codisjoint_toDual_iff [PartialOrder α] [OrderBot α] {a b : α} : Codisjoint (toDual a) (toDual b) ↔ Disjoint a b := Iff.rfl @[simp] theorem codisjoint_ofDual_iff [PartialOrder α] [OrderTop α] {a b : αᵒᵈ} : Codisjoint (ofDual a) (ofDual b) ↔ Disjoint a b := Iff.rfl section DistribLattice variable [DistribLattice α] [BoundedOrder α] {a b c : α} theorem Disjoint.le_of_codisjoint (hab : Disjoint a b) (hbc : Codisjoint b c) : a ≤ c := by rw [← @inf_top_eq _ _ _ a, ← @bot_sup_eq _ _ _ c, ← hab.eq_bot, ← hbc.eq_top, sup_inf_right] exact inf_le_inf_right _ le_sup_left end DistribLattice section IsCompl /-- Two elements `x` and `y` are complements of each other if `x ⊔ y = ⊤` and `x ⊓ y = ⊥`. -/ structure IsCompl [PartialOrder α] [BoundedOrder α] (x y : α) : Prop where /-- If `x` and `y` are to be complementary in an order, they should be disjoint. -/ protected disjoint : Disjoint x y /-- If `x` and `y` are to be complementary in an order, they should be codisjoint. -/ protected codisjoint : Codisjoint x y theorem isCompl_iff [PartialOrder α] [BoundedOrder α] {a b : α} : IsCompl a b ↔ Disjoint a b ∧ Codisjoint a b := ⟨fun h ↦ ⟨h.1, h.2⟩, fun h ↦ ⟨h.1, h.2⟩⟩ namespace IsCompl section BoundedPartialOrder variable [PartialOrder α] [BoundedOrder α] {x y : α} @[symm] protected theorem symm (h : IsCompl x y) : IsCompl y x := ⟨h.1.symm, h.2.symm⟩ lemma _root_.isCompl_comm : IsCompl x y ↔ IsCompl y x := ⟨IsCompl.symm, IsCompl.symm⟩ theorem dual (h : IsCompl x y) : IsCompl (toDual x) (toDual y) := ⟨h.2, h.1⟩ theorem ofDual {a b : αᵒᵈ} (h : IsCompl a b) : IsCompl (ofDual a) (ofDual b) := ⟨h.2, h.1⟩ end BoundedPartialOrder section BoundedLattice variable [Lattice α] [BoundedOrder α] {x y : α} theorem of_le (h₁ : x ⊓ y ≤ ⊥) (h₂ : ⊤ ≤ x ⊔ y) : IsCompl x y := ⟨disjoint_iff_inf_le.mpr h₁, codisjoint_iff_le_sup.mpr h₂⟩ theorem of_eq (h₁ : x ⊓ y = ⊥) (h₂ : x ⊔ y = ⊤) : IsCompl x y := ⟨disjoint_iff.mpr h₁, codisjoint_iff.mpr h₂⟩ theorem inf_eq_bot (h : IsCompl x y) : x ⊓ y = ⊥ := h.disjoint.eq_bot theorem sup_eq_top (h : IsCompl x y) : x ⊔ y = ⊤ := h.codisjoint.eq_top end BoundedLattice variable [DistribLattice α] [BoundedOrder α] {a b x y z : α} theorem inf_left_le_of_le_sup_right (h : IsCompl x y) (hle : a ≤ b ⊔ y) : a ⊓ x ≤ b := calc a ⊓ x ≤ (b ⊔ y) ⊓ x := inf_le_inf hle le_rfl _ = b ⊓ x ⊔ y ⊓ x := inf_sup_right _ _ _ _ = b ⊓ x := by rw [h.symm.inf_eq_bot, sup_bot_eq] _ ≤ b := inf_le_left theorem le_sup_right_iff_inf_left_le {a b} (h : IsCompl x y) : a ≤ b ⊔ y ↔ a ⊓ x ≤ b := ⟨h.inf_left_le_of_le_sup_right, h.symm.dual.inf_left_le_of_le_sup_right⟩ theorem inf_left_eq_bot_iff (h : IsCompl y z) : x ⊓ y = ⊥ ↔ x ≤ z := by rw [← le_bot_iff, ← h.le_sup_right_iff_inf_left_le, bot_sup_eq] theorem inf_right_eq_bot_iff (h : IsCompl y z) : x ⊓ z = ⊥ ↔ x ≤ y := h.symm.inf_left_eq_bot_iff theorem disjoint_left_iff (h : IsCompl y z) : Disjoint x y ↔ x ≤ z := by rw [disjoint_iff] exact h.inf_left_eq_bot_iff theorem disjoint_right_iff (h : IsCompl y z) : Disjoint x z ↔ x ≤ y := h.symm.disjoint_left_iff theorem le_left_iff (h : IsCompl x y) : z ≤ x ↔ Disjoint z y := h.disjoint_right_iff.symm theorem le_right_iff (h : IsCompl x y) : z ≤ y ↔ Disjoint z x := h.symm.le_left_iff theorem left_le_iff (h : IsCompl x y) : x ≤ z ↔ Codisjoint z y := h.dual.le_left_iff theorem right_le_iff (h : IsCompl x y) : y ≤ z ↔ Codisjoint z x := h.symm.left_le_iff protected theorem Antitone {x' y'} (h : IsCompl x y) (h' : IsCompl x' y') (hx : x ≤ x') : y' ≤ y := h'.right_le_iff.2 <| h.symm.codisjoint.mono_right hx theorem right_unique (hxy : IsCompl x y) (hxz : IsCompl x z) : y = z := le_antisymm (hxz.Antitone hxy <| le_refl x) (hxy.Antitone hxz <| le_refl x) theorem left_unique (hxz : IsCompl x z) (hyz : IsCompl y z) : x = y := hxz.symm.right_unique hyz.symm theorem sup_inf {x' y'} (h : IsCompl x y) (h' : IsCompl x' y') : IsCompl (x ⊔ x') (y ⊓ y') := of_eq (by rw [inf_sup_right, ← inf_assoc, h.inf_eq_bot, bot_inf_eq, bot_sup_eq, inf_left_comm, h'.inf_eq_bot, inf_bot_eq]) (by rw [sup_inf_left, sup_comm x, sup_assoc, h.sup_eq_top, sup_top_eq, top_inf_eq, sup_assoc, sup_left_comm, h'.sup_eq_top, sup_top_eq]) theorem inf_sup {x' y'} (h : IsCompl x y) (h' : IsCompl x' y') : IsCompl (x ⊓ x') (y ⊔ y') := (h.symm.sup_inf h'.symm).symm end IsCompl namespace Prod variable {β : Type*} [PartialOrder α] [PartialOrder β] protected theorem disjoint_iff [OrderBot α] [OrderBot β] {x y : α × β} : Disjoint x y ↔ Disjoint x.1 y.1 ∧ Disjoint x.2 y.2 := by constructor · intro h refine ⟨fun a hx hy ↦ (@h (a, ⊥) ⟨hx, ?_⟩ ⟨hy, ?_⟩).1, fun b hx hy ↦ (@h (⊥, b) ⟨?_, hx⟩ ⟨?_, hy⟩).2⟩ all_goals exact bot_le · rintro ⟨ha, hb⟩ z hza hzb exact ⟨ha hza.1 hzb.1, hb hza.2 hzb.2⟩ protected theorem codisjoint_iff [OrderTop α] [OrderTop β] {x y : α × β} : Codisjoint x y ↔ Codisjoint x.1 y.1 ∧ Codisjoint x.2 y.2 := @Prod.disjoint_iff αᵒᵈ βᵒᵈ _ _ _ _ _ _ protected theorem isCompl_iff [BoundedOrder α] [BoundedOrder β] {x y : α × β} : IsCompl x y ↔ IsCompl x.1 y.1 ∧ IsCompl x.2 y.2 := by simp_rw [isCompl_iff, Prod.disjoint_iff, Prod.codisjoint_iff, and_and_and_comm] end Prod section variable [Lattice α] [BoundedOrder α] {a b x : α} @[simp] theorem isCompl_toDual_iff : IsCompl (toDual a) (toDual b) ↔ IsCompl a b := ⟨IsCompl.ofDual, IsCompl.dual⟩ @[simp] theorem isCompl_ofDual_iff {a b : αᵒᵈ} : IsCompl (ofDual a) (ofDual b) ↔ IsCompl a b := ⟨IsCompl.dual, IsCompl.ofDual⟩ theorem isCompl_bot_top : IsCompl (⊥ : α) ⊤ := IsCompl.of_eq (bot_inf_eq _) (sup_top_eq _) theorem isCompl_top_bot : IsCompl (⊤ : α) ⊥ := IsCompl.of_eq (inf_bot_eq _) (top_sup_eq _) theorem eq_top_of_isCompl_bot (h : IsCompl x ⊥) : x = ⊤ := by rw [← sup_bot_eq x, h.sup_eq_top] theorem eq_top_of_bot_isCompl (h : IsCompl ⊥ x) : x = ⊤ := eq_top_of_isCompl_bot h.symm theorem eq_bot_of_isCompl_top (h : IsCompl x ⊤) : x = ⊥ := eq_top_of_isCompl_bot h.dual theorem eq_bot_of_top_isCompl (h : IsCompl ⊤ x) : x = ⊥ := eq_top_of_bot_isCompl h.dual end section IsComplemented section Lattice variable [Lattice α] [BoundedOrder α] /-- An element is *complemented* if it has a complement. -/ def IsComplemented (a : α) : Prop := ∃ b, IsCompl a b theorem isComplemented_bot : IsComplemented (⊥ : α) := ⟨⊤, isCompl_bot_top⟩ theorem isComplemented_top : IsComplemented (⊤ : α) := ⟨⊥, isCompl_top_bot⟩ end Lattice variable [DistribLattice α] [BoundedOrder α] {a b : α} theorem IsComplemented.sup : IsComplemented a → IsComplemented b → IsComplemented (a ⊔ b) := fun ⟨a', ha⟩ ⟨b', hb⟩ => ⟨a' ⊓ b', ha.sup_inf hb⟩ theorem IsComplemented.inf : IsComplemented a → IsComplemented b → IsComplemented (a ⊓ b) := fun ⟨a', ha⟩ ⟨b', hb⟩ => ⟨a' ⊔ b', ha.inf_sup hb⟩ end IsComplemented /-- A complemented bounded lattice is one where every element has a (not necessarily unique) complement. -/ class ComplementedLattice (α) [Lattice α] [BoundedOrder α] : Prop where /-- In a `ComplementedLattice`, every element admits a complement. -/ exists_isCompl : ∀ a : α, ∃ b : α, IsCompl a b lemma complementedLattice_iff (α) [Lattice α] [BoundedOrder α] : ComplementedLattice α ↔ ∀ a : α, ∃ b : α, IsCompl a b := ⟨fun ⟨h⟩ ↦ h, fun h ↦ ⟨h⟩⟩ export ComplementedLattice (exists_isCompl) -- This was previously a global instance, -- but it doesn't appear to be used and has been implicated in slow typeclass resolutions. lemma Subsingleton.instComplementedLattice [Lattice α] [BoundedOrder α] [Subsingleton α] : ComplementedLattice α := by refine ⟨fun a ↦ ⟨⊥, disjoint_bot_right, ?_⟩⟩ rw [Subsingleton.elim ⊥ ⊤] exact codisjoint_top_right namespace ComplementedLattice variable [Lattice α] [BoundedOrder α] [ComplementedLattice α] instance : ComplementedLattice αᵒᵈ := ⟨fun a ↦ let ⟨b, hb⟩ := exists_isCompl (show α from a) ⟨b, hb.dual⟩⟩ end ComplementedLattice -- TODO: Define as a sublattice? /-- The sublattice of complemented elements. -/ abbrev Complementeds (α : Type*) [Lattice α] [BoundedOrder α] : Type _ := {a : α // IsComplemented a} namespace Complementeds section Lattice variable [Lattice α] [BoundedOrder α] {a b : Complementeds α} instance hasCoeT : CoeTC (Complementeds α) α := ⟨Subtype.val⟩ theorem coe_injective : Injective ((↑) : Complementeds α → α) := Subtype.coe_injective @[simp, norm_cast] theorem coe_inj : (a : α) = b ↔ a = b := Subtype.coe_inj @[norm_cast] theorem coe_le_coe : (a : α) ≤ b ↔ a ≤ b := by simp @[norm_cast] theorem coe_lt_coe : (a : α) < b ↔ a < b := by simp instance : BoundedOrder (Complementeds α) := Subtype.boundedOrder isComplemented_bot isComplemented_top @[simp, norm_cast] theorem coe_bot : ((⊥ : Complementeds α) : α) = ⊥ := rfl @[simp, norm_cast] theorem coe_top : ((⊤ : Complementeds α) : α) = ⊤ := rfl theorem mk_bot : (⟨⊥, isComplemented_bot⟩ : Complementeds α) = ⊥ := by simp theorem mk_top : (⟨⊤, isComplemented_top⟩ : Complementeds α) = ⊤ := by simp instance : Inhabited (Complementeds α) := ⟨⊥⟩ end Lattice variable [DistribLattice α] [BoundedOrder α] {a b : Complementeds α} instance : Max (Complementeds α) := ⟨fun a b => ⟨a ⊔ b, a.2.sup b.2⟩⟩ instance : Min (Complementeds α) := ⟨fun a b => ⟨a ⊓ b, a.2.inf b.2⟩⟩ @[simp, norm_cast] theorem coe_sup (a b : Complementeds α) : ↑(a ⊔ b) = (a : α) ⊔ b := rfl @[simp, norm_cast] theorem coe_inf (a b : Complementeds α) : ↑(a ⊓ b) = (a : α) ⊓ b := rfl @[simp] theorem mk_sup_mk {a b : α} (ha : IsComplemented a) (hb : IsComplemented b) : (⟨a, ha⟩ ⊔ ⟨b, hb⟩ : Complementeds α) = ⟨a ⊔ b, ha.sup hb⟩ := rfl @[simp] theorem mk_inf_mk {a b : α} (ha : IsComplemented a) (hb : IsComplemented b) : (⟨a, ha⟩ ⊓ ⟨b, hb⟩ : Complementeds α) = ⟨a ⊓ b, ha.inf hb⟩ := rfl instance : DistribLattice (Complementeds α) := Complementeds.coe_injective.distribLattice _ coe_sup coe_inf @[simp, norm_cast] theorem disjoint_coe : Disjoint (a : α) b ↔ Disjoint a b := by rw [disjoint_iff, disjoint_iff, ← coe_inf, ← coe_bot, coe_inj] @[simp, norm_cast] theorem codisjoint_coe : Codisjoint (a : α) b ↔ Codisjoint a b := by rw [codisjoint_iff, codisjoint_iff, ← coe_sup, ← coe_top, coe_inj] @[simp, norm_cast] theorem isCompl_coe : IsCompl (a : α) b ↔ IsCompl a b := by simp_rw [isCompl_iff, disjoint_coe, codisjoint_coe] instance : ComplementedLattice (Complementeds α) := ⟨fun ⟨a, b, h⟩ => ⟨⟨b, a, h.symm⟩, isCompl_coe.1 h⟩⟩ end Complementeds end IsCompl
.lake/packages/mathlib/Mathlib/Order/PartialSups.lean
import Mathlib.Data.Set.Finite.Lattice import Mathlib.Order.ConditionallyCompleteLattice.Indexed import Mathlib.Order.Interval.Finset.Nat import Mathlib.Order.SuccPred.Basic /-! # The monotone sequence of partial supremums of a sequence For `ι` a preorder in which all bounded-above intervals are finite (such as `ℕ`), and `α` a `⊔`-semilattice, we define `partialSups : (ι → α) → ι →o α` by the formula `partialSups f i = (Finset.Iic i).sup' ⋯ f`, where the `⋯` denotes a proof that `Finset.Iic i` is nonempty. This is a way of spelling `⊔ k ≤ i, f k` which does not require a `α` to have a bottom element, and makes sense in conditionally-complete lattices (where indexed suprema over sets are badly-behaved). Under stronger hypotheses on `α` and `ι`, we show that this coincides with other candidate definitions, see e.g. `partialSups_eq_biSup`, `partialSups_eq_sup_range`, and `partialSups_eq_sup'_range`. We show this construction gives a Galois insertion between functions `ι → α` and monotone functions `ι →o α`, see `partialSups.gi`. ## Notes One might dispute whether this sequence should start at `f 0` or `⊥`. We choose the former because: * Starting at `⊥` requires... having a bottom element. * `fun f i ↦ (Finset.Iio i).sup f` is already effectively the sequence starting at `⊥`. * If we started at `⊥` we wouldn't have the Galois insertion. See `partialSups.gi`. -/ open Finset variable {α β ι : Type*} section SemilatticeSup variable [SemilatticeSup α] [SemilatticeSup β] section Preorder variable [Preorder ι] [LocallyFiniteOrderBot ι] /-- The monotone sequence whose value at `i` is the supremum of the `f j` where `j ≤ i`. -/ def partialSups (f : ι → α) : ι →o α where toFun i := (Iic i).sup' nonempty_Iic f monotone' _ _ hmn := sup'_mono f (Iic_subset_Iic.mpr hmn) nonempty_Iic lemma partialSups_apply (f : ι → α) (i : ι) : partialSups f i = (Iic i).sup' nonempty_Iic f := rfl lemma partialSups_iff_forall {f : ι → α} (p : α → Prop) (hp : ∀ {a b}, p (a ⊔ b) ↔ p a ∧ p b) {i : ι} : p (partialSups f i) ↔ ∀ j ≤ i, p (f j) := by classical rw [partialSups_apply, comp_sup'_eq_sup'_comp (γ := Propᵒᵈ) _ p, sup'_eq_sup] · change (Iic i).inf (p ∘ f) ↔ _ simp [Finset.inf_eq_iInf] · intro x y rw [hp] rfl @[simp] lemma partialSups_le_iff {f : ι → α} {i : ι} {a : α} : partialSups f i ≤ a ↔ ∀ j ≤ i, f j ≤ a := partialSups_iff_forall (· ≤ a) sup_le_iff theorem le_partialSups_of_le (f : ι → α) {i j : ι} (h : i ≤ j) : f i ≤ partialSups f j := partialSups_le_iff.1 le_rfl i h theorem le_partialSups (f : ι → α) : f ≤ partialSups f := fun _ => le_partialSups_of_le f le_rfl theorem partialSups_le (f : ι → α) (i : ι) (a : α) (w : ∀ j ≤ i, f j ≤ a) : partialSups f i ≤ a := partialSups_le_iff.2 w @[simp] lemma upperBounds_range_partialSups (f : ι → α) : upperBounds (Set.range (partialSups f)) = upperBounds (Set.range f) := by ext a simp only [mem_upperBounds, Set.forall_mem_range, partialSups_le_iff] exact ⟨fun h _ ↦ h _ _ le_rfl, fun h _ _ _ ↦ h _⟩ @[simp] theorem bddAbove_range_partialSups {f : ι → α} : BddAbove (Set.range (partialSups f)) ↔ BddAbove (Set.range f) := .of_eq <| congr_arg Set.Nonempty <| upperBounds_range_partialSups f theorem Monotone.partialSups_eq {f : ι → α} (hf : Monotone f) : partialSups f = f := funext fun i ↦ le_antisymm (partialSups_le _ _ _ (@hf · i)) (le_partialSups _ _) theorem partialSups_mono : Monotone (partialSups : (ι → α) → ι →o α) := fun _ _ h _ ↦ partialSups_le_iff.2 fun j hj ↦ (h j).trans (le_partialSups_of_le _ hj) lemma partialSups_monotone (f : ι → α) : Monotone (partialSups f) := fun i _ hnm ↦ partialSups_le f i _ (fun _ hm'n ↦ le_partialSups_of_le _ (hm'n.trans hnm)) /-- `partialSups` forms a Galois insertion with the coercion from monotone functions to functions. -/ def partialSups.gi : GaloisInsertion (partialSups : (ι → α) → ι →o α) (↑) where choice f h := ⟨f, by convert (partialSups f).monotone using 1; exact (le_partialSups f).antisymm h⟩ gc f g := by refine ⟨(le_partialSups f).trans, fun h ↦ ?_⟩ convert partialSups_mono h exact OrderHom.ext _ _ g.monotone.partialSups_eq.symm le_l_u f := le_partialSups f choice_eq f h := OrderHom.ext _ _ ((le_partialSups f).antisymm h) protected lemma Pi.partialSups_apply {τ : Type*} {π : τ → Type*} [∀ t, SemilatticeSup (π t)] (f : ι → (t : τ) → π t) (i : ι) (t : τ) : partialSups f i t = partialSups (f · t) i := by simp only [partialSups_apply, Finset.sup'_apply] lemma comp_partialSups {F : Type*} [FunLike F α β] [SupHomClass F α β] (f : ι → α) (g : F) : partialSups (g ∘ f) = g ∘ partialSups f := by funext _; simp [partialSups] lemma map_partialSups {F : Type*} [FunLike F α β] [SupHomClass F α β] (f : F) (g : ι → α) (i : ι) : partialSups (fun j ↦ f (g j)) i = f (partialSups g i) := congr($(comp_partialSups ..) i) end Preorder @[simp] theorem partialSups_succ [LinearOrder ι] [LocallyFiniteOrderBot ι] [SuccOrder ι] (f : ι → α) (i : ι) : partialSups f (Order.succ i) = partialSups f i ⊔ f (Order.succ i) := by suffices Iic (Order.succ i) = Iic i ∪ {Order.succ i} by simp only [partialSups_apply, this, sup'_union nonempty_Iic ⟨_, mem_singleton_self _⟩ f, sup'_singleton] ext simp only [mem_Iic, mem_union, mem_singleton] constructor · exact fun h ↦ (Order.le_succ_iff_eq_or_le.mp h).symm · exact fun h ↦ h.elim (le_trans · <| Order.le_succ _) le_of_eq @[simp] theorem partialSups_bot [PartialOrder ι] [LocallyFiniteOrder ι] [OrderBot ι] (f : ι → α) : partialSups f ⊥ = f ⊥ := by simp only [partialSups_apply] -- should we add a lemma `Finset.Iic_bot`? suffices Iic (⊥ : ι) = {⊥} by simp only [this, sup'_singleton] simp only [← coe_eq_singleton, coe_Iic, Set.Iic_bot] /-! ### Functions out of `ℕ` -/ @[simp] theorem partialSups_zero (f : ℕ → α) : partialSups f 0 = f 0 := partialSups_bot f theorem partialSups_eq_sup'_range (f : ℕ → α) (n : ℕ) : partialSups f n = (Finset.range (n + 1)).sup' nonempty_range_add_one f := eq_of_forall_ge_iff fun _ ↦ by simp [Nat.lt_succ_iff] theorem partialSups_eq_sup_range [OrderBot α] (f : ℕ → α) (n : ℕ) : partialSups f n = (Finset.range (n + 1)).sup f := eq_of_forall_ge_iff fun _ ↦ by simp [Nat.lt_succ_iff] end SemilatticeSup section DistribLattice /-! ### Functions valued in a distributive lattice These lemmas require the target to be a distributive lattice, so they are not useful (or true) in situations such as submodules. -/ variable [Preorder ι] [LocallyFiniteOrderBot ι] [DistribLattice α] [OrderBot α] @[simp] lemma disjoint_partialSups_left {f : ι → α} {i : ι} {x : α} : Disjoint (partialSups f i) x ↔ ∀ j ≤ i, Disjoint (f j) x := partialSups_iff_forall (Disjoint · x) disjoint_sup_left @[simp] lemma disjoint_partialSups_right {f : ι → α} {i : ι} {x : α} : Disjoint x (partialSups f i) ↔ ∀ j ≤ i, Disjoint x (f j) := partialSups_iff_forall (Disjoint x) disjoint_sup_right open scoped Function in -- required for scoped `on` notation /- Note this lemma requires a distributive lattice, so is not useful (or true) in situations such as submodules. -/ theorem partialSups_disjoint_of_disjoint (f : ι → α) (h : Pairwise (Disjoint on f)) {i j : ι} (hij : i < j) : Disjoint (partialSups f i) (f j) := disjoint_partialSups_left.2 fun _ hk ↦ h (hk.trans_lt hij).ne end DistribLattice section ConditionallyCompleteLattice /-! ### Lemmas about the supremum over the whole domain These lemmas require some completeness assumptions on the target space. -/ variable [Preorder ι] [LocallyFiniteOrderBot ι] theorem partialSups_eq_ciSup_Iic [ConditionallyCompleteLattice α] (f : ι → α) (i : ι) : partialSups f i = ⨆ i : Set.Iic i, f i := by simp only [partialSups_apply] apply le_antisymm · exact sup'_le _ _ fun j hj ↦ le_ciSup_of_le (Set.finite_range _).bddAbove ⟨j, by simpa only [Set.mem_Iic, mem_Iic] using hj⟩ le_rfl · exact ciSup_le fun ⟨j, hj⟩ ↦ le_sup' f (by simpa only [mem_Iic, Set.mem_Iic] using hj) @[simp] theorem ciSup_partialSups_eq [ConditionallyCompleteLattice α] {f : ι → α} (h : BddAbove (Set.range f)) : ⨆ i, partialSups f i = ⨆ i, f i := by by_cases hι : Nonempty ι · refine (ciSup_le fun i ↦ ?_).antisymm (ciSup_mono ?_ <| le_partialSups f) · simpa only [partialSups_eq_ciSup_Iic] using ciSup_le fun i ↦ le_ciSup h _ · rwa [bddAbove_range_partialSups] · exact congr_arg _ (funext (not_nonempty_iff.mp hι).elim) /-- Version of `ciSup_partialSups_eq` without boundedness assumptions, but requiring a `ConditionallyCompleteLinearOrder` rather than just a `ConditionallyCompleteLattice`. -/ @[simp] theorem ciSup_partialSups_eq' [ConditionallyCompleteLinearOrder α] (f : ι → α) : ⨆ i, partialSups f i = ⨆ i, f i := by by_cases h : BddAbove (Set.range f) · exact ciSup_partialSups_eq h · rw [iSup, iSup, ConditionallyCompleteLinearOrder.csSup_of_not_bddAbove _ h, ConditionallyCompleteLinearOrder.csSup_of_not_bddAbove _ (bddAbove_range_partialSups.not.mpr h)] end ConditionallyCompleteLattice section CompleteLattice variable [Preorder ι] [LocallyFiniteOrderBot ι] [CompleteLattice α] /-- Version of `ciSup_partialSups_eq` without boundedness assumptions, but requiring a `CompleteLattice` rather than just a `ConditionallyCompleteLattice`. -/ theorem iSup_partialSups_eq (f : ι → α) : ⨆ i, partialSups f i = ⨆ i, f i := ciSup_partialSups_eq <| OrderTop.bddAbove _ theorem partialSups_eq_biSup (f : ι → α) (i : ι) : partialSups f i = ⨆ j ≤ i, f j := by simpa only [iSup_subtype] using partialSups_eq_ciSup_Iic f i theorem iSup_le_iSup_of_partialSups_le_partialSups {f g : ι → α} (h : partialSups f ≤ partialSups g) : ⨆ i, f i ≤ ⨆ i, g i := by rw [← iSup_partialSups_eq f, ← iSup_partialSups_eq g] exact iSup_mono h theorem iSup_eq_iSup_of_partialSups_eq_partialSups {f g : ι → α} (h : partialSups f = partialSups g) : ⨆ i, f i = ⨆ i, g i := by simp_rw [← iSup_partialSups_eq f, ← iSup_partialSups_eq g, h] end CompleteLattice section Set /-! ### Functions into `Set α` -/ lemma partialSups_eq_sUnion_image [DecidableEq (Set α)] (s : ℕ → Set α) (n : ℕ) : partialSups s n = ⋃₀ ↑((Finset.range (n + 1)).image s) := by simp [partialSups_eq_biSup, Nat.lt_succ_iff] lemma partialSups_eq_biUnion_range (s : ℕ → Set α) (n : ℕ) : partialSups s n = ⋃ i ∈ Finset.range (n + 1), s i := by simp [partialSups_eq_biSup, Nat.lt_succ] end Set
.lake/packages/mathlib/Mathlib/Order/ULift.lean
import Mathlib.Logic.Function.ULift import Mathlib.Order.Basic /-! # Ordered structures on `ULift.{v} α` Once these basic instances are setup, the instances of more complex typeclasses should live next to the corresponding `Prod` instances. -/ namespace ULift open Batteries universe v u variable {α : Type u} instance [LE α] : LE (ULift.{v} α) where le x y := x.down ≤ y.down @[simp] theorem up_le [LE α] {a b : α} : up a ≤ up b ↔ a ≤ b := Iff.rfl @[simp] theorem down_le [LE α] {a b : ULift α} : down a ≤ down b ↔ a ≤ b := Iff.rfl instance [LT α] : LT (ULift.{v} α) where lt x y := x.down < y.down @[simp] theorem up_lt [LT α] {a b : α} : up a < up b ↔ a < b := Iff.rfl @[simp] theorem down_lt [LT α] {a b : ULift α} : down a < down b ↔ a < b := Iff.rfl instance [BEq α] : BEq (ULift.{v} α) where beq x y := x.down == y.down @[simp] theorem up_beq [BEq α] (a b : α) : (up a == up b) = (a == b) := rfl @[simp] theorem down_beq [BEq α] (a b : ULift α) : (down a == down b) = (a == b) := rfl instance [Ord α] : Ord (ULift.{v} α) where compare x y := compare x.down y.down @[simp] theorem up_compare [Ord α] (a b : α) : compare (up a) (up b) = compare a b := rfl @[simp] theorem down_compare [Ord α] (a b : ULift α) : compare (down a) (down b) = compare a b := rfl instance [Max α] : Max (ULift.{v} α) where max x y := up <| x.down ⊔ y.down @[simp] theorem up_sup [Max α] (a b : α) : up (a ⊔ b) = up a ⊔ up b := rfl @[simp] theorem down_sup [Max α] (a b : ULift α) : down (a ⊔ b) = down a ⊔ down b := rfl instance [Min α] : Min (ULift.{v} α) where min x y := up <| x.down ⊓ y.down @[simp] theorem up_inf [Min α] (a b : α) : up (a ⊓ b) = up a ⊓ up b := rfl @[simp] theorem down_inf [Min α] (a b : ULift α) : down (a ⊓ b) = down a ⊓ down b := rfl instance [SDiff α] : SDiff (ULift.{v} α) where sdiff x y := up <| x.down \ y.down @[simp] theorem up_sdiff [SDiff α] (a b : α) : up (a \ b) = up a \ up b := rfl @[simp] theorem down_sdiff [SDiff α] (a b : ULift α) : down (a \ b) = down a \ down b := rfl instance [HasCompl α] : HasCompl (ULift.{v} α) where compl x := up <| x.downᶜ @[simp] theorem up_compl [HasCompl α] (a : α) : up (aᶜ) = (up a)ᶜ := rfl @[simp] theorem down_compl [HasCompl α] (a : ULift α) : down aᶜ = (down a)ᶜ := rfl instance [Ord α] [inst : Std.OrientedOrd α] : Std.OrientedOrd (ULift.{v} α) where eq_swap := inst.eq_swap instance [Ord α] [inst : Std.TransOrd α] : Std.TransOrd (ULift.{v} α) where isLE_trans := inst.isLE_trans instance [BEq α] [Ord α] [inst : Std.LawfulBEqOrd α] : Std.LawfulBEqOrd (ULift.{v} α) where compare_eq_iff_beq := inst.compare_eq_iff_beq instance [LT α] [Ord α] [inst : Std.LawfulLTOrd α] : Std.LawfulLTOrd (ULift.{v} α) where eq_lt_iff_lt := inst.eq_lt_iff_lt instance [LE α] [Ord α] [inst : Std.LawfulLEOrd α] : Std.LawfulLEOrd (ULift.{v} α) where isLE_iff_le := inst.isLE_iff_le instance [LE α] [LT α] [BEq α] [Ord α] [inst : Std.LawfulBOrd α] : Std.LawfulBOrd (ULift.{v} α) where eq_lt_iff_lt := inst.eq_lt_iff_lt isLE_iff_le := inst.isLE_iff_le instance [Preorder α] : Preorder (ULift.{v} α) := Preorder.lift ULift.down instance [PartialOrder α] : PartialOrder (ULift.{v} α) := PartialOrder.lift ULift.down ULift.down_injective end ULift
.lake/packages/mathlib/Mathlib/Order/Compare.lean
import Mathlib.Data.Ordering.Basic import Mathlib.Order.Synonym /-! # Comparison This file provides basic results about orderings and comparison in linear orders. ## Definitions * `CmpLE`: An `Ordering` from `≤`. * `Ordering.Compares`: Turns an `Ordering` into `<` and `=` propositions. * `linearOrderOfCompares`: Constructs a `LinearOrder` instance from the fact that any two elements that are not one strictly less than the other either way are equal. -/ variable {α β : Type*} /-- Like `cmp`, but uses a `≤` on the type instead of `<`. Given two elements `x` and `y`, returns a three-way comparison result `Ordering`. -/ def cmpLE {α} [LE α] [DecidableLE α] (x y : α) : Ordering := if x ≤ y then if y ≤ x then Ordering.eq else Ordering.lt else Ordering.gt theorem cmpLE_swap {α} [LE α] [IsTotal α (· ≤ ·)] [DecidableLE α] (x y : α) : (cmpLE x y).swap = cmpLE y x := by by_cases xy : x ≤ y <;> by_cases yx : y ≤ x <;> simp [cmpLE, *, Ordering.swap] cases not_or_intro xy yx (total_of _ _ _) theorem cmpLE_eq_cmp {α} [Preorder α] [IsTotal α (· ≤ ·)] [DecidableLE α] [DecidableLT α] (x y : α) : cmpLE x y = cmp x y := by by_cases xy : x ≤ y <;> by_cases yx : y ≤ x <;> simp [cmpLE, lt_iff_le_not_ge, *, cmp, cmpUsing] cases not_or_intro xy yx (total_of _ _ _) namespace Ordering theorem compares_swap [LT α] {a b : α} {o : Ordering} : o.swap.Compares a b ↔ o.Compares b a := by cases o · exact Iff.rfl · exact eq_comm · exact Iff.rfl alias ⟨Compares.of_swap, Compares.swap⟩ := compares_swap theorem swap_eq_iff_eq_swap {o o' : Ordering} : o.swap = o' ↔ o = o'.swap := by rw [← swap_inj, swap_swap] theorem Compares.eq_lt [Preorder α] : ∀ {o} {a b : α}, Compares o a b → (o = lt ↔ a < b) | lt, _, _, h => ⟨fun _ => h, fun _ => rfl⟩ | eq, a, b, h => ⟨fun h => by injection h, fun h' => (ne_of_lt h' h).elim⟩ | gt, a, b, h => ⟨fun h => by injection h, fun h' => (lt_asymm h h').elim⟩ theorem Compares.ne_lt [Preorder α] : ∀ {o} {a b : α}, Compares o a b → (o ≠ lt ↔ b ≤ a) | lt, _, _, h => ⟨absurd rfl, fun h' => (not_le_of_gt h h').elim⟩ | eq, _, _, h => ⟨fun _ => ge_of_eq h, fun _ h => by injection h⟩ | gt, _, _, h => ⟨fun _ => le_of_lt h, fun _ h => by injection h⟩ theorem Compares.eq_eq [Preorder α] : ∀ {o} {a b : α}, Compares o a b → (o = eq ↔ a = b) | lt, a, b, h => ⟨fun h => by injection h, fun h' => (ne_of_lt h h').elim⟩ | eq, _, _, h => ⟨fun _ => h, fun _ => rfl⟩ | gt, a, b, h => ⟨fun h => by injection h, fun h' => (ne_of_gt h h').elim⟩ theorem Compares.eq_gt [Preorder α] {o} {a b : α} (h : Compares o a b) : o = gt ↔ b < a := swap_eq_iff_eq_swap.symm.trans h.swap.eq_lt theorem Compares.ne_gt [Preorder α] {o} {a b : α} (h : Compares o a b) : o ≠ gt ↔ a ≤ b := (not_congr swap_eq_iff_eq_swap.symm).trans h.swap.ne_lt theorem Compares.le_total [Preorder α] {a b : α} : ∀ {o}, Compares o a b → a ≤ b ∨ b ≤ a | lt, h => Or.inl (le_of_lt h) | eq, h => Or.inl (le_of_eq h) | gt, h => Or.inr (le_of_lt h) theorem Compares.le_antisymm [Preorder α] {a b : α} : ∀ {o}, Compares o a b → a ≤ b → b ≤ a → a = b | lt, h, _, hba => (not_le_of_gt h hba).elim | eq, h, _, _ => h | gt, h, hab, _ => (not_le_of_gt h hab).elim theorem Compares.inj [Preorder α] {o₁} : ∀ {o₂} {a b : α}, Compares o₁ a b → Compares o₂ a b → o₁ = o₂ | lt, _, _, h₁, h₂ => h₁.eq_lt.2 h₂ | eq, _, _, h₁, h₂ => h₁.eq_eq.2 h₂ | gt, _, _, h₁, h₂ => h₁.eq_gt.2 h₂ theorem compares_iff_of_compares_impl [LinearOrder α] [Preorder β] {a b : α} {a' b' : β} (h : ∀ {o}, Compares o a b → Compares o a' b') (o) : Compares o a b ↔ Compares o a' b' := by refine ⟨h, fun ho => ?_⟩ rcases lt_trichotomy a b with hab | hab | hab · have hab : Compares Ordering.lt a b := hab rwa [ho.inj (h hab)] · have hab : Compares Ordering.eq a b := hab rwa [ho.inj (h hab)] · have hab : Compares Ordering.gt a b := hab rwa [ho.inj (h hab)] end Ordering open Ordering OrderDual @[simp] theorem toDual_compares_toDual [LT α] {a b : α} {o : Ordering} : Compares o (toDual a) (toDual b) ↔ Compares o b a := by cases o exacts [Iff.rfl, eq_comm, Iff.rfl] @[simp] theorem ofDual_compares_ofDual [LT α] {a b : αᵒᵈ} {o : Ordering} : Compares o (ofDual a) (ofDual b) ↔ Compares o b a := by cases o exacts [Iff.rfl, eq_comm, Iff.rfl] theorem cmp_compares [LinearOrder α] (a b : α) : (cmp a b).Compares a b := by obtain h | h | h := lt_trichotomy a b <;> simp [cmp, cmpUsing, h, h.not_gt] theorem Ordering.Compares.cmp_eq [LinearOrder α] {a b : α} {o : Ordering} (h : o.Compares a b) : cmp a b = o := (cmp_compares a b).inj h @[simp] theorem cmp_swap [Preorder α] [DecidableLT α] (a b : α) : (cmp a b).swap = cmp b a := by unfold cmp cmpUsing by_cases h : a < b <;> by_cases h₂ : b < a <;> simp [h, h₂, Ordering.swap] exact lt_asymm h h₂ @[simp] theorem cmpLE_toDual [LE α] [DecidableLE α] (x y : α) : cmpLE (toDual x) (toDual y) = cmpLE y x := rfl @[simp] theorem cmpLE_ofDual [LE α] [DecidableLE α] (x y : αᵒᵈ) : cmpLE (ofDual x) (ofDual y) = cmpLE y x := rfl @[simp] theorem cmp_toDual [LT α] [DecidableLT α] (x y : α) : cmp (toDual x) (toDual y) = cmp y x := rfl @[simp] theorem cmp_ofDual [LT α] [DecidableLT α] (x y : αᵒᵈ) : cmp (ofDual x) (ofDual y) = cmp y x := rfl /-- Generate a linear order structure from a preorder and `cmp` function. -/ def linearOrderOfCompares [Preorder α] (cmp : α → α → Ordering) (h : ∀ a b, (cmp a b).Compares a b) : LinearOrder α := let H : DecidableLE α := fun a b => decidable_of_iff _ (h a b).ne_gt { inferInstanceAs (Preorder α) with le_antisymm := fun a b => (h a b).le_antisymm, le_total := fun a b => (h a b).le_total, toMin := minOfLe, toMax := maxOfLe, toDecidableLE := H, toDecidableLT := fun a b => decidable_of_iff _ (h a b).eq_lt, toDecidableEq := fun a b => decidable_of_iff _ (h a b).eq_eq } variable [LinearOrder α] (x y : α) @[simp] theorem cmp_eq_lt_iff : cmp x y = Ordering.lt ↔ x < y := Ordering.Compares.eq_lt (cmp_compares x y) @[simp] theorem cmp_eq_eq_iff : cmp x y = Ordering.eq ↔ x = y := Ordering.Compares.eq_eq (cmp_compares x y) @[simp] theorem cmp_eq_gt_iff : cmp x y = Ordering.gt ↔ y < x := Ordering.Compares.eq_gt (cmp_compares x y) @[simp] theorem cmp_self_eq_eq : cmp x x = Ordering.eq := by rw [cmp_eq_eq_iff] variable {x y} {β : Type*} [LinearOrder β] {x' y' : β} theorem cmp_eq_cmp_symm : cmp x y = cmp x' y' ↔ cmp y x = cmp y' x' := ⟨fun h => by rwa [← cmp_swap x', ← cmp_swap, swap_inj], fun h => by rwa [← cmp_swap y', ← cmp_swap, swap_inj]⟩ theorem lt_iff_lt_of_cmp_eq_cmp (h : cmp x y = cmp x' y') : x < y ↔ x' < y' := by rw [← cmp_eq_lt_iff, ← cmp_eq_lt_iff, h] theorem le_iff_le_of_cmp_eq_cmp (h : cmp x y = cmp x' y') : x ≤ y ↔ x' ≤ y' := by rw [← not_lt, ← not_lt] apply not_congr apply lt_iff_lt_of_cmp_eq_cmp rwa [cmp_eq_cmp_symm] theorem eq_iff_eq_of_cmp_eq_cmp (h : cmp x y = cmp x' y') : x = y ↔ x' = y' := by rw [le_antisymm_iff, le_antisymm_iff, le_iff_le_of_cmp_eq_cmp h, le_iff_le_of_cmp_eq_cmp (cmp_eq_cmp_symm.1 h)] theorem LT.lt.cmp_eq_lt (h : x < y) : cmp x y = Ordering.lt := (cmp_eq_lt_iff _ _).2 h theorem LT.lt.cmp_eq_gt (h : x < y) : cmp y x = Ordering.gt := (cmp_eq_gt_iff _ _).2 h theorem Eq.cmp_eq_eq (h : x = y) : cmp x y = Ordering.eq := (cmp_eq_eq_iff _ _).2 h theorem Eq.cmp_eq_eq' (h : x = y) : cmp y x = Ordering.eq := h.symm.cmp_eq_eq
.lake/packages/mathlib/Mathlib/Order/Ideal.lean
import Mathlib.Data.Finset.Lattice.Fold import Mathlib.Logic.Encodable.Basic import Mathlib.Order.Atoms import Mathlib.Order.Cofinal import Mathlib.Order.UpperLower.Principal /-! # 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. - `Order.Ideal P`: the type of nonempty, upward directed, and downward closed subsets of `P`. Dual to the notion of a filter on a preorder. - `Order.IsIdeal I`: a predicate for when a `Set P` is an ideal. - `Order.Ideal.principal p`: the principal ideal generated by `p : P`. - `Order.Ideal.IsProper I`: a predicate for proper ideals. Dual to the notion of a proper filter. - `Order.Ideal.IsMaximal I`: a predicate for maximal ideals. Dual to the notion of an ultrafilter. - `Order.Cofinal P`: the type of subsets of `P` containing arbitrarily large elements. Dual to the notion of 'dense set' used in forcing. - `Order.idealOfCofinals 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 `𝒟`. (This a form of the Rasiowa–Sikorski lemma.) ## References - <https://en.wikipedia.org/wiki/Ideal_(order_theory)> - <https://en.wikipedia.org/wiki/Cofinal_(mathematics)> - <https://en.wikipedia.org/wiki/Rasiowa%E2%80%93Sikorski_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 -/ open Function Set namespace Order variable {P : Type*} /-- An ideal on an order `P` is a subset of `P` that is - nonempty - upward directed (any pair of elements in the ideal has an upper bound in the ideal) - downward closed (any element less than an element of the ideal is in the ideal). -/ structure Ideal (P) [LE P] extends LowerSet P where /-- The ideal is nonempty. -/ nonempty' : carrier.Nonempty /-- The ideal is upward directed. -/ directed' : DirectedOn (· ≤ ·) carrier -- TODO: remove this configuration and use the default configuration. -- We keep this to be consistent with Lean 3. initialize_simps_projections Ideal (+toLowerSet, -carrier) /-- A subset of a preorder `P` is an ideal if it is - nonempty - upward directed (any pair of elements in the ideal has an upper bound in the ideal) - downward closed (any element less than an element of the ideal is in the ideal). -/ @[mk_iff] structure IsIdeal {P} [LE P] (I : Set P) : Prop where /-- The ideal is downward closed. -/ IsLowerSet : IsLowerSet I /-- The ideal is nonempty. -/ Nonempty : I.Nonempty /-- The ideal is upward directed. -/ Directed : DirectedOn (· ≤ ·) I /-- Create an element of type `Order.Ideal` from a set satisfying the predicate `Order.IsIdeal`. -/ def IsIdeal.toIdeal [LE P] {I : Set P} (h : IsIdeal I) : Ideal P := ⟨⟨I, h.IsLowerSet⟩, h.Nonempty, h.Directed⟩ namespace Ideal section LE variable [LE P] section variable {I s t : Ideal P} {x : P} theorem toLowerSet_injective : Injective (toLowerSet : Ideal P → LowerSet P) := fun s t _ ↦ by cases s cases t congr instance : SetLike (Ideal P) P where coe s := s.carrier coe_injective' _ _ h := toLowerSet_injective <| SetLike.coe_injective h @[ext] theorem ext {s t : Ideal P} : (s : Set P) = t → s = t := SetLike.ext' @[simp] theorem carrier_eq_coe (s : Ideal P) : s.carrier = s := rfl @[simp] theorem coe_toLowerSet (s : Ideal P) : (s.toLowerSet : Set P) = s := rfl protected theorem lower (s : Ideal P) : IsLowerSet (s : Set P) := s.lower' protected theorem nonempty (s : Ideal P) : (s : Set P).Nonempty := s.nonempty' protected theorem directed (s : Ideal P) : DirectedOn (· ≤ ·) (s : Set P) := s.directed' protected theorem isIdeal (s : Ideal P) : IsIdeal (s : Set P) := ⟨s.lower, s.nonempty, s.directed⟩ theorem mem_compl_of_ge {x y : P} : x ≤ y → x ∈ (I : Set P)ᶜ → y ∈ (I : Set P)ᶜ := fun h ↦ mt <| I.lower h /-- The partial ordering by subset inclusion, inherited from `Set P`. -/ instance instPartialOrderIdeal : PartialOrder (Ideal P) := PartialOrder.lift SetLike.coe SetLike.coe_injective theorem coe_subset_coe : (s : Set P) ⊆ t ↔ s ≤ t := Iff.rfl theorem coe_ssubset_coe : (s : Set P) ⊂ t ↔ s < t := Iff.rfl @[trans] theorem mem_of_mem_of_le {x : P} {I J : Ideal P} : x ∈ I → I ≤ J → x ∈ J := @Set.mem_of_mem_of_subset P x I J /-- A proper ideal is one that is not the whole set. Note that the whole set might not be an ideal. -/ @[mk_iff] class IsProper (I : Ideal P) : Prop where /-- This ideal is not the whole set. -/ ne_univ : (I : Set P) ≠ univ theorem isProper_of_notMem {I : Ideal P} {p : P} (notMem : p ∉ I) : IsProper I := ⟨fun hp ↦ by have := mem_univ p rw [← hp] at this exact notMem this⟩ @[deprecated (since := "2025-05-23")] alias isProper_of_not_mem := isProper_of_notMem /-- An ideal is maximal if it is maximal in the collection of proper ideals. Note that `IsCoatom` is less general because ideals only have a top element when `P` is directed and nonempty. -/ @[mk_iff] class IsMaximal (I : Ideal P) : Prop extends IsProper I where /-- This ideal is maximal in the collection of proper ideals. -/ maximal_proper : ∀ ⦃J : Ideal P⦄, I < J → (J : Set P) = univ theorem inter_nonempty [IsDirected P (· ≥ ·)] (I J : Ideal P) : (I ∩ J : Set P).Nonempty := by obtain ⟨a, ha⟩ := I.nonempty obtain ⟨b, hb⟩ := J.nonempty obtain ⟨c, hac, hbc⟩ := exists_le_le a b exact ⟨c, I.lower hac ha, J.lower hbc hb⟩ end section Directed variable [IsDirected P (· ≤ ·)] [Nonempty P] {I : Ideal P} /-- In a directed and nonempty order, the top ideal of a is `univ`. -/ instance : OrderTop (Ideal P) where top := ⟨⊤, univ_nonempty, directedOn_univ⟩ le_top _ _ _ := LowerSet.mem_top @[simp] theorem top_toLowerSet : (⊤ : Ideal P).toLowerSet = ⊤ := rfl @[simp] theorem coe_top : ((⊤ : Ideal P) : Set P) = univ := rfl theorem isProper_of_ne_top (ne_top : I ≠ ⊤) : IsProper I := ⟨fun h ↦ ne_top <| ext h⟩ theorem IsProper.ne_top (_ : IsProper I) : I ≠ ⊤ := fun h ↦ IsProper.ne_univ <| congr_arg SetLike.coe h theorem _root_.IsCoatom.isProper (hI : IsCoatom I) : IsProper I := isProper_of_ne_top hI.1 theorem isProper_iff_ne_top : IsProper I ↔ I ≠ ⊤ := ⟨fun h ↦ h.ne_top, fun h ↦ isProper_of_ne_top h⟩ theorem IsMaximal.isCoatom (_ : IsMaximal I) : IsCoatom I := ⟨IsMaximal.toIsProper.ne_top, fun _ h ↦ ext <| IsMaximal.maximal_proper h⟩ theorem IsMaximal.isCoatom' [IsMaximal I] : IsCoatom I := IsMaximal.isCoatom ‹_› theorem _root_.IsCoatom.isMaximal (hI : IsCoatom I) : IsMaximal I := { IsCoatom.isProper hI with maximal_proper := fun _ hJ ↦ by simp [hI.2 _ hJ] } theorem isMaximal_iff_isCoatom : IsMaximal I ↔ IsCoatom I := ⟨fun h ↦ h.isCoatom, fun h ↦ IsCoatom.isMaximal h⟩ end Directed section OrderBot variable [OrderBot P] @[simp] theorem bot_mem (s : Ideal P) : ⊥ ∈ s := s.lower bot_le s.nonempty'.some_mem end OrderBot section OrderTop variable [OrderTop P] {I : Ideal P} theorem top_of_top_mem (h : ⊤ ∈ I) : I = ⊤ := by ext exact iff_of_true (I.lower le_top h) trivial theorem IsProper.top_notMem (hI : IsProper I) : ⊤ ∉ I := fun h ↦ hI.ne_top <| top_of_top_mem h @[deprecated (since := "2025-05-23")] alias IsProper.top_not_mem := IsProper.top_notMem end OrderTop end LE section Preorder variable [Preorder P] section variable {I : Ideal P} {x y : P} /-- The smallest ideal containing a given element. -/ @[simps] def principal (p : P) : Ideal P where toLowerSet := LowerSet.Iic p nonempty' := nonempty_Iic directed' _ hx _ hy := ⟨p, le_rfl, hx, hy⟩ instance [Inhabited P] : Inhabited (Ideal P) := ⟨Ideal.principal default⟩ @[simp] theorem principal_le_iff : principal x ≤ I ↔ x ∈ I := ⟨fun h ↦ h le_rfl, fun hx _ hy ↦ I.lower hy hx⟩ @[simp] theorem mem_principal : x ∈ principal y ↔ x ≤ y := Iff.rfl lemma mem_principal_self : x ∈ principal x := mem_principal.2 (le_refl x) end section OrderBot variable [OrderBot P] /-- There is a bottom ideal when `P` has a bottom element. -/ instance : OrderBot (Ideal P) where bot := principal ⊥ bot_le := by simp @[simp] theorem principal_bot : principal (⊥ : P) = ⊥ := rfl end OrderBot section OrderTop variable [OrderTop P] @[simp] theorem principal_top : principal (⊤ : P) = ⊤ := toLowerSet_injective <| LowerSet.Iic_top end OrderTop end Preorder section SemilatticeSup variable [SemilatticeSup P] {x y : P} {I s : Ideal P} /-- A specific witness of `I.directed` when `P` has joins. -/ theorem sup_mem (hx : x ∈ s) (hy : y ∈ s) : x ⊔ y ∈ s := let ⟨_, hz, hx, hy⟩ := s.directed x hx y hy s.lower (sup_le hx hy) hz @[simp] theorem sup_mem_iff : x ⊔ y ∈ I ↔ x ∈ I ∧ y ∈ I := ⟨fun h ↦ ⟨I.lower le_sup_left h, I.lower le_sup_right h⟩, fun h ↦ sup_mem h.1 h.2⟩ @[simp] lemma finsetSup_mem_iff {P : Type*} [SemilatticeSup P] [OrderBot P] (t : Ideal P) {ι : Type*} {f : ι → P} {s : Finset ι} : s.sup f ∈ t ↔ ∀ i ∈ s, f i ∈ t := by classical induction s using Finset.induction_on <;> simp [*] end SemilatticeSup section SemilatticeSupDirected variable [SemilatticeSup P] [IsDirected P (· ≥ ·)] {x : P} {I J s t : Ideal P} /-- The infimum of two ideals of a co-directed order is their intersection. -/ instance : Min (Ideal P) := ⟨fun I J ↦ { toLowerSet := I.toLowerSet ⊓ J.toLowerSet nonempty' := inter_nonempty I J directed' := fun x hx y hy ↦ ⟨x ⊔ y, ⟨sup_mem hx.1 hy.1, sup_mem hx.2 hy.2⟩, by simp⟩ }⟩ /-- The supremum of two ideals of a co-directed order is the union of the down sets of the pointwise supremum of `I` and `J`. -/ instance : Max (Ideal P) := ⟨fun I J ↦ { carrier := { x | ∃ i ∈ I, ∃ j ∈ J, x ≤ i ⊔ j } nonempty' := by obtain ⟨w, h⟩ := inter_nonempty I J exact ⟨w, w, h.1, w, h.2, le_sup_left⟩ directed' := fun x ⟨xi, _, xj, _, _⟩ y ⟨yi, _, yj, _, _⟩ ↦ ⟨x ⊔ y, ⟨xi ⊔ yi, sup_mem ‹_› ‹_›, xj ⊔ yj, sup_mem ‹_› ‹_›, sup_le (calc x ≤ xi ⊔ xj := ‹_› _ ≤ xi ⊔ yi ⊔ (xj ⊔ yj) := sup_le_sup le_sup_left le_sup_left) (calc y ≤ yi ⊔ yj := ‹_› _ ≤ xi ⊔ yi ⊔ (xj ⊔ yj) := sup_le_sup le_sup_right le_sup_right)⟩, le_sup_left, le_sup_right⟩ lower' := fun _ _ h ⟨yi, hi, yj, hj, hxy⟩ ↦ ⟨yi, hi, yj, hj, h.trans hxy⟩ }⟩ instance : Lattice (Ideal P) := { Ideal.instPartialOrderIdeal with sup := (· ⊔ ·) le_sup_left := fun _ J i hi ↦ let ⟨w, hw⟩ := J.nonempty ⟨i, hi, w, hw, le_sup_left⟩ le_sup_right := fun I _ j hj ↦ let ⟨w, hw⟩ := I.nonempty ⟨w, hw, j, hj, le_sup_right⟩ sup_le := fun _ _ K hIK hJK _ ⟨_, hi, _, hj, ha⟩ ↦ K.lower ha <| sup_mem (mem_of_mem_of_le hi hIK) (mem_of_mem_of_le hj hJK) inf := (· ⊓ ·) inf_le_left := fun _ _ ↦ inter_subset_left inf_le_right := fun _ _ ↦ inter_subset_right le_inf := fun _ _ _ ↦ subset_inter } @[simp] theorem coe_sup : ↑(s ⊔ t) = { x | ∃ a ∈ s, ∃ b ∈ t, x ≤ a ⊔ b } := rfl @[simp] theorem coe_inf : (↑(s ⊓ t) : Set P) = ↑s ∩ ↑t := rfl @[simp] theorem mem_inf : x ∈ I ⊓ J ↔ x ∈ I ∧ x ∈ J := Iff.rfl @[simp] theorem mem_sup : x ∈ I ⊔ J ↔ ∃ i ∈ I, ∃ j ∈ J, x ≤ i ⊔ j := Iff.rfl theorem lt_sup_principal_of_notMem (hx : x ∉ I) : I < I ⊔ principal x := le_sup_left.lt_of_ne fun h ↦ hx <| by simpa only [left_eq_sup, principal_le_iff] using h @[deprecated (since := "2025-05-23")] alias lt_sup_principal_of_not_mem := lt_sup_principal_of_notMem end SemilatticeSupDirected section SemilatticeSupOrderBot variable [SemilatticeSup P] [OrderBot P] {x : P} instance : InfSet (Ideal P) := ⟨fun S ↦ { toLowerSet := ⨅ s ∈ S, toLowerSet s nonempty' := ⟨⊥, by rw [LowerSet.carrier_eq_coe, LowerSet.coe_iInf₂, Set.mem_iInter₂] exact fun s _ ↦ s.bot_mem⟩ directed' := fun a ha b hb ↦ ⟨a ⊔ b, ⟨by rw [LowerSet.carrier_eq_coe, LowerSet.coe_iInf₂, Set.mem_iInter₂] at ha hb ⊢ exact fun s hs ↦ sup_mem (ha _ hs) (hb _ hs), le_sup_left, le_sup_right⟩⟩ }⟩ variable {S : Set (Ideal P)} @[simp] theorem coe_sInf : (↑(sInf S) : Set P) = ⋂ s ∈ S, ↑s := LowerSet.coe_iInf₂ _ @[simp] theorem mem_sInf : x ∈ sInf S ↔ ∀ s ∈ S, x ∈ s := by simp_rw [← SetLike.mem_coe, coe_sInf, mem_iInter₂] instance : CompleteLattice (Ideal P) := { (inferInstance : Lattice (Ideal P)), completeLatticeOfInf (Ideal P) fun S ↦ by refine ⟨fun s hs ↦ ?_, fun s hs ↦ by rwa [← coe_subset_coe, coe_sInf, subset_iInter₂_iff]⟩ rw [← coe_subset_coe, coe_sInf] exact biInter_subset_of_mem hs with } end SemilatticeSupOrderBot section DistribLattice variable [DistribLattice P] variable {I J : Ideal P} theorem eq_sup_of_le_sup {x i j : P} (hi : i ∈ I) (hj : j ∈ J) (hx : x ≤ i ⊔ j) : ∃ i' ∈ I, ∃ j' ∈ J, x = i' ⊔ j' := by refine ⟨x ⊓ i, I.lower inf_le_right hi, x ⊓ j, J.lower inf_le_right hj, ?_⟩ calc x = x ⊓ (i ⊔ j) := left_eq_inf.mpr hx _ = x ⊓ i ⊔ x ⊓ j := inf_sup_left _ _ _ theorem coe_sup_eq : ↑(I ⊔ J) = { x | ∃ i ∈ I, ∃ j ∈ J, x = i ⊔ j } := Set.ext fun _ ↦ ⟨fun ⟨_, _, _, _, _⟩ ↦ eq_sup_of_le_sup ‹_› ‹_› ‹_›, fun ⟨i, _, j, _, _⟩ ↦ ⟨i, ‹_›, j, ‹_›, le_of_eq ‹_›⟩⟩ end DistribLattice section BooleanAlgebra variable [BooleanAlgebra P] {x : P} {I : Ideal P} theorem IsProper.notMem_of_compl_mem (hI : IsProper I) (hxc : xᶜ ∈ I) : x ∉ I := by intro hx apply hI.top_notMem have ht : x ⊔ xᶜ ∈ I := sup_mem ‹_› ‹_› rwa [sup_compl_eq_top] at ht @[deprecated (since := "2025-05-23")] alias IsProper.not_mem_of_compl_mem := IsProper.notMem_of_compl_mem theorem IsProper.notMem_or_compl_notMem (hI : IsProper I) : x ∉ I ∨ xᶜ ∉ I := by have h : xᶜ ∈ I → x ∉ I := hI.notMem_of_compl_mem tauto @[deprecated (since := "2025-05-23")] alias IsProper.not_mem_or_compl_not_mem := IsProper.notMem_or_compl_notMem end BooleanAlgebra 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) [Preorder P] where /-- The carrier of a `Cofinal` is the underlying set. -/ carrier : Set P /-- The `Cofinal` contains arbitrarily large elements. -/ isCofinal : IsCofinal carrier namespace Cofinal variable [Preorder P] instance : Inhabited (Cofinal P) := ⟨_, .univ⟩ instance : Membership P (Cofinal P) := ⟨fun D x ↦ x ∈ D.carrier⟩ variable (D : Cofinal P) (x : P) /-- A (noncomputable) element of a cofinal set lying above a given element. -/ noncomputable def above : P := Classical.choose <| D.isCofinal x theorem above_mem : D.above x ∈ D := (Classical.choose_spec <| D.isCofinal x).1 theorem le_above : x ≤ D.above x := (Classical.choose_spec <| D.isCofinal x).2 end Cofinal section IdealOfCofinals variable [Preorder P] (p : P) {ι : Type*} [Encodable ι] (𝒟 : ι → Cofinal P) /-- Given a starting point, and a countable family of cofinal sets, this is an increasing sequence that intersects each cofinal set. -/ noncomputable def sequenceOfCofinals : ℕ → P | 0 => p | n + 1 => match Encodable.decode n with | none => sequenceOfCofinals n | some i => (𝒟 i).above (sequenceOfCofinals n) theorem sequenceOfCofinals.monotone : Monotone (sequenceOfCofinals p 𝒟) := by apply monotone_nat_of_le_succ intro n dsimp only [sequenceOfCofinals, Nat.add] cases (Encodable.decode n : Option ι) · rfl · apply Cofinal.le_above theorem sequenceOfCofinals.encode_mem (i : ι) : sequenceOfCofinals p 𝒟 (Encodable.encode i + 1) ∈ 𝒟 i := by dsimp only [sequenceOfCofinals, Nat.add] rw [Encodable.encodek] apply Cofinal.above_mem /-- Given an element `p : P` and a family `𝒟` of cofinal subsets of a preorder `P`, indexed by a countable type, `idealOfCofinals p 𝒟` is an ideal in `P` which - contains `p`, according to `mem_idealOfCofinals p 𝒟`, and - intersects every set in `𝒟`, according to `cofinal_meets_idealOfCofinals p 𝒟`. This proves the Rasiowa–Sikorski lemma. -/ def idealOfCofinals : Ideal P where carrier := { x : P | ∃ n, x ≤ sequenceOfCofinals p 𝒟 n } lower' := fun _ _ hxy ⟨n, hn⟩ ↦ ⟨n, le_trans hxy hn⟩ nonempty' := ⟨p, 0, le_rfl⟩ directed' := fun _ ⟨n, hn⟩ _ ⟨m, hm⟩ ↦ ⟨_, ⟨max n m, le_rfl⟩, le_trans hn <| sequenceOfCofinals.monotone p 𝒟 (le_max_left _ _), le_trans hm <| sequenceOfCofinals.monotone p 𝒟 (le_max_right _ _)⟩ theorem mem_idealOfCofinals : p ∈ idealOfCofinals p 𝒟 := ⟨0, le_rfl⟩ /-- `idealOfCofinals p 𝒟` is `𝒟`-generic. -/ theorem cofinal_meets_idealOfCofinals (i : ι) : ∃ x : P, x ∈ 𝒟 i ∧ x ∈ idealOfCofinals p 𝒟 := ⟨_, sequenceOfCofinals.encode_mem p 𝒟 i, _, le_rfl⟩ end IdealOfCofinals section sUnion variable [Preorder P] /-- A non-empty directed union of ideals of sets in a preorder is an ideal. -/ lemma isIdeal_sUnion_of_directedOn {C : Set (Set P)} (hidl : ∀ I ∈ C, IsIdeal I) (hD : DirectedOn (· ⊆ ·) C) (hNe : C.Nonempty) : IsIdeal C.sUnion := by refine ⟨isLowerSet_sUnion (fun I hI ↦ (hidl I hI).1), Set.nonempty_sUnion.2 ?_, directedOn_sUnion hD (fun J hJ => (hidl J hJ).3)⟩ let ⟨I, hI⟩ := hNe exact ⟨I, ⟨hI, (hidl I hI).2⟩⟩ /-- A union of a nonempty chain of ideals of sets is an ideal. -/ lemma isIdeal_sUnion_of_isChain {C : Set (Set P)} (hidl : ∀ I ∈ C, IsIdeal I) (hC : IsChain (· ⊆ ·) C) (hNe : C.Nonempty) : IsIdeal C.sUnion := isIdeal_sUnion_of_directedOn hidl hC.directedOn hNe end sUnion end Order
.lake/packages/mathlib/Mathlib/Order/WellFounded.lean
import Mathlib.Data.Set.Function import Mathlib.Order.Bounds.Defs /-! # Well-founded relations A relation is well-founded if it can be used for induction: for each `x`, `(∀ y, r y x → P y) → P x` implies `P x`. Well-founded relations can be used for induction and recursion, including construction of fixed points in the space of dependent functions `Π x : α, β x`. The predicate `WellFounded` is defined in the core library. In this file we prove some extra lemmas and provide a few new definitions: `WellFounded.min`, `WellFounded.sup`, and `WellFounded.succ`, and an induction principle `WellFounded.induction_bot`. -/ theorem acc_def {α} {r : α → α → Prop} {a : α} : Acc r a ↔ ∀ b, r b a → Acc r b where mp h := h.rec fun _ h _ ↦ h mpr := .intro a theorem exists_not_acc_lt_of_not_acc {α} {a : α} {r} (h : ¬Acc r a) : ∃ b, ¬Acc r b ∧ r b a := by rw [acc_def] at h push_neg at h simpa only [and_comm] theorem not_acc_iff_exists_descending_chain {α} {r : α → α → Prop} {x : α} : ¬Acc r x ↔ ∃ f : ℕ → α, f 0 = x ∧ ∀ n, r (f (n + 1)) (f n) where mp hx := let f : ℕ → {a : α // ¬Acc r a} := Nat.rec ⟨x, hx⟩ fun _ a ↦ ⟨_, (exists_not_acc_lt_of_not_acc a.2).choose_spec.1⟩ ⟨(f · |>.1), rfl, fun n ↦ (exists_not_acc_lt_of_not_acc (f n).2).choose_spec.2⟩ mpr h acc := acc.rec (fun _x _ ih ⟨f, hf⟩ ↦ ih (f 1) (hf.1 ▸ hf.2 0) ⟨(f <| · + 1), rfl, fun _ ↦ hf.2 _⟩) h theorem acc_iff_isEmpty_descending_chain {α} {r : α → α → Prop} {x : α} : Acc r x ↔ IsEmpty { f : ℕ → α // f 0 = x ∧ ∀ n, r (f (n + 1)) (f n) } := by rw [← not_iff_not, not_isEmpty_iff, nonempty_subtype] exact not_acc_iff_exists_descending_chain /-- A relation is well-founded iff it doesn't have any infinite descending chain. See `RelEmbedding.wellFounded_iff_isEmpty` for a version in terms of relation embeddings. -/ theorem wellFounded_iff_isEmpty_descending_chain {α} {r : α → α → Prop} : WellFounded r ↔ IsEmpty { f : ℕ → α // ∀ n, r (f (n + 1)) (f n) } where mp := fun ⟨h⟩ ↦ ⟨fun ⟨f, hf⟩ ↦ (acc_iff_isEmpty_descending_chain.mp (h (f 0))).false ⟨f, rfl, hf⟩⟩ mpr h := ⟨fun _ ↦ acc_iff_isEmpty_descending_chain.mpr ⟨fun ⟨f, hf⟩ ↦ h.false ⟨f, hf.2⟩⟩⟩ variable {α β γ : Type*} namespace WellFounded variable {r r' : α → α → Prop} protected theorem isAsymm (h : WellFounded r) : IsAsymm α r := ⟨h.asymmetric⟩ protected theorem isIrrefl (h : WellFounded r) : IsIrrefl α r := @IsAsymm.isIrrefl α r h.isAsymm instance [WellFoundedRelation α] : IsAsymm α WellFoundedRelation.rel := WellFoundedRelation.wf.isAsymm instance : IsIrrefl α WellFoundedRelation.rel := IsAsymm.isIrrefl theorem mono (hr : WellFounded r) (h : ∀ a b, r' a b → r a b) : WellFounded r' := Subrelation.wf (h _ _) hr open scoped Function in -- required for scoped `on` notation theorem onFun {α β : Sort*} {r : β → β → Prop} {f : α → β} : WellFounded r → WellFounded (r on f) := InvImage.wf _ /-- If `r` is a well-founded relation, then any nonempty set has a minimal element with respect to `r`. -/ theorem has_min {α} {r : α → α → Prop} (H : WellFounded r) (s : Set α) : s.Nonempty → ∃ a ∈ s, ∀ x ∈ s, ¬r x a | ⟨a, ha⟩ => show ∃ b ∈ s, ∀ x ∈ s, ¬r x b from Acc.recOn (H.apply a) (fun x _ IH => not_imp_not.1 fun hne hx => hne <| ⟨x, hx, fun y hy hyx => hne <| IH y hyx hy⟩) ha /-- A minimal element of a nonempty set in a well-founded order. If you're working with a nonempty linear order, consider defining a `ConditionallyCompleteLinearOrderBot` instance via `WellFoundedLT.conditionallyCompleteLinearOrderBot` and using `Inf` instead. -/ noncomputable def min {r : α → α → Prop} (H : WellFounded r) (s : Set α) (h : s.Nonempty) : α := Classical.choose (H.has_min s h) theorem min_mem {r : α → α → Prop} (H : WellFounded r) (s : Set α) (h : s.Nonempty) : H.min s h ∈ s := let ⟨h, _⟩ := Classical.choose_spec (H.has_min s h) h theorem not_lt_min {r : α → α → Prop} (H : WellFounded r) (s : Set α) (h : s.Nonempty) {x} (hx : x ∈ s) : ¬r x (H.min s h) := let ⟨_, h'⟩ := Classical.choose_spec (H.has_min s h) h' _ hx theorem wellFounded_iff_has_min {r : α → α → Prop} : WellFounded r ↔ ∀ s : Set α, s.Nonempty → ∃ m ∈ s, ∀ x ∈ s, ¬r x m := by refine ⟨fun h => h.has_min, fun h => ⟨fun x => ?_⟩⟩ by_contra hx obtain ⟨m, hm, hm'⟩ := h {x | ¬Acc r x} ⟨x, hx⟩ refine hm ⟨_, fun y hy => ?_⟩ by_contra hy' exact hm' y hy' hy @[deprecated (since := "2025-08-10")] alias wellFounded_iff_no_descending_seq := wellFounded_iff_isEmpty_descending_chain theorem not_rel_apply_succ [h : IsWellFounded α r] (f : ℕ → α) : ∃ n, ¬ r (f (n + 1)) (f n) := by by_contra! hf exact (wellFounded_iff_isEmpty_descending_chain.1 h.wf).elim ⟨f, hf⟩ open Set /-- The supremum of a bounded, well-founded order -/ protected noncomputable def sup {r : α → α → Prop} (wf : WellFounded r) (s : Set α) (h : Bounded r s) : α := wf.min { x | ∀ a ∈ s, r a x } h protected theorem lt_sup {r : α → α → Prop} (wf : WellFounded r) {s : Set α} (h : Bounded r s) {x} (hx : x ∈ s) : r x (wf.sup s h) := min_mem wf { x | ∀ a ∈ s, r a x } h x hx end WellFounded section LinearOrder variable [LinearOrder β] [Preorder γ] theorem WellFounded.min_le (h : WellFounded ((· < ·) : β → β → Prop)) {x : β} {s : Set β} (hx : x ∈ s) (hne : s.Nonempty := ⟨x, hx⟩) : h.min s hne ≤ x := not_lt.1 <| h.not_lt_min _ _ hx theorem Set.range_injOn_strictMono [WellFoundedLT β] : Set.InjOn Set.range { f : β → γ | StrictMono f } := by intro f hf g hg hfg ext a apply WellFoundedLT.induction a intro a IH obtain ⟨b, hb⟩ := hfg ▸ mem_range_self a obtain h | rfl | h := lt_trichotomy b a · rw [← IH b h] at hb cases (hf.injective hb).not_lt h · rw [hb] · obtain ⟨c, hc⟩ := hfg.symm ▸ mem_range_self a have := hg h rw [hb, ← hc, hf.lt_iff_lt] at this rw [IH c this] at hc cases (hg.injective hc).not_lt this theorem Set.range_injOn_strictAnti [WellFoundedGT β] : Set.InjOn Set.range { f : β → γ | StrictAnti f } := fun _ hf _ hg ↦ Set.range_injOn_strictMono (β := βᵒᵈ) hf.dual hg.dual theorem StrictMono.range_inj [WellFoundedLT β] {f g : β → γ} (hf : StrictMono f) (hg : StrictMono g) : Set.range f = Set.range g ↔ f = g := Set.range_injOn_strictMono.eq_iff hf hg theorem StrictAnti.range_inj [WellFoundedGT β] {f g : β → γ} (hf : StrictAnti f) (hg : StrictAnti g) : Set.range f = Set.range g ↔ f = g := Set.range_injOn_strictAnti.eq_iff hf hg /-- A strictly monotone function `f` on a well-order satisfies `x ≤ f x` for all `x`. -/ theorem StrictMono.id_le [WellFoundedLT β] {f : β → β} (hf : StrictMono f) : id ≤ f := by rw [Pi.le_def] by_contra! H obtain ⟨m, hm, hm'⟩ := wellFounded_lt.has_min _ H exact hm' _ (hf hm) hm theorem StrictMono.le_apply [WellFoundedLT β] {f : β → β} (hf : StrictMono f) {x} : x ≤ f x := hf.id_le x /-- A strictly monotone function `f` on a cowell-order satisfies `f x ≤ x` for all `x`. -/ theorem StrictMono.le_id [WellFoundedGT β] {f : β → β} (hf : StrictMono f) : f ≤ id := StrictMono.id_le (β := βᵒᵈ) hf.dual theorem StrictMono.apply_le [WellFoundedGT β] {f : β → β} (hf : StrictMono f) {x} : f x ≤ x := StrictMono.le_apply (β := βᵒᵈ) hf.dual theorem StrictMono.not_bddAbove_range_of_wellFoundedLT {f : β → β} [WellFoundedLT β] [NoMaxOrder β] (hf : StrictMono f) : ¬ BddAbove (Set.range f) := by rintro ⟨a, ha⟩ obtain ⟨b, hb⟩ := exists_gt a exact ((hf.le_apply.trans_lt (hf hb)).trans_le <| ha (Set.mem_range_self _)).false theorem StrictMono.not_bddBelow_range_of_wellFoundedGT {f : β → β} [WellFoundedGT β] [NoMinOrder β] (hf : StrictMono f) : ¬ BddBelow (Set.range f) := hf.dual.not_bddAbove_range_of_wellFoundedLT end LinearOrder namespace Function variable (f : α → β) section LT variable [LT β] [h : WellFoundedLT β] /-- Given a function `f : α → β` where `β` carries a well-founded `<`, this is an element of `α` whose image under `f` is minimal in the sense of `Function.not_lt_argmin`. -/ noncomputable def argmin [Nonempty α] : α := WellFounded.min (InvImage.wf f h.wf) Set.univ Set.univ_nonempty theorem not_lt_argmin [Nonempty α] (a : α) : ¬f a < f (argmin f) := WellFounded.not_lt_min (InvImage.wf f h.wf) _ _ (Set.mem_univ a) /-- Given a function `f : α → β` where `β` carries a well-founded `<`, and a non-empty subset `s` of `α`, this is an element of `s` whose image under `f` is minimal in the sense of `Function.not_lt_argminOn`. -/ noncomputable def argminOn (s : Set α) (hs : s.Nonempty) : α := WellFounded.min (InvImage.wf f h.wf) s hs @[simp] theorem argminOn_mem (s : Set α) (hs : s.Nonempty) : argminOn f s hs ∈ s := WellFounded.min_mem _ _ _ theorem not_lt_argminOn (s : Set α) {a : α} (ha : a ∈ s) (hs : s.Nonempty := Set.nonempty_of_mem ha) : ¬f a < f (argminOn f s hs) := WellFounded.not_lt_min (InvImage.wf f h.wf) s hs ha end LT section LinearOrder variable [LinearOrder β] [WellFoundedLT β] theorem argmin_le (a : α) [Nonempty α] : f (argmin f) ≤ f a := not_lt.mp <| not_lt_argmin f a theorem argminOn_le (s : Set α) {a : α} (ha : a ∈ s) (hs : s.Nonempty := Set.nonempty_of_mem ha) : f (argminOn f s hs) ≤ f a := not_lt.mp <| not_lt_argminOn f s ha hs end LinearOrder end Function section Induction /-- Let `r` be a relation on `α`, let `f : α → β` be a function, let `C : β → Prop`, and let `bot : α`. This induction principle shows that `C (f bot)` holds, given that * some `a` that is accessible by `r` satisfies `C (f a)`, and * for each `b` such that `f b ≠ f bot` and `C (f b)` holds, there is `c` satisfying `r c b` and `C (f c)`. -/ theorem Acc.induction_bot' {α β} {r : α → α → Prop} {a bot : α} (ha : Acc r a) {C : β → Prop} {f : α → β} (ih : ∀ b, f b ≠ f bot → C (f b) → ∃ c, r c b ∧ C (f c)) : C (f a) → C (f bot) := (@Acc.recOn _ _ (fun x _ => C (f x) → C (f bot)) _ ha) fun x _ ih' hC => (eq_or_ne (f x) (f bot)).elim (fun h => h ▸ hC) (fun h => let ⟨y, hy₁, hy₂⟩ := ih x h hC ih' y hy₁ hy₂) /-- Let `r` be a relation on `α`, let `C : α → Prop` and let `bot : α`. This induction principle shows that `C bot` holds, given that * some `a` that is accessible by `r` satisfies `C a`, and * for each `b ≠ bot` such that `C b` holds, there is `c` satisfying `r c b` and `C c`. -/ theorem Acc.induction_bot {α} {r : α → α → Prop} {a bot : α} (ha : Acc r a) {C : α → Prop} (ih : ∀ b, b ≠ bot → C b → ∃ c, r c b ∧ C c) : C a → C bot := ha.induction_bot' ih /-- Let `r` be a well-founded relation on `α`, let `f : α → β` be a function, let `C : β → Prop`, and let `bot : α`. This induction principle shows that `C (f bot)` holds, given that * some `a` satisfies `C (f a)`, and * for each `b` such that `f b ≠ f bot` and `C (f b)` holds, there is `c` satisfying `r c b` and `C (f c)`. -/ theorem WellFounded.induction_bot' {α β} {r : α → α → Prop} (hwf : WellFounded r) {a bot : α} {C : β → Prop} {f : α → β} (ih : ∀ b, f b ≠ f bot → C (f b) → ∃ c, r c b ∧ C (f c)) : C (f a) → C (f bot) := (hwf.apply a).induction_bot' ih /-- Let `r` be a well-founded relation on `α`, let `C : α → Prop`, and let `bot : α`. This induction principle shows that `C bot` holds, given that * some `a` satisfies `C a`, and * for each `b` that satisfies `C b`, there is `c` satisfying `r c b` and `C c`. The naming is inspired by the fact that when `r` is transitive, it follows that `bot` is the smallest element w.r.t. `r` that satisfies `C`. -/ theorem WellFounded.induction_bot {α} {r : α → α → Prop} (hwf : WellFounded r) {a bot : α} {C : α → Prop} (ih : ∀ b, b ≠ bot → C b → ∃ c, r c b ∧ C c) : C a → C bot := hwf.induction_bot' ih end Induction /-- A nonempty linear order with well-founded `<` has a bottom element. -/ noncomputable def WellFoundedLT.toOrderBot {α} [LinearOrder α] [Nonempty α] [h : WellFoundedLT α] : OrderBot α where bot := h.wf.min _ Set.univ_nonempty bot_le a := h.wf.min_le (Set.mem_univ a) /-- A nonempty linear order with well-founded `>` has a top element. -/ noncomputable def WellFoundedGT.toOrderTop {α} [LinearOrder α] [Nonempty α] [WellFoundedGT α] : OrderTop α := have := WellFoundedLT.toOrderBot (α := αᵒᵈ) inferInstanceAs (OrderTop αᵒᵈᵒᵈ) namespace ULift instance [LT α] [h : WellFoundedLT α] : WellFoundedLT (ULift α) where wf := InvImage.wf down h.wf instance [LT α] [WellFoundedGT α] : WellFoundedGT (ULift α) := inferInstanceAs (WellFoundedLT (ULift αᵒᵈ)) end ULift
.lake/packages/mathlib/Mathlib/Order/README.md
# Order This folder contains order theory in a broad sense. ## Order hierarchy The basic order hierarchy is split across a series of subfolders that each depend on the previous: * `Order.Preorder` for preorders, partial orders, lattices, linear orders * `Order.BooleanAlgebra` for Heyting/bi-Heyting/co-Heyting/Boolean algebras * `Order.CompleteLattice` for frames, coframes, complete lattices * `Order.ConditionallyCompleteLattice` for conditionally complete lattices * `Order.CompleteBooleanAlgebra` for complete Boolean algebras Files in earlier subfolders should not import files in later ones. ## TODO Succinctly explain the other subfolders. The above is still very much a vision. We need to sort the content of existing files into those order hierarchy subfolders.
.lake/packages/mathlib/Mathlib/Order/IsNormal.lean
import Mathlib.Order.SuccPred.CompleteLinearOrder import Mathlib.Order.SuccPred.InitialSeg /-! # Normal functions A normal function between well-orders is a strictly monotonic continuous function. Normal functions arise chiefly in the context of cardinal and ordinal-valued functions. We opt for an equivalent definition that's both simpler and often more convenient: a normal function is a strictly monotonic function `f` such that at successor limits `a`, `f a` is the least upper bound of `f b` with `b < a`. ## TODO * Prove the equivalence with the standard definition (in some other file). * Replace `Ordinal.IsNormal` by this more general notion. -/ open Order Set variable {α β γ : Type*} {a b : α} {f : α → β} {g : β → γ} namespace Order /-- A normal function between well-orders is a strictly monotonic continuous function. -/ @[mk_iff isNormal_iff'] structure IsNormal [LinearOrder α] [LinearOrder β] (f : α → β) : Prop where strictMono : StrictMono f /-- This condition is the RHS of the `IsLUB (f '' Iio a) (f a)` predicate, which is sufficient since the LHS is implied by monotonicity. -/ mem_lowerBounds_upperBounds_of_isSuccLimit {a : α} (ha : IsSuccLimit a) : f a ∈ lowerBounds (upperBounds (f '' Iio a)) theorem isNormal_iff [LinearOrder α] [LinearOrder β] {f : α → β} : IsNormal f ↔ StrictMono f ∧ ∀ o, IsSuccLimit o → ∀ a, (∀ b < o, f b ≤ a) → f o ≤ a := by simp [isNormal_iff', mem_lowerBounds, mem_upperBounds] namespace IsNormal section LinearOrder variable [LinearOrder α] [LinearOrder β] [LinearOrder γ] theorem isLUB_image_Iio_of_isSuccLimit {f : α → β} (hf : IsNormal f) {a : α} (ha : IsSuccLimit a) : IsLUB (f '' Iio a) (f a) := by refine ⟨?_, hf.2 ha⟩ rintro - ⟨b, hb, rfl⟩ exact (hf.1 hb).le @[deprecated "use the default constructor of `IsNormal` directly" (since := "2025-07-08")] theorem of_mem_lowerBounds_upperBounds {f : α → β} (hf : StrictMono f) (hl : ∀ {a}, IsSuccLimit a → f a ∈ lowerBounds (upperBounds (f '' Iio a))) : IsNormal f := ⟨hf, hl⟩ theorem le_iff_forall_le (hf : IsNormal f) (ha : IsSuccLimit a) {b : β} : f a ≤ b ↔ ∀ a' < a, f a' ≤ b := by simpa [mem_upperBounds] using isLUB_le_iff (hf.isLUB_image_Iio_of_isSuccLimit ha) theorem lt_iff_exists_lt (hf : IsNormal f) (ha : IsSuccLimit a) {b : β} : b < f a ↔ ∃ a' < a, b < f a' := by simpa [mem_upperBounds] using lt_isLUB_iff (hf.isLUB_image_Iio_of_isSuccLimit ha) theorem map_isSuccLimit (hf : IsNormal f) (ha : IsSuccLimit a) : IsSuccLimit (f a) := by refine ⟨?_, fun b hb ↦ ?_⟩ · obtain ⟨b, hb⟩ := not_isMin_iff.1 ha.not_isMin exact not_isMin_iff.2 ⟨_, hf.strictMono hb⟩ · obtain ⟨c, hc, hc'⟩ := (hf.lt_iff_exists_lt ha).1 hb.lt have hc' := hb.ge_of_gt hc' rw [hf.strictMono.le_iff_le] at hc' exact hc.not_ge hc' theorem map_isLUB (hf : IsNormal f) {s : Set α} (hs : IsLUB s a) (hs' : s.Nonempty) : IsLUB (f '' s) (f a) := by refine ⟨?_, fun b hb ↦ ?_⟩ · simpa [mem_upperBounds, hf.strictMono.le_iff_le] using hs.1 · by_cases ha : a ∈ s · simp_all [mem_upperBounds] · have ha' := hs.isSuccLimit_of_notMem hs' ha rw [le_iff_forall_le hf ha'] intro c hc obtain ⟨d, hd, hcd, hda⟩ := hs.exists_between hc simp_rw [mem_upperBounds, forall_mem_image] at hb exact (hf.strictMono hcd).le.trans (hb hd) theorem _root_.InitialSeg.isNormal (f : α ≤i β) : IsNormal f where strictMono := f.strictMono mem_lowerBounds_upperBounds_of_isSuccLimit ha := by rw [f.image_Iio] exact (f.map_isSuccLimit ha).isLUB_Iio.2 theorem _root_.PrincipalSeg.isNormal (f : α <i β) : IsNormal f := (f : α ≤i β).isNormal theorem _root_.OrderIso.isNormal (f : α ≃o β) : IsNormal f := f.toInitialSeg.isNormal protected theorem id : IsNormal (@id α) := (OrderIso.refl _).isNormal theorem comp (hg : IsNormal g) (hf : IsNormal f) : IsNormal (g ∘ f) := by refine ⟨hg.strictMono.comp hf.strictMono, fun ha b hb ↦ ?_⟩ simp_rw [Function.comp_apply, mem_upperBounds, forall_mem_image] at hb simpa [hg.le_iff_forall_le (hf.map_isSuccLimit ha), hf.lt_iff_exists_lt ha] using fun c d hd hc ↦ (hg.strictMono hc).le.trans (hb hd) section WellFoundedLT variable [WellFoundedLT α] [SuccOrder α] theorem of_succ_lt (hs : ∀ a, f a < f (succ a)) (hl : ∀ {a}, IsSuccLimit a → IsLUB (f '' Iio a) (f a)) : IsNormal f := by refine ⟨fun a b ↦ ?_, fun ha ↦ (hl ha).2⟩ induction b using SuccOrder.limitRecOn with | isMin b hb => exact hb.not_lt.elim | succ b hb IH => intro hab obtain rfl | h := (lt_succ_iff_eq_or_lt_of_not_isMax hb).1 hab · exact hs a · exact (IH h).trans (hs b) | isSuccLimit b hb IH => intro hab have hab' := hb.succ_lt hab exact (IH _ hab' (lt_succ_of_not_isMax hab.not_isMax)).trans_le ((hl hb).1 (mem_image_of_mem _ hab')) protected theorem ext [OrderBot α] {g : α → β} (hf : IsNormal f) (hg : IsNormal g) : f = g ↔ f ⊥ = g ⊥ ∧ ∀ a, f a = g a → f (succ a) = g (succ a) := by constructor · simp_all rintro ⟨H₁, H₂⟩ ext a induction a using SuccOrder.limitRecOn with | isMin a ha => rw [ha.eq_bot, H₁] | succ a ha IH => exact H₂ a IH | isSuccLimit a ha IH => apply (hf.isLUB_image_Iio_of_isSuccLimit ha).unique convert hg.isLUB_image_Iio_of_isSuccLimit ha using 1 aesop end WellFoundedLT end LinearOrder section ConditionallyCompleteLinearOrder variable [ConditionallyCompleteLinearOrder α] [ConditionallyCompleteLinearOrder β] theorem map_sSup (hf : IsNormal f) {s : Set α} (hs : s.Nonempty) (hs' : BddAbove s) : f (sSup s) = sSup (f '' s) := ((hf.map_isLUB (isLUB_csSup hs hs') hs).csSup_eq (hs.image f)).symm theorem map_iSup {ι} [Nonempty ι] {g : ι → α} (hf : IsNormal f) (hg : BddAbove (range g)) : f (⨆ i, g i) = ⨆ i, f (g i) := by unfold iSup convert map_sSup hf (range_nonempty g) hg ext simp theorem preimage_Iic (hf : IsNormal f) {x : β} (h₁ : (f ⁻¹' Iic x).Nonempty) (h₂ : BddAbove (f ⁻¹' Iic x)) : f ⁻¹' Iic x = Iic (sSup (f ⁻¹' Iic x)) := by refine le_antisymm (fun _ ↦ le_csSup h₂) (fun y hy ↦ ?_) obtain hy | rfl := hy.lt_or_eq · rw [lt_csSup_iff h₂ h₁] at hy obtain ⟨z, hz, hyz⟩ := hy exact (hf.strictMono hyz).le.trans hz · rw [mem_preimage, hf.map_sSup h₁ h₂] apply (csSup_le_csSup bddAbove_Iic _ (image_preimage_subset ..)).trans · rw [csSup_Iic] · simpa end ConditionallyCompleteLinearOrder section ConditionallyCompleteLinearOrderBot variable [ConditionallyCompleteLinearOrderBot α] [ConditionallyCompleteLinearOrder β] theorem apply_of_isSuccLimit (hf : IsNormal f) (ha : IsSuccLimit a) : f a = ⨆ b : Iio a, f b := by convert map_iSup hf _ · exact ha.iSup_Iio.symm · exact ⟨⊥, ha.bot_lt⟩ · use a rintro _ ⟨⟨x, hx⟩, rfl⟩ exact hx.le end ConditionallyCompleteLinearOrderBot end IsNormal end Order
.lake/packages/mathlib/Mathlib/Order/RelClasses.lean
import Mathlib.Logic.IsEmpty import Mathlib.Order.Basic import Mathlib.Tactic.MkIffOfInductiveProp import Batteries.WF /-! # Unbundled relation classes In this file we prove some properties of `Is*` classes defined in `Mathlib/Order/Defs/Unbundled.lean`. The main difference between these classes and the usual order classes (`Preorder` etc) is that usual classes extend `LE` and/or `LT` while these classes take a relation as an explicit argument. -/ universe u v variable {α : Type u} {β : Type v} {r : α → α → Prop} {s : β → β → Prop} open Function theorem IsRefl.swap (r) [IsRefl α r] : IsRefl α (swap r) := ⟨refl_of r⟩ theorem IsIrrefl.swap (r) [IsIrrefl α r] : IsIrrefl α (swap r) := ⟨irrefl_of r⟩ theorem IsTrans.swap (r) [IsTrans α r] : IsTrans α (swap r) := ⟨fun _ _ _ h₁ h₂ => trans_of r h₂ h₁⟩ theorem IsAntisymm.swap (r) [IsAntisymm α r] : IsAntisymm α (swap r) := ⟨fun _ _ h₁ h₂ => _root_.antisymm h₂ h₁⟩ theorem IsAsymm.swap (r) [IsAsymm α r] : IsAsymm α (swap r) := ⟨fun _ _ h₁ h₂ => asymm_of r h₂ h₁⟩ theorem IsTotal.swap (r) [IsTotal α r] : IsTotal α (swap r) := ⟨fun a b => (total_of r a b).symm⟩ theorem IsTrichotomous.swap (r) [IsTrichotomous α r] : IsTrichotomous α (swap r) := ⟨fun a b => by simpa [Function.swap, or_comm, or_left_comm] using trichotomous_of r a b⟩ theorem IsPreorder.swap (r) [IsPreorder α r] : IsPreorder α (swap r) := { @IsRefl.swap α r _, @IsTrans.swap α r _ with } theorem IsStrictOrder.swap (r) [IsStrictOrder α r] : IsStrictOrder α (swap r) := { @IsIrrefl.swap α r _, @IsTrans.swap α r _ with } theorem IsPartialOrder.swap (r) [IsPartialOrder α r] : IsPartialOrder α (swap r) := { @IsPreorder.swap α r _, @IsAntisymm.swap α r _ with } theorem eq_empty_relation (r) [IsIrrefl α r] [Subsingleton α] : r = EmptyRelation := funext₂ <| by simpa using not_rel_of_subsingleton r /-- Construct a partial order from an `isStrictOrder` relation. See note [reducible non-instances]. -/ abbrev partialOrderOfSO (r) [IsStrictOrder α r] : PartialOrder α where le x y := x = y ∨ r x y lt := r le_refl _ := Or.inl rfl le_trans x y z h₁ h₂ := match y, z, h₁, h₂ with | _, _, Or.inl rfl, h₂ => h₂ | _, _, h₁, Or.inl rfl => h₁ | _, _, Or.inr h₁, Or.inr h₂ => Or.inr (_root_.trans h₁ h₂) le_antisymm x y h₁ h₂ := match y, h₁, h₂ with | _, Or.inl rfl, _ => rfl | _, _, Or.inl rfl => rfl | _, Or.inr h₁, Or.inr h₂ => (asymm h₁ h₂).elim lt_iff_le_not_ge x y := ⟨fun h => ⟨Or.inr h, not_or_intro (fun e => by rw [e] at h; exact irrefl _ h) (asymm h)⟩, fun ⟨h₁, h₂⟩ => h₁.resolve_left fun e => h₂ <| e ▸ Or.inl rfl⟩ /-- Construct a linear order from an `IsStrictTotalOrder` relation. See note [reducible non-instances]. -/ abbrev linearOrderOfSTO (r) [IsStrictTotalOrder α r] [DecidableRel r] : LinearOrder α := let hD : DecidableRel (fun x y => x = y ∨ r x y) := fun x y => decidable_of_iff (¬r y x) ⟨fun h => ((trichotomous_of r y x).resolve_left h).imp Eq.symm id, fun h => h.elim (fun h => h ▸ irrefl_of _ _) (asymm_of r)⟩ { __ := partialOrderOfSO r le_total := fun x y => match y, trichotomous_of r x y with | _, Or.inl h => Or.inl (Or.inr h) | _, Or.inr (Or.inl rfl) => Or.inl (Or.inl rfl) | _, Or.inr (Or.inr h) => Or.inr (Or.inr h), toMin := minOfLe, toMax := maxOfLe, toDecidableLE := hD } theorem IsStrictTotalOrder.swap (r) [IsStrictTotalOrder α r] : IsStrictTotalOrder α (swap r) := { IsTrichotomous.swap r, IsStrictOrder.swap r with } /-! ### Order connection -/ /-- A connected order is one satisfying the condition `a < c → a < b ∨ b < c`. This is recognizable as an intuitionistic substitute for `a ≤ b ∨ b ≤ a` on the constructive reals, and is also known as negative transitivity, since the contrapositive asserts transitivity of the relation `¬ a < b`. -/ class IsOrderConnected (α : Type u) (lt : α → α → Prop) : Prop where /-- A connected order is one satisfying the condition `a < c → a < b ∨ b < c`. -/ conn : ∀ a b c, lt a c → lt a b ∨ lt b c theorem IsOrderConnected.neg_trans {r : α → α → Prop} [IsOrderConnected α r] {a b c} (h₁ : ¬r a b) (h₂ : ¬r b c) : ¬r a c := mt (IsOrderConnected.conn a b c) <| by simp [h₁, h₂] theorem isStrictWeakOrder_of_isOrderConnected [IsAsymm α r] [IsOrderConnected α r] : IsStrictWeakOrder α r := { @IsAsymm.isIrrefl α r _ with trans := fun _ _ c h₁ h₂ => (IsOrderConnected.conn _ c _ h₁).resolve_right (asymm h₂), incomp_trans := fun _ _ _ ⟨h₁, h₂⟩ ⟨h₃, h₄⟩ => ⟨IsOrderConnected.neg_trans h₁ h₃, IsOrderConnected.neg_trans h₄ h₂⟩ } -- see Note [lower instance priority] instance (priority := 100) isStrictOrderConnected_of_isStrictTotalOrder [IsStrictTotalOrder α r] : IsOrderConnected α r := ⟨fun _ _ _ h ↦ (trichotomous _ _).imp_right fun o ↦ o.elim (fun e ↦ e ▸ h) fun h' ↦ _root_.trans h' h⟩ /-! ### Inverse Image -/ theorem InvImage.isTrichotomous [IsTrichotomous α r] {f : β → α} (h : Function.Injective f) : IsTrichotomous β (InvImage r f) where trichotomous a b := trichotomous (f a) (f b) |>.imp3 id (h ·) id instance InvImage.isAsymm [IsAsymm α r] (f : β → α) : IsAsymm β (InvImage r f) where asymm a b h h2 := IsAsymm.asymm (f a) (f b) h h2 /-! ### Well-order -/ /-- A well-founded relation. Not to be confused with `IsWellOrder`. -/ @[mk_iff] class IsWellFounded (α : Type u) (r : α → α → Prop) : Prop where /-- The relation is `WellFounded`, as a proposition. -/ wf : WellFounded r instance WellFoundedRelation.isWellFounded [h : WellFoundedRelation α] : IsWellFounded α WellFoundedRelation.rel := { h with } theorem WellFoundedRelation.asymmetric {α : Sort*} [WellFoundedRelation α] {a b : α} : WellFoundedRelation.rel a b → ¬ WellFoundedRelation.rel b a := fun hab hba => WellFoundedRelation.asymmetric hba hab termination_by a theorem WellFoundedRelation.asymmetric₃ {α : Sort*} [WellFoundedRelation α] {a b c : α} : WellFoundedRelation.rel a b → WellFoundedRelation.rel b c → ¬ WellFoundedRelation.rel c a := fun hab hbc hca => WellFoundedRelation.asymmetric₃ hca hab hbc termination_by a lemma WellFounded.prod_lex {ra : α → α → Prop} {rb : β → β → Prop} (ha : WellFounded ra) (hb : WellFounded rb) : WellFounded (Prod.Lex ra rb) := (Prod.lex ⟨_, ha⟩ ⟨_, hb⟩).wf section PSigma open PSigma /-- The lexicographical order of well-founded relations is well-founded. -/ theorem WellFounded.psigma_lex {α : Sort*} {β : α → Sort*} {r : α → α → Prop} {s : ∀ a : α, β a → β a → Prop} (ha : WellFounded r) (hb : ∀ x, WellFounded (s x)) : WellFounded (Lex r s) := WellFounded.intro fun ⟨a, b⟩ => lexAccessible (WellFounded.apply ha a) hb b theorem WellFounded.psigma_revLex {α : Sort*} {β : Sort*} {r : α → α → Prop} {s : β → β → Prop} (ha : WellFounded r) (hb : WellFounded s) : WellFounded (RevLex r s) := WellFounded.intro fun ⟨a, b⟩ => revLexAccessible (apply hb b) (WellFounded.apply ha) a theorem WellFounded.psigma_skipLeft (α : Type u) {β : Type v} {s : β → β → Prop} (hb : WellFounded s) : WellFounded (SkipLeft α s) := psigma_revLex emptyWf.wf hb end PSigma namespace IsWellFounded variable (r) [IsWellFounded α r] /-- Induction on a well-founded relation. -/ theorem induction {C : α → Prop} (a : α) (ind : ∀ x, (∀ y, r y x → C y) → C x) : C a := wf.induction _ ind /-- All values are accessible under the well-founded relation. -/ theorem apply : ∀ a, Acc r a := wf.apply /-- Creates data, given a way to generate a value from all that compare as less under a well-founded relation. See also `IsWellFounded.fix_eq`. -/ def fix {C : α → Sort*} : (∀ x : α, (∀ y : α, r y x → C y) → C x) → ∀ x : α, C x := wf.fix /-- The value from `IsWellFounded.fix` is built from the previous ones as specified. -/ theorem fix_eq {C : α → Sort*} (F : ∀ x : α, (∀ y : α, r y x → C y) → C x) : ∀ x, fix r F x = F x fun y _ => fix r F y := wf.fix_eq F /-- Derive a `WellFoundedRelation` instance from an `isWellFounded` instance. -/ def toWellFoundedRelation : WellFoundedRelation α := ⟨r, IsWellFounded.wf⟩ end IsWellFounded theorem WellFounded.asymmetric {α : Sort*} {r : α → α → Prop} (h : WellFounded r) (a b) : r a b → ¬r b a := @WellFoundedRelation.asymmetric _ ⟨_, h⟩ _ _ theorem WellFounded.asymmetric₃ {α : Sort*} {r : α → α → Prop} (h : WellFounded r) (a b c) : r a b → r b c → ¬r c a := @WellFoundedRelation.asymmetric₃ _ ⟨_, h⟩ _ _ _ -- see Note [lower instance priority] instance (priority := 100) (r : α → α → Prop) [IsWellFounded α r] : IsAsymm α r := ⟨IsWellFounded.wf.asymmetric⟩ -- see Note [lower instance priority] instance (priority := 100) (r : α → α → Prop) [IsWellFounded α r] : IsIrrefl α r := IsAsymm.isIrrefl instance (r : α → α → Prop) [i : IsWellFounded α r] : IsWellFounded α (Relation.TransGen r) := ⟨i.wf.transGen⟩ /-- A class for a well-founded relation `<`. -/ abbrev WellFoundedLT (α : Type*) [LT α] : Prop := IsWellFounded α (· < ·) /-- A class for a well-founded relation `>`. -/ abbrev WellFoundedGT (α : Type*) [LT α] : Prop := IsWellFounded α (· > ·) lemma wellFounded_lt [LT α] [WellFoundedLT α] : @WellFounded α (· < ·) := IsWellFounded.wf lemma wellFounded_gt [LT α] [WellFoundedGT α] : @WellFounded α (· > ·) := IsWellFounded.wf -- See note [lower instance priority] instance (priority := 100) (α : Type*) [LT α] [h : WellFoundedLT α] : WellFoundedGT αᵒᵈ := h -- See note [lower instance priority] instance (priority := 100) (α : Type*) [LT α] [h : WellFoundedGT α] : WellFoundedLT αᵒᵈ := h theorem wellFoundedGT_dual_iff (α : Type*) [LT α] : WellFoundedGT αᵒᵈ ↔ WellFoundedLT α := ⟨fun h => ⟨h.wf⟩, fun h => ⟨h.wf⟩⟩ theorem wellFoundedLT_dual_iff (α : Type*) [LT α] : WellFoundedLT αᵒᵈ ↔ WellFoundedGT α := ⟨fun h => ⟨h.wf⟩, fun h => ⟨h.wf⟩⟩ /-- A well order is a well-founded linear order. -/ class IsWellOrder (α : Type u) (r : α → α → Prop) : Prop extends IsTrichotomous α r, IsTrans α r, IsWellFounded α r -- see Note [lower instance priority] instance (priority := 100) {α} (r : α → α → Prop) [IsWellOrder α r] : IsStrictTotalOrder α r where -- see Note [lower instance priority] instance (priority := 100) {α} (r : α → α → Prop) [IsWellOrder α r] : IsTrichotomous α r := by infer_instance -- see Note [lower instance priority] instance (priority := 100) {α} (r : α → α → Prop) [IsWellOrder α r] : IsTrans α r := by infer_instance -- see Note [lower instance priority] instance (priority := 100) {α} (r : α → α → Prop) [IsWellOrder α r] : IsIrrefl α r := by infer_instance -- see Note [lower instance priority] instance (priority := 100) {α} (r : α → α → Prop) [IsWellOrder α r] : IsAsymm α r := by infer_instance namespace WellFoundedLT variable [LT α] [WellFoundedLT α] /-- Inducts on a well-founded `<` relation. -/ theorem induction {C : α → Prop} (a : α) (ind : ∀ x, (∀ y, y < x → C y) → C x) : C a := IsWellFounded.induction _ _ ind /-- All values are accessible under the well-founded `<`. -/ theorem apply : ∀ a : α, Acc (· < ·) a := IsWellFounded.apply _ /-- Creates data, given a way to generate a value from all that compare as lesser. See also `WellFoundedLT.fix_eq`. -/ def fix {C : α → Sort*} : (∀ x : α, (∀ y : α, y < x → C y) → C x) → ∀ x : α, C x := IsWellFounded.fix (· < ·) /-- The value from `WellFoundedLT.fix` is built from the previous ones as specified. -/ theorem fix_eq {C : α → Sort*} (F : ∀ x : α, (∀ y : α, y < x → C y) → C x) : ∀ x, fix F x = F x fun y _ => fix F y := IsWellFounded.fix_eq _ F /-- Derive a `WellFoundedRelation` instance from a `WellFoundedLT` instance. -/ def toWellFoundedRelation : WellFoundedRelation α := IsWellFounded.toWellFoundedRelation (· < ·) end WellFoundedLT namespace WellFoundedGT variable [LT α] [WellFoundedGT α] /-- Inducts on a well-founded `>` relation. -/ theorem induction {C : α → Prop} (a : α) (ind : ∀ x, (∀ y, x < y → C y) → C x) : C a := IsWellFounded.induction _ _ ind /-- All values are accessible under the well-founded `>`. -/ theorem apply : ∀ a : α, Acc (· > ·) a := IsWellFounded.apply _ /-- Creates data, given a way to generate a value from all that compare as greater. See also `WellFoundedGT.fix_eq`. -/ def fix {C : α → Sort*} : (∀ x : α, (∀ y : α, x < y → C y) → C x) → ∀ x : α, C x := IsWellFounded.fix (· > ·) /-- The value from `WellFoundedGT.fix` is built from the successive ones as specified. -/ theorem fix_eq {C : α → Sort*} (F : ∀ x : α, (∀ y : α, x < y → C y) → C x) : ∀ x, fix F x = F x fun y _ => fix F y := IsWellFounded.fix_eq _ F /-- Derive a `WellFoundedRelation` instance from a `WellFoundedGT` instance. -/ def toWellFoundedRelation : WellFoundedRelation α := IsWellFounded.toWellFoundedRelation (· > ·) end WellFoundedGT open Classical in /-- Construct a decidable linear order from a well-founded linear order. -/ noncomputable def IsWellOrder.linearOrder (r : α → α → Prop) [IsWellOrder α r] : LinearOrder α := linearOrderOfSTO r /-- Derive a `WellFoundedRelation` instance from an `IsWellOrder` instance. -/ def IsWellOrder.toHasWellFounded [LT α] [hwo : IsWellOrder α (· < ·)] : WellFoundedRelation α where rel := (· < ·) wf := hwo.wf -- This isn't made into an instance as it loops with `IsIrrefl α r`. theorem Subsingleton.isWellOrder [Subsingleton α] (r : α → α → Prop) [hr : IsIrrefl α r] : IsWellOrder α r := { hr with trichotomous := fun a b => Or.inr <| Or.inl <| Subsingleton.elim a b, trans := fun a b _ h => (not_rel_of_subsingleton r a b h).elim, wf := ⟨fun a => ⟨_, fun y h => (not_rel_of_subsingleton r y a h).elim⟩⟩ } instance [Subsingleton α] : IsWellOrder α EmptyRelation := Subsingleton.isWellOrder _ instance (priority := 100) [IsEmpty α] (r : α → α → Prop) : IsWellOrder α r where trichotomous := isEmptyElim trans := isEmptyElim wf := wellFounded_of_isEmpty r instance Prod.Lex.instIsWellFounded [IsWellFounded α r] [IsWellFounded β s] : IsWellFounded (α × β) (Prod.Lex r s) := ⟨IsWellFounded.wf.prod_lex IsWellFounded.wf⟩ instance [IsWellOrder α r] [IsWellOrder β s] : IsWellOrder (α × β) (Prod.Lex r s) where trichotomous := fun ⟨a₁, a₂⟩ ⟨b₁, b₂⟩ => match @trichotomous _ r _ a₁ b₁ with | Or.inl h₁ => Or.inl <| Prod.Lex.left _ _ h₁ | Or.inr (Or.inr h₁) => Or.inr <| Or.inr <| Prod.Lex.left _ _ h₁ | Or.inr (Or.inl (.refl _)) => match @trichotomous _ s _ a₂ b₂ with | Or.inl h => Or.inl <| Prod.Lex.right _ h | Or.inr (Or.inr h) => Or.inr <| Or.inr <| Prod.Lex.right _ h | Or.inr (Or.inl (.refl _)) => Or.inr <| Or.inl rfl trans a b c h₁ h₂ := by rcases h₁ with ⟨a₂, b₂, ab⟩ | ⟨a₁, ab⟩ <;> rcases h₂ with ⟨c₁, c₂, bc⟩ | ⟨c₂, bc⟩ exacts [.left _ _ (_root_.trans ab bc), .left _ _ ab, .left _ _ bc, .right _ (_root_.trans ab bc)] instance (r : α → α → Prop) [IsWellFounded α r] (f : β → α) : IsWellFounded _ (InvImage r f) := ⟨InvImage.wf f IsWellFounded.wf⟩ instance (f : α → ℕ) : IsWellFounded _ (InvImage (· < ·) f) := ⟨(measure f).wf⟩ theorem Subrelation.isWellFounded (r : α → α → Prop) [IsWellFounded α r] {s : α → α → Prop} (h : Subrelation s r) : IsWellFounded α s := ⟨h.wf IsWellFounded.wf⟩ /-- See `Prod.wellFoundedLT` for a version that only requires `Preorder α`. -/ theorem Prod.wellFoundedLT' [PartialOrder α] [WellFoundedLT α] [Preorder β] [WellFoundedLT β] : WellFoundedLT (α × β) := Subrelation.isWellFounded (Prod.Lex (· < ·) (· < ·)) fun {x y} h ↦ (Prod.lt_iff.mp h).elim (fun h ↦ .left _ _ h.1) fun h ↦ h.1.lt_or_eq.elim (.left _ _) <| by cases x; cases y; rintro rfl; exact .right _ h.2 /-- See `Prod.wellFoundedGT` for a version that only requires `Preorder α`. -/ theorem Prod.wellFoundedGT' [PartialOrder α] [WellFoundedGT α] [Preorder β] [WellFoundedGT β] : WellFoundedGT (α × β) := @Prod.wellFoundedLT' αᵒᵈ βᵒᵈ _ _ _ _ namespace Set /-- An unbounded or cofinal set. -/ def Unbounded (r : α → α → Prop) (s : Set α) : Prop := ∀ a, ∃ b ∈ s, ¬r b a /-- A bounded or final set. Not to be confused with `Bornology.IsBounded`. -/ def Bounded (r : α → α → Prop) (s : Set α) : Prop := ∃ a, ∀ b ∈ s, r b a @[simp] theorem not_bounded_iff {r : α → α → Prop} (s : Set α) : ¬Bounded r s ↔ Unbounded r s := by simp only [Bounded, Unbounded, not_forall, not_exists, exists_prop] @[simp] theorem not_unbounded_iff {r : α → α → Prop} (s : Set α) : ¬Unbounded r s ↔ Bounded r s := by rw [not_iff_comm, not_bounded_iff] theorem unbounded_of_isEmpty [IsEmpty α] {r : α → α → Prop} (s : Set α) : Unbounded r s := isEmptyElim end Set namespace Order.Preimage instance instIsRefl [IsRefl α r] {f : β → α} : IsRefl β (f ⁻¹'o r) := ⟨fun _ => refl_of r _⟩ instance instIsIrrefl [IsIrrefl α r] {f : β → α} : IsIrrefl β (f ⁻¹'o r) := ⟨fun _ => irrefl_of r _⟩ instance instIsSymm [IsSymm α r] {f : β → α} : IsSymm β (f ⁻¹'o r) := ⟨fun _ _ ↦ symm_of r⟩ instance instIsAsymm [IsAsymm α r] {f : β → α} : IsAsymm β (f ⁻¹'o r) := ⟨fun _ _ ↦ asymm_of r⟩ instance instIsTrans [IsTrans α r] {f : β → α} : IsTrans β (f ⁻¹'o r) := ⟨fun _ _ _ => trans_of r⟩ instance instIsPreorder [IsPreorder α r] {f : β → α} : IsPreorder β (f ⁻¹'o r) where instance instIsStrictOrder [IsStrictOrder α r] {f : β → α} : IsStrictOrder β (f ⁻¹'o r) where instance instIsStrictWeakOrder [IsStrictWeakOrder α r] {f : β → α} : IsStrictWeakOrder β (f ⁻¹'o r) where incomp_trans _ _ _ := IsStrictWeakOrder.incomp_trans (lt := r) _ _ _ instance instIsEquiv [IsEquiv α r] {f : β → α} : IsEquiv β (f ⁻¹'o r) where instance instIsTotal [IsTotal α r] {f : β → α} : IsTotal β (f ⁻¹'o r) := ⟨fun _ _ => total_of r _ _⟩ theorem isAntisymm [IsAntisymm α r] {f : β → α} (hf : f.Injective) : IsAntisymm β (f ⁻¹'o r) := ⟨fun _ _ h₁ h₂ ↦ hf <| antisymm_of r h₁ h₂⟩ end Order.Preimage /-! ### Strict-non strict relations -/ /-- An unbundled relation class stating that `r` is the nonstrict relation corresponding to the strict relation `s`. Compare `Preorder.lt_iff_le_not_ge`. This is mostly meant to provide dot notation on `(⊆)` and `(⊂)`. -/ class IsNonstrictStrictOrder (α : Type*) (r : semiOutParam (α → α → Prop)) (s : α → α → Prop) : Prop where /-- The relation `r` is the nonstrict relation corresponding to the strict relation `s`. -/ right_iff_left_not_left (a b : α) : s a b ↔ r a b ∧ ¬r b a theorem right_iff_left_not_left {r s : α → α → Prop} [IsNonstrictStrictOrder α r s] {a b : α} : s a b ↔ r a b ∧ ¬r b a := IsNonstrictStrictOrder.right_iff_left_not_left _ _ /-- A version of `right_iff_left_not_left` with explicit `r` and `s`. -/ theorem right_iff_left_not_left_of (r s : α → α → Prop) [IsNonstrictStrictOrder α r s] {a b : α} : s a b ↔ r a b ∧ ¬r b a := right_iff_left_not_left instance {s : α → α → Prop} [IsNonstrictStrictOrder α r s] : IsIrrefl α s := ⟨fun _ h => ((right_iff_left_not_left_of r s).1 h).2 ((right_iff_left_not_left_of r s).1 h).1⟩ /-! #### `⊆` and `⊂` -/ section Subset variable [HasSubset α] {a b c : α} lemma subset_of_eq_of_subset (hab : a = b) (hbc : b ⊆ c) : a ⊆ c := by rwa [hab] lemma subset_of_subset_of_eq (hab : a ⊆ b) (hbc : b = c) : a ⊆ c := by rwa [← hbc] @[refl, simp] lemma subset_refl [IsRefl α (· ⊆ ·)] (a : α) : a ⊆ a := refl _ lemma subset_rfl [IsRefl α (· ⊆ ·)] : a ⊆ a := refl _ lemma subset_of_eq [IsRefl α (· ⊆ ·)] : a = b → a ⊆ b := fun h => h ▸ subset_rfl lemma superset_of_eq [IsRefl α (· ⊆ ·)] : a = b → b ⊆ a := fun h => h ▸ subset_rfl lemma ne_of_not_subset [IsRefl α (· ⊆ ·)] : ¬a ⊆ b → a ≠ b := mt subset_of_eq lemma ne_of_not_superset [IsRefl α (· ⊆ ·)] : ¬a ⊆ b → b ≠ a := mt superset_of_eq @[trans] lemma subset_trans [IsTrans α (· ⊆ ·)] {a b c : α} : a ⊆ b → b ⊆ c → a ⊆ c := _root_.trans lemma subset_antisymm [IsAntisymm α (· ⊆ ·)] : a ⊆ b → b ⊆ a → a = b := antisymm lemma superset_antisymm [IsAntisymm α (· ⊆ ·)] : a ⊆ b → b ⊆ a → b = a := antisymm' alias Eq.trans_subset := subset_of_eq_of_subset alias HasSubset.subset.trans_eq := subset_of_subset_of_eq alias Eq.subset' := subset_of_eq --TODO: Fix it and kill `Eq.subset` alias Eq.superset := superset_of_eq alias HasSubset.Subset.trans := subset_trans alias HasSubset.Subset.antisymm := subset_antisymm alias HasSubset.Subset.antisymm' := superset_antisymm theorem subset_antisymm_iff [IsRefl α (· ⊆ ·)] [IsAntisymm α (· ⊆ ·)] : a = b ↔ a ⊆ b ∧ b ⊆ a := ⟨fun h => ⟨h.subset', h.superset⟩, fun h => h.1.antisymm h.2⟩ theorem superset_antisymm_iff [IsRefl α (· ⊆ ·)] [IsAntisymm α (· ⊆ ·)] : a = b ↔ b ⊆ a ∧ a ⊆ b := ⟨fun h => ⟨h.superset, h.subset'⟩, fun h => h.1.antisymm' h.2⟩ end Subset section Ssubset variable [HasSSubset α] {a b c : α} lemma ssubset_of_eq_of_ssubset (hab : a = b) (hbc : b ⊂ c) : a ⊂ c := by rwa [hab] lemma ssubset_of_ssubset_of_eq (hab : a ⊂ b) (hbc : b = c) : a ⊂ c := by rwa [← hbc] lemma ssubset_irrefl [IsIrrefl α (· ⊂ ·)] (a : α) : ¬a ⊂ a := irrefl _ lemma ssubset_irrfl [IsIrrefl α (· ⊂ ·)] {a : α} : ¬a ⊂ a := irrefl _ lemma ne_of_ssubset [IsIrrefl α (· ⊂ ·)] {a b : α} : a ⊂ b → a ≠ b := ne_of_irrefl lemma ne_of_ssuperset [IsIrrefl α (· ⊂ ·)] {a b : α} : a ⊂ b → b ≠ a := ne_of_irrefl' @[trans] lemma ssubset_trans [IsTrans α (· ⊂ ·)] {a b c : α} : a ⊂ b → b ⊂ c → a ⊂ c := _root_.trans lemma ssubset_asymm [IsAsymm α (· ⊂ ·)] {a b : α} : a ⊂ b → ¬b ⊂ a := asymm alias Eq.trans_ssubset := ssubset_of_eq_of_ssubset alias HasSSubset.SSubset.trans_eq := ssubset_of_ssubset_of_eq alias HasSSubset.SSubset.false := ssubset_irrfl alias HasSSubset.SSubset.ne := ne_of_ssubset alias HasSSubset.SSubset.ne' := ne_of_ssuperset alias HasSSubset.SSubset.trans := ssubset_trans alias HasSSubset.SSubset.asymm := ssubset_asymm end Ssubset section SubsetSsubset variable [HasSubset α] [HasSSubset α] [IsNonstrictStrictOrder α (· ⊆ ·) (· ⊂ ·)] {a b c : α} theorem ssubset_iff_subset_not_subset : a ⊂ b ↔ a ⊆ b ∧ ¬b ⊆ a := right_iff_left_not_left theorem subset_of_ssubset (h : a ⊂ b) : a ⊆ b := (ssubset_iff_subset_not_subset.1 h).1 theorem not_subset_of_ssubset (h : a ⊂ b) : ¬b ⊆ a := (ssubset_iff_subset_not_subset.1 h).2 theorem not_ssubset_of_subset (h : a ⊆ b) : ¬b ⊂ a := fun h' => not_subset_of_ssubset h' h theorem ssubset_of_subset_not_subset (h₁ : a ⊆ b) (h₂ : ¬b ⊆ a) : a ⊂ b := ssubset_iff_subset_not_subset.2 ⟨h₁, h₂⟩ alias HasSSubset.SSubset.subset := subset_of_ssubset alias HasSSubset.SSubset.not_subset := not_subset_of_ssubset alias HasSubset.Subset.not_ssubset := not_ssubset_of_subset alias HasSubset.Subset.ssubset_of_not_subset := ssubset_of_subset_not_subset theorem ssubset_of_subset_of_ssubset [IsTrans α (· ⊆ ·)] (h₁ : a ⊆ b) (h₂ : b ⊂ c) : a ⊂ c := (h₁.trans h₂.subset).ssubset_of_not_subset fun h => h₂.not_subset <| h.trans h₁ theorem ssubset_of_ssubset_of_subset [IsTrans α (· ⊆ ·)] (h₁ : a ⊂ b) (h₂ : b ⊆ c) : a ⊂ c := (h₁.subset.trans h₂).ssubset_of_not_subset fun h => h₁.not_subset <| h₂.trans h theorem ssubset_of_subset_of_ne [IsAntisymm α (· ⊆ ·)] (h₁ : a ⊆ b) (h₂ : a ≠ b) : a ⊂ b := h₁.ssubset_of_not_subset <| mt h₁.antisymm h₂ theorem ssubset_of_ne_of_subset [IsAntisymm α (· ⊆ ·)] (h₁ : a ≠ b) (h₂ : a ⊆ b) : a ⊂ b := ssubset_of_subset_of_ne h₂ h₁ theorem eq_or_ssubset_of_subset [IsAntisymm α (· ⊆ ·)] (h : a ⊆ b) : a = b ∨ a ⊂ b := (em (b ⊆ a)).imp h.antisymm h.ssubset_of_not_subset theorem ssubset_or_eq_of_subset [IsAntisymm α (· ⊆ ·)] (h : a ⊆ b) : a ⊂ b ∨ a = b := (eq_or_ssubset_of_subset h).symm lemma eq_of_subset_of_not_ssubset [IsAntisymm α (· ⊆ ·)] (hab : a ⊆ b) (hba : ¬ a ⊂ b) : a = b := (eq_or_ssubset_of_subset hab).resolve_right hba lemma eq_of_superset_of_not_ssuperset [IsAntisymm α (· ⊆ ·)] (hab : a ⊆ b) (hba : ¬ a ⊂ b) : b = a := ((eq_or_ssubset_of_subset hab).resolve_right hba).symm alias HasSubset.Subset.trans_ssubset := ssubset_of_subset_of_ssubset alias HasSSubset.SSubset.trans_subset := ssubset_of_ssubset_of_subset alias HasSubset.Subset.ssubset_of_ne := ssubset_of_subset_of_ne alias Ne.ssubset_of_subset := ssubset_of_ne_of_subset alias HasSubset.Subset.eq_or_ssubset := eq_or_ssubset_of_subset alias HasSubset.Subset.ssubset_or_eq := ssubset_or_eq_of_subset alias HasSubset.Subset.eq_of_not_ssubset := eq_of_subset_of_not_ssubset alias HasSubset.Subset.eq_of_not_ssuperset := eq_of_superset_of_not_ssuperset theorem ssubset_iff_subset_ne [IsAntisymm α (· ⊆ ·)] : a ⊂ b ↔ a ⊆ b ∧ a ≠ b := ⟨fun h => ⟨h.subset, h.ne⟩, fun h => h.1.ssubset_of_ne h.2⟩ theorem subset_iff_ssubset_or_eq [IsRefl α (· ⊆ ·)] [IsAntisymm α (· ⊆ ·)] : a ⊆ b ↔ a ⊂ b ∨ a = b := ⟨fun h => h.ssubset_or_eq, fun h => h.elim subset_of_ssubset subset_of_eq⟩ namespace GCongr variable [IsTrans α (· ⊆ ·)] {a b c d : α} @[gcongr] theorem ssubset_imp_ssubset (h₁ : c ⊆ a) (h₂ : b ⊆ d) : a ⊂ b → c ⊂ d := fun h => (h₁.trans_ssubset h).trans_subset h₂ @[gcongr] theorem ssuperset_imp_ssuperset (h₁ : a ⊆ c) (h₂ : d ⊆ b) : a ⊃ b → c ⊃ d := ssubset_imp_ssubset h₂ h₁ /-- See if the term is `a ⊂ b` and the goal is `a ⊆ b`. -/ @[gcongr_forward] def exactSubsetOfSSubset : Mathlib.Tactic.GCongr.ForwardExt where eval h goal := do goal.assignIfDefEq (← Lean.Meta.mkAppM ``subset_of_ssubset #[h]) end GCongr end SubsetSsubset /-! ### Conversion of bundled order typeclasses to unbundled relation typeclasses -/ instance [Preorder α] : IsRefl α (· ≤ ·) := ⟨le_refl⟩ instance [Preorder α] : IsRefl α (· ≥ ·) := IsRefl.swap _ instance [Preorder α] : IsTrans α (· ≤ ·) := ⟨@le_trans _ _⟩ instance [Preorder α] : IsTrans α (· ≥ ·) := IsTrans.swap _ instance [Preorder α] : IsPreorder α (· ≤ ·) where instance [Preorder α] : IsPreorder α (· ≥ ·) where instance [Preorder α] : IsIrrefl α (· < ·) := ⟨lt_irrefl⟩ instance [Preorder α] : IsIrrefl α (· > ·) := IsIrrefl.swap _ instance [Preorder α] : IsTrans α (· < ·) := ⟨@lt_trans _ _⟩ instance [Preorder α] : IsTrans α (· > ·) := IsTrans.swap _ instance [Preorder α] : IsAsymm α (· < ·) := ⟨@lt_asymm _ _⟩ instance [Preorder α] : IsAsymm α (· > ·) := IsAsymm.swap _ instance [Preorder α] : IsAntisymm α (· < ·) := IsAsymm.isAntisymm _ instance [Preorder α] : IsAntisymm α (· > ·) := IsAsymm.isAntisymm _ instance [Preorder α] : IsStrictOrder α (· < ·) where instance [Preorder α] : IsStrictOrder α (· > ·) where instance [Preorder α] : IsNonstrictStrictOrder α (· ≤ ·) (· < ·) := ⟨@lt_iff_le_not_ge _ _⟩ instance [PartialOrder α] : IsAntisymm α (· ≤ ·) := ⟨@le_antisymm _ _⟩ instance [PartialOrder α] : IsAntisymm α (· ≥ ·) := IsAntisymm.swap _ instance [PartialOrder α] : IsPartialOrder α (· ≤ ·) where instance [PartialOrder α] : IsPartialOrder α (· ≥ ·) where instance LE.isTotal [LinearOrder α] : IsTotal α (· ≤ ·) := ⟨le_total⟩ instance [LinearOrder α] : IsTotal α (· ≥ ·) := IsTotal.swap _ instance [LinearOrder α] : IsLinearOrder α (· ≤ ·) where instance [LinearOrder α] : IsLinearOrder α (· ≥ ·) where instance [LinearOrder α] : IsTrichotomous α (· < ·) := ⟨lt_trichotomy⟩ instance [LinearOrder α] : IsTrichotomous α (· > ·) := IsTrichotomous.swap _ instance [LinearOrder α] : IsTrichotomous α (· ≤ ·) := IsTotal.isTrichotomous _ instance [LinearOrder α] : IsTrichotomous α (· ≥ ·) := IsTotal.isTrichotomous _ instance [LinearOrder α] : IsStrictTotalOrder α (· < ·) where instance [LinearOrder α] : IsOrderConnected α (· < ·) := by infer_instance theorem transitive_le [Preorder α] : Transitive (@LE.le α _) := transitive_of_trans _ theorem transitive_lt [Preorder α] : Transitive (@LT.lt α _) := transitive_of_trans _ theorem transitive_ge [Preorder α] : Transitive (@GE.ge α _) := transitive_of_trans _ theorem transitive_gt [Preorder α] : Transitive (@GT.gt α _) := transitive_of_trans _ instance OrderDual.isTotal_le [LE α] [h : IsTotal α (· ≤ ·)] : IsTotal αᵒᵈ (· ≤ ·) := @IsTotal.swap α _ h instance : WellFoundedLT ℕ := ⟨Nat.lt_wfRel.wf⟩ instance (priority := 100) isWellOrder_lt [LinearOrder α] [WellFoundedLT α] : IsWellOrder α (· < ·) where instance (priority := 100) isWellOrder_gt [LinearOrder α] [WellFoundedGT α] : IsWellOrder α (· > ·) where
.lake/packages/mathlib/Mathlib/Order/Minimal.lean
import Mathlib.Order.Hom.Basic import Mathlib.Order.Interval.Set.Defs import Mathlib.Order.WellFounded /-! # Minimality and Maximality This file proves basic facts about minimality and maximality of an element with respect to a predicate `P` on an ordered type `α`. ## Implementation Details This file underwent a refactor from a version where minimality and maximality were defined using sets rather than predicates, and with an unbundled order relation rather than a `LE` instance. A side effect is that it has become less straightforward to state that something is minimal with respect to a relation that is *not* defeq to the default `LE`. One possible way would be with a type synonym, and another would be with an ad hoc `LE` instance and `@` notation. This was not an issue in practice anywhere in mathlib at the time of the refactor, but it may be worth re-examining this to make it easier in the future; see the TODO below. ## TODO * In the linearly ordered case, versions of lemmas like `minimal_mem_image` will hold with `MonotoneOn`/`AntitoneOn` assumptions rather than the stronger `x ≤ y ↔ f x ≤ f y` assumptions. * `Set.maximal_iff_forall_insert` and `Set.minimal_iff_forall_diff_singleton` will generalize to lemmas about covering in the case of an `IsStronglyAtomic`/`IsStronglyCoatomic` order. * `Finset` versions of the lemmas about sets. * API to allow for easily expressing min/maximality with respect to an arbitrary non-`LE` relation. * API for `MinimalFor`/`MaximalFor` -/ assert_not_exists CompleteLattice open Set OrderDual variable {ι α : Type*} section LE variable [LE α] {f : ι → α} {i j : ι} @[simp] lemma minimalFor_eq_iff : MinimalFor (· = j) f i ↔ i = j := by simp +contextual [MinimalFor] @[simp] lemma maximalFor_eq_iff : MaximalFor (· = j) f i ↔ i = j := by simp +contextual [MaximalFor] end LE variable {P Q : α → Prop} {a x y : α} section LE variable [LE α] @[simp] lemma minimalFor_id : MinimalFor P id x ↔ Minimal P x := .rfl @[simp] lemma maximalFor_id : MaximalFor P id x ↔ Maximal P x := .rfl @[simp] theorem minimal_toDual : Minimal (fun x ↦ P (ofDual x)) (toDual x) ↔ Maximal P x := Iff.rfl alias ⟨Minimal.of_dual, Minimal.dual⟩ := minimal_toDual @[simp] theorem maximal_toDual : Maximal (fun x ↦ P (ofDual x)) (toDual x) ↔ Minimal P x := Iff.rfl alias ⟨Maximal.of_dual, Maximal.dual⟩ := maximal_toDual @[simp] theorem minimal_false : ¬ Minimal (fun _ ↦ False) x := by simp [Minimal] @[simp] theorem maximal_false : ¬ Maximal (fun _ ↦ False) x := by simp [Maximal] @[simp] theorem minimal_true : Minimal (fun _ ↦ True) x ↔ IsMin x := by simp [IsMin, Minimal] @[simp] theorem maximal_true : Maximal (fun _ ↦ True) x ↔ IsMax x := minimal_true (α := αᵒᵈ) @[simp] theorem minimal_subtype {x : Subtype Q} : Minimal (fun x ↦ P x.1) x ↔ Minimal (P ⊓ Q) x := by obtain ⟨x, hx⟩ := x simp only [Minimal, Subtype.forall, Subtype.mk_le_mk, Pi.inf_apply, inf_Prop_eq] tauto @[simp] theorem maximal_subtype {x : Subtype Q} : Maximal (fun x ↦ P x.1) x ↔ Maximal (P ⊓ Q) x := minimal_subtype (α := αᵒᵈ) theorem maximal_true_subtype {x : Subtype P} : Maximal (fun _ ↦ True) x ↔ Maximal P x := by obtain ⟨x, hx⟩ := x simp [Maximal, hx] theorem minimal_true_subtype {x : Subtype P} : Minimal (fun _ ↦ True) x ↔ Minimal P x := by obtain ⟨x, hx⟩ := x simp [Minimal, hx] @[simp] theorem minimal_minimal : Minimal (Minimal P) x ↔ Minimal P x := ⟨fun h ↦ h.prop, fun h ↦ ⟨h, fun _ hy hyx ↦ h.le_of_le hy.prop hyx⟩⟩ @[simp] theorem maximal_maximal : Maximal (Maximal P) x ↔ Maximal P x := minimal_minimal (α := αᵒᵈ) /-- If `P` is down-closed, then minimal elements satisfying `P` are exactly the globally minimal elements satisfying `P`. -/ theorem minimal_iff_isMin (hP : ∀ ⦃x y⦄, P y → x ≤ y → P x) : Minimal P x ↔ P x ∧ IsMin x := ⟨fun h ↦ ⟨h.prop, fun _ h' ↦ h.le_of_le (hP h.prop h') h'⟩, fun h ↦ ⟨h.1, fun _ _ h' ↦ h.2 h'⟩⟩ /-- If `P` is up-closed, then maximal elements satisfying `P` are exactly the globally maximal elements satisfying `P`. -/ theorem maximal_iff_isMax (hP : ∀ ⦃x y⦄, P y → y ≤ x → P x) : Maximal P x ↔ P x ∧ IsMax x := ⟨fun h ↦ ⟨h.prop, fun _ h' ↦ h.le_of_ge (hP h.prop h') h'⟩, fun h ↦ ⟨h.1, fun _ _ h' ↦ h.2 h'⟩⟩ theorem Minimal.mono (h : Minimal P x) (hle : Q ≤ P) (hQ : Q x) : Minimal Q x := ⟨hQ, fun y hQy ↦ h.le_of_le (hle y hQy)⟩ theorem Maximal.mono (h : Maximal P x) (hle : Q ≤ P) (hQ : Q x) : Maximal Q x := ⟨hQ, fun y hQy ↦ h.le_of_ge (hle y hQy)⟩ theorem Minimal.and_right (h : Minimal P x) (hQ : Q x) : Minimal (fun x ↦ P x ∧ Q x) x := h.mono (fun _ ↦ And.left) ⟨h.prop, hQ⟩ theorem Minimal.and_left (h : Minimal P x) (hQ : Q x) : Minimal (fun x ↦ (Q x ∧ P x)) x := h.mono (fun _ ↦ And.right) ⟨hQ, h.prop⟩ theorem Maximal.and_right (h : Maximal P x) (hQ : Q x) : Maximal (fun x ↦ (P x ∧ Q x)) x := h.mono (fun _ ↦ And.left) ⟨h.prop, hQ⟩ theorem Maximal.and_left (h : Maximal P x) (hQ : Q x) : Maximal (fun x ↦ (Q x ∧ P x)) x := h.mono (fun _ ↦ And.right) ⟨hQ, h.prop⟩ @[simp] theorem minimal_eq_iff : Minimal (· = y) x ↔ x = y := by simp +contextual [Minimal] @[simp] theorem maximal_eq_iff : Maximal (· = y) x ↔ x = y := by simp +contextual [Maximal] theorem not_minimal_iff (hx : P x) : ¬ Minimal P x ↔ ∃ y, P y ∧ y ≤ x ∧ ¬ (x ≤ y) := by simp [Minimal, hx] theorem not_maximal_iff (hx : P x) : ¬ Maximal P x ↔ ∃ y, P y ∧ x ≤ y ∧ ¬ (y ≤ x) := not_minimal_iff (α := αᵒᵈ) hx theorem Minimal.or (h : Minimal (fun x ↦ P x ∨ Q x) x) : Minimal P x ∨ Minimal Q x := by obtain ⟨h | h, hmin⟩ := h · exact .inl ⟨h, fun y hy hyx ↦ hmin (Or.inl hy) hyx⟩ exact .inr ⟨h, fun y hy hyx ↦ hmin (Or.inr hy) hyx⟩ theorem Maximal.or (h : Maximal (fun x ↦ P x ∨ Q x) x) : Maximal P x ∨ Maximal Q x := Minimal.or (α := αᵒᵈ) h theorem minimal_and_iff_right_of_imp (hPQ : ∀ ⦃x⦄, P x → Q x) : Minimal (fun x ↦ P x ∧ Q x) x ↔ (Minimal P x) ∧ Q x := by simp_rw [and_iff_left_of_imp (fun x ↦ hPQ x), iff_self_and] exact fun h ↦ hPQ h.prop theorem minimal_and_iff_left_of_imp (hPQ : ∀ ⦃x⦄, P x → Q x) : Minimal (fun x ↦ Q x ∧ P x) x ↔ Q x ∧ (Minimal P x) := by simp_rw [iff_comm, and_comm, minimal_and_iff_right_of_imp hPQ, and_comm] theorem maximal_and_iff_right_of_imp (hPQ : ∀ ⦃x⦄, P x → Q x) : Maximal (fun x ↦ P x ∧ Q x) x ↔ (Maximal P x) ∧ Q x := minimal_and_iff_right_of_imp (α := αᵒᵈ) hPQ theorem maximal_and_iff_left_of_imp (hPQ : ∀ ⦃x⦄, P x → Q x) : Maximal (fun x ↦ Q x ∧ P x) x ↔ Q x ∧ (Maximal P x) := minimal_and_iff_left_of_imp (α := αᵒᵈ) hPQ end LE section Preorder variable [Preorder α] theorem minimal_iff_forall_lt : Minimal P x ↔ P x ∧ ∀ ⦃y⦄, y < x → ¬ P y := by simp [Minimal, lt_iff_le_not_ge, imp.swap] theorem maximal_iff_forall_gt : Maximal P x ↔ P x ∧ ∀ ⦃y⦄, x < y → ¬ P y := minimal_iff_forall_lt (α := αᵒᵈ) theorem Minimal.not_prop_of_lt (h : Minimal P x) (hlt : y < x) : ¬ P y := (minimal_iff_forall_lt.1 h).2 hlt theorem Maximal.not_prop_of_gt (h : Maximal P x) (hlt : x < y) : ¬ P y := (maximal_iff_forall_gt.1 h).2 hlt theorem Minimal.not_lt (h : Minimal P x) (hy : P y) : ¬(y < x) := fun hlt ↦ h.not_prop_of_lt hlt hy theorem Maximal.not_gt (h : Maximal P x) (hy : P y) : ¬(x < y) := fun hlt ↦ h.not_prop_of_gt hlt hy @[simp] theorem minimal_le_iff : Minimal (· ≤ y) x ↔ x ≤ y ∧ IsMin x := minimal_iff_isMin (fun _ _ h h' ↦ h'.trans h) @[simp] theorem maximal_ge_iff : Maximal (y ≤ ·) x ↔ y ≤ x ∧ IsMax x := minimal_le_iff (α := αᵒᵈ) @[simp] theorem minimal_lt_iff : Minimal (· < y) x ↔ x < y ∧ IsMin x := minimal_iff_isMin (fun _ _ h h' ↦ h'.trans_lt h) @[simp] theorem maximal_gt_iff : Maximal (y < ·) x ↔ y < x ∧ IsMax x := minimal_lt_iff (α := αᵒᵈ) theorem not_minimal_iff_exists_lt (hx : P x) : ¬ Minimal P x ↔ ∃ y, y < x ∧ P y := by simp_rw [not_minimal_iff hx, lt_iff_le_not_ge, and_comm] alias ⟨exists_lt_of_not_minimal, _⟩ := not_minimal_iff_exists_lt theorem not_maximal_iff_exists_gt (hx : P x) : ¬ Maximal P x ↔ ∃ y, x < y ∧ P y := not_minimal_iff_exists_lt (α := αᵒᵈ) hx alias ⟨exists_gt_of_not_maximal, _⟩ := not_maximal_iff_exists_gt section WellFoundedLT variable [WellFoundedLT α] lemma exists_minimalFor_of_wellFoundedLT (P : ι → Prop) (f : ι → α) (hP : ∃ i, P i) : ∃ i, MinimalFor P f i := by simpa [not_lt_iff_le_imp_ge, InvImage] using (instIsWellFoundedInvImage (· < ·) f).wf.has_min _ hP lemma exists_minimal_of_wellFoundedLT (P : α → Prop) (hP : ∃ a, P a) : ∃ a, Minimal P a := exists_minimalFor_of_wellFoundedLT P id hP lemma exists_minimal_le_of_wellFoundedLT (P : α → Prop) (a : α) (ha : P a) : ∃ b ≤ a, Minimal P b := by obtain ⟨b, ⟨hba, hb⟩, hbmin⟩ := exists_minimal_of_wellFoundedLT (fun b ↦ b ≤ a ∧ P b) ⟨a, le_rfl, ha⟩ exact ⟨b, hba, hb, fun c hc hcb ↦ hbmin ⟨hcb.trans hba, hc⟩ hcb⟩ end WellFoundedLT section WellFoundedGT variable [WellFoundedGT α] lemma exists_maximalFor_of_wellFoundedGT (P : ι → Prop) (f : ι → α) (hP : ∃ i, P i) : ∃ i, MaximalFor P f i := exists_minimalFor_of_wellFoundedLT (α := αᵒᵈ) P f hP lemma exists_maximal_of_wellFoundedGT (P : α → Prop) (hP : ∃ a, P a) : ∃ a, Maximal P a := exists_minimal_of_wellFoundedLT (α := αᵒᵈ) P hP lemma exists_maximal_ge_of_wellFoundedGT (P : α → Prop) (a : α) (ha : P a) : ∃ b, a ≤ b ∧ Maximal P b := exists_minimal_le_of_wellFoundedLT (α := αᵒᵈ) P a ha end WellFoundedGT end Preorder section PartialOrder variable [PartialOrder α] theorem Minimal.eq_of_ge (hx : Minimal P x) (hy : P y) (hge : y ≤ x) : x = y := (hx.2 hy hge).antisymm hge theorem Minimal.eq_of_le (hx : Minimal P x) (hy : P y) (hle : y ≤ x) : y = x := (hx.eq_of_ge hy hle).symm theorem Maximal.eq_of_le (hx : Maximal P x) (hy : P y) (hle : x ≤ y) : x = y := hle.antisymm <| hx.2 hy hle theorem Maximal.eq_of_ge (hx : Maximal P x) (hy : P y) (hge : x ≤ y) : y = x := (hx.eq_of_le hy hge).symm theorem minimal_iff : Minimal P x ↔ P x ∧ ∀ ⦃y⦄, P y → y ≤ x → x = y := ⟨fun h ↦ ⟨h.1, fun _ ↦ h.eq_of_ge⟩, fun h ↦ ⟨h.1, fun _ hy hle ↦ (h.2 hy hle).le⟩⟩ theorem maximal_iff : Maximal P x ↔ P x ∧ ∀ ⦃y⦄, P y → x ≤ y → x = y := minimal_iff (α := αᵒᵈ) theorem minimal_mem_iff {s : Set α} : Minimal (· ∈ s) x ↔ x ∈ s ∧ ∀ ⦃y⦄, y ∈ s → y ≤ x → x = y := minimal_iff theorem maximal_mem_iff {s : Set α} : Maximal (· ∈ s) x ↔ x ∈ s ∧ ∀ ⦃y⦄, y ∈ s → x ≤ y → x = y := maximal_iff /-- If `P y` holds, and everything satisfying `P` is above `y`, then `y` is the unique minimal element satisfying `P`. -/ theorem minimal_iff_eq (hy : P y) (hP : ∀ ⦃x⦄, P x → y ≤ x) : Minimal P x ↔ x = y := ⟨fun h ↦ h.eq_of_ge hy (hP h.prop), by rintro rfl; exact ⟨hy, fun z hz _ ↦ hP hz⟩⟩ /-- If `P y` holds, and everything satisfying `P` is below `y`, then `y` is the unique maximal element satisfying `P`. -/ theorem maximal_iff_eq (hy : P y) (hP : ∀ ⦃x⦄, P x → x ≤ y) : Maximal P x ↔ x = y := minimal_iff_eq (α := αᵒᵈ) hy hP @[simp] theorem minimal_ge_iff : Minimal (y ≤ ·) x ↔ x = y := minimal_iff_eq rfl.le fun _ ↦ id @[simp] theorem maximal_le_iff : Maximal (· ≤ y) x ↔ x = y := maximal_iff_eq rfl.le fun _ ↦ id theorem minimal_iff_minimal_of_imp_of_forall (hPQ : ∀ ⦃x⦄, Q x → P x) (h : ∀ ⦃x⦄, P x → ∃ y, y ≤ x ∧ Q y) : Minimal P x ↔ Minimal Q x := by refine ⟨fun h' ↦ ⟨?_, fun y hy hyx ↦ h'.le_of_le (hPQ hy) hyx⟩, fun h' ↦ ⟨hPQ h'.prop, fun y hy hyx ↦ ?_⟩⟩ · obtain ⟨y, hyx, hy⟩ := h h'.prop rwa [((h'.le_of_le (hPQ hy)) hyx).antisymm hyx] obtain ⟨z, hzy, hz⟩ := h hy exact (h'.le_of_le hz (hzy.trans hyx)).trans hzy theorem maximal_iff_maximal_of_imp_of_forall (hPQ : ∀ ⦃x⦄, Q x → P x) (h : ∀ ⦃x⦄, P x → ∃ y, x ≤ y ∧ Q y) : Maximal P x ↔ Maximal Q x := minimal_iff_minimal_of_imp_of_forall (α := αᵒᵈ) hPQ h end PartialOrder section Subset variable {P : Set α → Prop} {s t : Set α} theorem Minimal.eq_of_superset (h : Minimal P s) (ht : P t) (hts : t ⊆ s) : s = t := h.eq_of_ge ht hts theorem Maximal.eq_of_subset (h : Maximal P s) (ht : P t) (hst : s ⊆ t) : s = t := h.eq_of_le ht hst theorem Minimal.eq_of_subset (h : Minimal P s) (ht : P t) (hts : t ⊆ s) : t = s := h.eq_of_le ht hts theorem Maximal.eq_of_superset (h : Maximal P s) (ht : P t) (hst : s ⊆ t) : t = s := h.eq_of_ge ht hst theorem minimal_subset_iff : Minimal P s ↔ P s ∧ ∀ ⦃t⦄, P t → t ⊆ s → s = t := _root_.minimal_iff theorem maximal_subset_iff : Maximal P s ↔ P s ∧ ∀ ⦃t⦄, P t → s ⊆ t → s = t := _root_.maximal_iff theorem minimal_subset_iff' : Minimal P s ↔ P s ∧ ∀ ⦃t⦄, P t → t ⊆ s → s ⊆ t := Iff.rfl theorem maximal_subset_iff' : Maximal P s ↔ P s ∧ ∀ ⦃t⦄, P t → s ⊆ t → t ⊆ s := Iff.rfl theorem not_minimal_subset_iff (hs : P s) : ¬ Minimal P s ↔ ∃ t, t ⊂ s ∧ P t := not_minimal_iff_exists_lt hs theorem not_maximal_subset_iff (hs : P s) : ¬ Maximal P s ↔ ∃ t, s ⊂ t ∧ P t := not_maximal_iff_exists_gt hs theorem Set.minimal_iff_forall_ssubset : Minimal P s ↔ P s ∧ ∀ ⦃t⦄, t ⊂ s → ¬ P t := minimal_iff_forall_lt theorem Minimal.not_prop_of_ssubset (h : Minimal P s) (ht : t ⊂ s) : ¬ P t := (minimal_iff_forall_lt.1 h).2 ht theorem Minimal.not_ssubset (h : Minimal P s) (ht : P t) : ¬ t ⊂ s := h.not_lt ht theorem Maximal.mem_of_prop_insert (h : Maximal P s) (hx : P (insert x s)) : x ∈ s := h.eq_of_subset hx (subset_insert _ _) ▸ mem_insert .. theorem Minimal.notMem_of_prop_diff_singleton (h : Minimal P s) (hx : P (s \ {x})) : x ∉ s := fun hxs ↦ ((h.eq_of_superset hx diff_subset).subset hxs).2 rfl @[deprecated (since := "2025-05-23")] alias Minimal.not_mem_of_prop_diff_singleton := Minimal.notMem_of_prop_diff_singleton theorem Set.minimal_iff_forall_diff_singleton (hP : ∀ ⦃s t⦄, P t → t ⊆ s → P s) : Minimal P s ↔ P s ∧ ∀ x ∈ s, ¬ P (s \ {x}) := ⟨fun h ↦ ⟨h.1, fun _ hx hP ↦ h.notMem_of_prop_diff_singleton hP hx⟩, fun h ↦ ⟨h.1, fun _ ht hts x hxs ↦ by_contra fun hxt ↦ h.2 x hxs (hP ht <| subset_diff_singleton hts hxt)⟩⟩ theorem Set.exists_diff_singleton_of_not_minimal (hP : ∀ ⦃s t⦄, P t → t ⊆ s → P s) (hs : P s) (h : ¬ Minimal P s) : ∃ x ∈ s, P (s \ {x}) := by simpa [Set.minimal_iff_forall_diff_singleton hP, hs] using h theorem Set.maximal_iff_forall_ssuperset : Maximal P s ↔ P s ∧ ∀ ⦃t⦄, s ⊂ t → ¬ P t := maximal_iff_forall_gt theorem Maximal.not_prop_of_ssuperset (h : Maximal P s) (ht : s ⊂ t) : ¬ P t := (maximal_iff_forall_gt.1 h).2 ht theorem Maximal.not_ssuperset (h : Maximal P s) (ht : P t) : ¬ s ⊂ t := h.not_gt ht theorem Set.maximal_iff_forall_insert (hP : ∀ ⦃s t⦄, P t → s ⊆ t → P s) : Maximal P s ↔ P s ∧ ∀ x ∉ s, ¬ P (insert x s) := by simp only [not_imp_not] exact ⟨fun h ↦ ⟨h.1, fun x ↦ h.mem_of_prop_insert⟩, fun h ↦ ⟨h.1, fun t ht hst x hxt ↦ h.2 x (hP ht <| insert_subset hxt hst)⟩⟩ theorem Set.exists_insert_of_not_maximal (hP : ∀ ⦃s t⦄, P t → s ⊆ t → P s) (hs : P s) (h : ¬ Maximal P s) : ∃ x ∉ s, P (insert x s) := by simpa [Set.maximal_iff_forall_insert hP, hs] using h /- TODO : generalize `minimal_iff_forall_diff_singleton` and `maximal_iff_forall_insert` to `IsStronglyCoatomic`/`IsStronglyAtomic` orders. -/ end Subset section Set variable {s t : Set α} section Preorder variable [Preorder α] theorem setOf_minimal_subset (s : Set α) : {x | Minimal (· ∈ s) x} ⊆ s := sep_subset .. theorem setOf_maximal_subset (s : Set α) : {x | Maximal (· ∈ s) x} ⊆ s := sep_subset .. theorem Set.Subsingleton.maximal_mem_iff (h : s.Subsingleton) : Maximal (· ∈ s) x ↔ x ∈ s := by obtain (rfl | ⟨x, rfl⟩) := h.eq_empty_or_singleton <;> simp theorem Set.Subsingleton.minimal_mem_iff (h : s.Subsingleton) : Minimal (· ∈ s) x ↔ x ∈ s := by obtain (rfl | ⟨x, rfl⟩) := h.eq_empty_or_singleton <;> simp theorem IsLeast.minimal (h : IsLeast s x) : Minimal (· ∈ s) x := ⟨h.1, fun _b hb _ ↦ h.2 hb⟩ theorem IsGreatest.maximal (h : IsGreatest s x) : Maximal (· ∈ s) x := ⟨h.1, fun _b hb _ ↦ h.2 hb⟩ end Preorder section PartialOrder variable [PartialOrder α] theorem IsLeast.minimal_iff (h : IsLeast s a) : Minimal (· ∈ s) x ↔ x = a := ⟨fun h' ↦ h'.eq_of_ge h.1 (h.2 h'.prop), fun h' ↦ h' ▸ h.minimal⟩ theorem IsGreatest.maximal_iff (h : IsGreatest s a) : Maximal (· ∈ s) x ↔ x = a := ⟨fun h' ↦ h'.eq_of_le h.1 (h.2 h'.prop), fun h' ↦ h' ▸ h.maximal⟩ end PartialOrder end Set section Image variable [Preorder α] {β : Type*} [Preorder β] {s : Set α} {t : Set β} section Function variable {f : α → β} theorem minimal_mem_image_monotone (hf : ∀ ⦃x y⦄, x ∈ s → y ∈ s → (f x ≤ f y ↔ x ≤ y)) (hx : Minimal (· ∈ s) x) : Minimal (· ∈ f '' s) (f x) := by refine ⟨mem_image_of_mem f hx.prop, ?_⟩ rintro _ ⟨y, hy, rfl⟩ rw [hf hx.prop hy, hf hy hx.prop] exact hx.le_of_le hy theorem maximal_mem_image_monotone (hf : ∀ ⦃x y⦄, x ∈ s → y ∈ s → (f x ≤ f y ↔ x ≤ y)) (hx : Maximal (· ∈ s) x) : Maximal (· ∈ f '' s) (f x) := minimal_mem_image_monotone (α := αᵒᵈ) (β := βᵒᵈ) (s := s) (fun _ _ hx hy ↦ hf hy hx) hx theorem minimal_mem_image_monotone_iff (ha : a ∈ s) (hf : ∀ ⦃x y⦄, x ∈ s → y ∈ s → (f x ≤ f y ↔ x ≤ y)) : Minimal (· ∈ f '' s) (f a) ↔ Minimal (· ∈ s) a := by refine ⟨fun h ↦ ⟨ha, fun y hys ↦ ?_⟩, minimal_mem_image_monotone hf⟩ rw [← hf ha hys, ← hf hys ha] exact h.le_of_le (mem_image_of_mem f hys) theorem maximal_mem_image_monotone_iff (ha : a ∈ s) (hf : ∀ ⦃x y⦄, x ∈ s → y ∈ s → (f x ≤ f y ↔ x ≤ y)) : Maximal (· ∈ f '' s) (f a) ↔ Maximal (· ∈ s) a := minimal_mem_image_monotone_iff (α := αᵒᵈ) (β := βᵒᵈ) (s := s) ha fun _ _ hx hy ↦ hf hy hx theorem minimal_mem_image_antitone (hf : ∀ ⦃x y⦄, x ∈ s → y ∈ s → (f x ≤ f y ↔ y ≤ x)) (hx : Minimal (· ∈ s) x) : Maximal (· ∈ f '' s) (f x) := minimal_mem_image_monotone (β := βᵒᵈ) (fun _ _ h h' ↦ hf h' h) hx theorem maximal_mem_image_antitone (hf : ∀ ⦃x y⦄, x ∈ s → y ∈ s → (f x ≤ f y ↔ y ≤ x)) (hx : Maximal (· ∈ s) x) : Minimal (· ∈ f '' s) (f x) := maximal_mem_image_monotone (β := βᵒᵈ) (fun _ _ h h' ↦ hf h' h) hx theorem minimal_mem_image_antitone_iff (ha : a ∈ s) (hf : ∀ ⦃x y⦄, x ∈ s → y ∈ s → (f x ≤ f y ↔ y ≤ x)) : Minimal (· ∈ f '' s) (f a) ↔ Maximal (· ∈ s) a := maximal_mem_image_monotone_iff (β := βᵒᵈ) ha (fun _ _ h h' ↦ hf h' h) theorem maximal_mem_image_antitone_iff (ha : a ∈ s) (hf : ∀ ⦃x y⦄, x ∈ s → y ∈ s → (f x ≤ f y ↔ y ≤ x)) : Maximal (· ∈ f '' s) (f a) ↔ Minimal (· ∈ s) a := minimal_mem_image_monotone_iff (β := βᵒᵈ) ha (fun _ _ h h' ↦ hf h' h) theorem image_monotone_setOf_minimal (hf : ∀ ⦃x y⦄, P x → P y → (f x ≤ f y ↔ x ≤ y)) : f '' {x | Minimal P x} = {x | Minimal (∃ x₀, P x₀ ∧ f x₀ = ·) x} := by refine Set.ext fun x ↦ ⟨?_, fun h ↦ ?_⟩ · rintro ⟨x, (hx : Minimal _ x), rfl⟩ exact (minimal_mem_image_monotone_iff hx.prop hf).2 hx obtain ⟨y, hy, rfl⟩ := (mem_setOf_eq ▸ h).prop exact mem_image_of_mem _ <| (minimal_mem_image_monotone_iff (s := setOf P) hy hf).1 h theorem image_monotone_setOf_maximal (hf : ∀ ⦃x y⦄, P x → P y → (f x ≤ f y ↔ x ≤ y)) : f '' {x | Maximal P x} = {x | Maximal (∃ x₀, P x₀ ∧ f x₀ = ·) x} := image_monotone_setOf_minimal (α := αᵒᵈ) (β := βᵒᵈ) (fun _ _ hx hy ↦ hf hy hx) theorem image_antitone_setOf_minimal (hf : ∀ ⦃x y⦄, P x → P y → (f x ≤ f y ↔ y ≤ x)) : f '' {x | Minimal P x} = {x | Maximal (∃ x₀, P x₀ ∧ f x₀ = ·) x} := image_monotone_setOf_minimal (β := βᵒᵈ) (fun _ _ hx hy ↦ hf hy hx) theorem image_antitone_setOf_maximal (hf : ∀ ⦃x y⦄, P x → P y → (f x ≤ f y ↔ y ≤ x)) : f '' {x | Maximal P x} = {x | Minimal (∃ x₀, P x₀ ∧ f x₀ = ·) x} := image_monotone_setOf_maximal (β := βᵒᵈ) (fun _ _ hx hy ↦ hf hy hx) theorem image_monotone_setOf_minimal_mem (hf : ∀ ⦃x y⦄, x ∈ s → y ∈ s → (f x ≤ f y ↔ x ≤ y)) : f '' {x | Minimal (· ∈ s) x} = {x | Minimal (· ∈ f '' s) x} := image_monotone_setOf_minimal hf theorem image_monotone_setOf_maximal_mem (hf : ∀ ⦃x y⦄, x ∈ s → y ∈ s → (f x ≤ f y ↔ x ≤ y)) : f '' {x | Maximal (· ∈ s) x} = {x | Maximal (· ∈ f '' s) x} := image_monotone_setOf_maximal hf theorem image_antitone_setOf_minimal_mem (hf : ∀ ⦃x y⦄, x ∈ s → y ∈ s → (f x ≤ f y ↔ y ≤ x)) : f '' {x | Minimal (· ∈ s) x} = {x | Maximal (· ∈ f '' s) x} := image_antitone_setOf_minimal hf theorem image_antitone_setOf_maximal_mem (hf : ∀ ⦃x y⦄, x ∈ s → y ∈ s → (f x ≤ f y ↔ y ≤ x)) : f '' {x | Maximal (· ∈ s) x} = {x | Minimal (· ∈ f '' s) x} := image_antitone_setOf_maximal hf end Function namespace OrderEmbedding variable {f : α ↪o β} {t : Set β} theorem minimal_mem_image (f : α ↪o β) (hx : Minimal (· ∈ s) x) : Minimal (· ∈ f '' s) (f x) := _root_.minimal_mem_image_monotone (by simp [f.le_iff_le]) hx theorem maximal_mem_image (f : α ↪o β) (hx : Maximal (· ∈ s) x) : Maximal (· ∈ f '' s) (f x) := _root_.maximal_mem_image_monotone (by simp [f.le_iff_le]) hx theorem minimal_mem_image_iff (ha : a ∈ s) : Minimal (· ∈ f '' s) (f a) ↔ Minimal (· ∈ s) a := _root_.minimal_mem_image_monotone_iff ha (by simp [f.le_iff_le]) theorem maximal_mem_image_iff (ha : a ∈ s) : Maximal (· ∈ f '' s) (f a) ↔ Maximal (· ∈ s) a := _root_.maximal_mem_image_monotone_iff ha (by simp [f.le_iff_le]) theorem minimal_apply_mem_inter_range_iff : Minimal (· ∈ t ∩ range f) (f x) ↔ Minimal (fun x ↦ f x ∈ t) x := by refine ⟨fun h ↦ ⟨h.prop.1, fun y hy ↦ ?_⟩, fun h ↦ ⟨⟨h.prop, by simp⟩, ?_⟩⟩ · rw [← f.le_iff_le, ← f.le_iff_le] exact h.le_of_le ⟨hy, by simp⟩ rintro _ ⟨hyt, ⟨y, rfl⟩⟩ simp_rw [f.le_iff_le] exact h.le_of_le hyt theorem maximal_apply_mem_inter_range_iff : Maximal (· ∈ t ∩ range f) (f x) ↔ Maximal (fun x ↦ f x ∈ t) x := f.dual.minimal_apply_mem_inter_range_iff theorem minimal_apply_mem_iff (ht : t ⊆ Set.range f) : Minimal (· ∈ t) (f x) ↔ Minimal (fun x ↦ f x ∈ t) x := by rw [← f.minimal_apply_mem_inter_range_iff, inter_eq_self_of_subset_left ht] theorem maximal_apply_iff (ht : t ⊆ Set.range f) : Maximal (· ∈ t) (f x) ↔ Maximal (fun x ↦ f x ∈ t) x := f.dual.minimal_apply_mem_iff ht @[simp] theorem image_setOf_minimal : f '' {x | Minimal (· ∈ s) x} = {x | Minimal (· ∈ f '' s) x} := _root_.image_monotone_setOf_minimal (by simp [f.le_iff_le]) @[simp] theorem image_setOf_maximal : f '' {x | Maximal (· ∈ s) x} = {x | Maximal (· ∈ f '' s) x} := _root_.image_monotone_setOf_maximal (by simp [f.le_iff_le]) theorem inter_preimage_setOf_minimal_eq_of_subset (hts : t ⊆ f '' s) : x ∈ s ∩ f ⁻¹' {y | Minimal (· ∈ t) y} ↔ Minimal (· ∈ s ∩ f ⁻¹' t) x := by simp_rw [mem_inter_iff, preimage_setOf_eq, mem_setOf_eq, mem_preimage, f.minimal_apply_mem_iff (hts.trans (image_subset_range _ _)), minimal_and_iff_left_of_imp (fun _ hx ↦ f.injective.mem_set_image.1 <| hts hx)] theorem inter_preimage_setOf_maximal_eq_of_subset (hts : t ⊆ f '' s) : x ∈ s ∩ f ⁻¹' {y | Maximal (· ∈ t) y} ↔ Maximal (· ∈ s ∩ f ⁻¹' t) x := f.dual.inter_preimage_setOf_minimal_eq_of_subset hts end OrderEmbedding namespace OrderIso theorem image_setOf_minimal (f : α ≃o β) (P : α → Prop) : f '' {x | Minimal P x} = {x | Minimal (fun x ↦ P (f.symm x)) x} := by convert _root_.image_monotone_setOf_minimal (f := f) (by simp [f.le_iff_le]) aesop theorem image_setOf_maximal (f : α ≃o β) (P : α → Prop) : f '' {x | Maximal P x} = {x | Maximal (fun x ↦ P (f.symm x)) x} := by convert _root_.image_monotone_setOf_maximal (f := f) (by simp [f.le_iff_le]) aesop theorem map_minimal_mem (f : s ≃o t) (hx : Minimal (· ∈ s) x) : Minimal (· ∈ t) (f ⟨x, hx.prop⟩) := by simpa only [show t = range (Subtype.val ∘ f) by simp, mem_univ, minimal_true_subtype, hx, true_imp_iff, image_univ] using OrderEmbedding.minimal_mem_image (f.toOrderEmbedding.trans (OrderEmbedding.subtype t)) (s := univ) (x := ⟨x, hx.prop⟩) theorem map_maximal_mem (f : s ≃o t) (hx : Maximal (· ∈ s) x) : Maximal (· ∈ t) (f ⟨x, hx.prop⟩) := by simpa only [show t = range (Subtype.val ∘ f) by simp, mem_univ, maximal_true_subtype, hx, true_imp_iff, image_univ] using OrderEmbedding.maximal_mem_image (f.toOrderEmbedding.trans (OrderEmbedding.subtype t)) (s := univ) (x := ⟨x, hx.prop⟩) /-- If two sets are order isomorphic, their minimals are also order isomorphic. -/ def mapSetOfMinimal (f : s ≃o t) : {x | Minimal (· ∈ s) x} ≃o {x | Minimal (· ∈ t) x} where toFun x := ⟨f ⟨x, x.2.1⟩, f.map_minimal_mem x.2⟩ invFun x := ⟨f.symm ⟨x, x.2.1⟩, f.symm.map_minimal_mem x.2⟩ left_inv x := Subtype.ext (congr_arg Subtype.val <| f.left_inv ⟨x, x.2.1⟩ :) right_inv x := Subtype.ext (congr_arg Subtype.val <| f.right_inv ⟨x, x.2.1⟩ :) map_rel_iff' := f.map_rel_iff /-- If two sets are order isomorphic, their maximals are also order isomorphic. -/ def mapSetOfMaximal (f : s ≃o t) : {x | Maximal (· ∈ s) x} ≃o {x | Maximal (· ∈ t) x} where toFun x := ⟨f ⟨x, x.2.1⟩, f.map_maximal_mem x.2⟩ invFun x := ⟨f.symm ⟨x, x.2.1⟩, f.symm.map_maximal_mem x.2⟩ left_inv x := Subtype.ext (congr_arg Subtype.val <| f.left_inv ⟨x, x.2.1⟩ :) right_inv x := Subtype.ext (congr_arg Subtype.val <| f.right_inv ⟨x, x.2.1⟩ :) map_rel_iff' := f.map_rel_iff /-- If two sets are antitonically order isomorphic, their minimals/maximals are too. -/ def setOfMinimalIsoSetOfMaximal (f : s ≃o tᵒᵈ) : {x | Minimal (· ∈ s) x} ≃o {x | Maximal (· ∈ t) (ofDual x)} where toFun x := ⟨(f ⟨x.1, x.2.1⟩).1, ((show s ≃o ofDual ⁻¹' t from f).mapSetOfMinimal x).2⟩ invFun x := ⟨(f.symm ⟨x.1, x.2.1⟩).1, ((show ofDual ⁻¹' t ≃o s from f.symm).mapSetOfMinimal x).2⟩ __ := (show s ≃o ofDual⁻¹' t from f).mapSetOfMinimal /-- If two sets are antitonically order isomorphic, their maximals/minimals are too. -/ def setOfMaximalIsoSetOfMinimal (f : s ≃o tᵒᵈ) : {x | Maximal (· ∈ s) x} ≃o {x | Minimal (· ∈ t) (ofDual x)} where toFun x := ⟨(f ⟨x.1, x.2.1⟩).1, ((show s ≃o ofDual ⁻¹' t from f).mapSetOfMaximal x).2⟩ invFun x := ⟨(f.symm ⟨x.1, x.2.1⟩).1, ((show ofDual ⁻¹' t ≃o s from f.symm).mapSetOfMaximal x).2⟩ __ := (show s ≃o ofDual⁻¹' t from f).mapSetOfMaximal end OrderIso end Image section Interval variable [PartialOrder α] {a b : α} theorem minimal_mem_Icc (hab : a ≤ b) : Minimal (· ∈ Icc a b) x ↔ x = a := minimal_iff_eq ⟨rfl.le, hab⟩ (fun _ ↦ And.left) theorem maximal_mem_Icc (hab : a ≤ b) : Maximal (· ∈ Icc a b) x ↔ x = b := maximal_iff_eq ⟨hab, rfl.le⟩ (fun _ ↦ And.right) theorem minimal_mem_Ico (hab : a < b) : Minimal (· ∈ Ico a b) x ↔ x = a := minimal_iff_eq ⟨rfl.le, hab⟩ (fun _ ↦ And.left) theorem maximal_mem_Ioc (hab : a < b) : Maximal (· ∈ Ioc a b) x ↔ x = b := maximal_iff_eq ⟨hab, rfl.le⟩ (fun _ ↦ And.right) /- Note : The one-sided interval versions of these lemmas are unnecessary, since `simp` handles them with `maximal_le_iff` and `minimal_ge_iff`. -/ end Interval
.lake/packages/mathlib/Mathlib/Order/Concept.lean
import Mathlib.Data.Set.Lattice /-! # Formal concept analysis This file defines concept lattices. A concept of a relation `r : α → β → Prop` is a pair of sets `s : Set α` and `t : Set β` such that `s` is the set of all `a : α` that are related to all elements of `t`, and `t` is the set of all `b : β` that are related to all elements of `s`. Ordering the concepts of a relation `r` by inclusion on the first component gives rise to a *concept lattice*. Every concept lattice is complete and in fact every complete lattice arises as the concept lattice of its `≤`. ## Implementation notes Concept lattices are usually defined from a *context*, that is the triple `(α, β, r)`, but the type of `r` determines `α` and `β` already, so we do not define contexts as a separate object. ## TODO Prove the fundamental theorem of concept lattices. ## References * [Davey, Priestley *Introduction to Lattices and Order*][davey_priestley] * [Birkhoff, Garrett *Lattice Theory*][birkhoff1940] ## Tags concept, formal concept analysis, intent, extend, attribute -/ open Function OrderDual Set variable {ι : Sort*} {α β : Type*} {κ : ι → Sort*} (r : α → β → Prop) {s : Set α} {t : Set β} /-! ### Lower and upper polars -/ /-- The upper polar of `s : Set α` along a relation `r : α → β → Prop` is the set of all elements which `r` relates to all elements of `s`. -/ def upperPolar (s : Set α) : Set β := { b | ∀ ⦃a⦄, a ∈ s → r a b } @[deprecated (since := "2025-07-10")] alias intentClosure := upperPolar /-- The lower polar of `t : Set β` along a relation `r : α → β → Prop` is the set of all elements which `r` relates to all elements of `t`. -/ def lowerPolar (t : Set β) : Set α := { a | ∀ ⦃b⦄, b ∈ t → r a b } @[deprecated (since := "2025-07-10")] alias extentClosure := lowerPolar variable {r} theorem subset_upperPolar_iff_subset_lowerPolar : t ⊆ upperPolar r s ↔ s ⊆ lowerPolar r t := ⟨fun h _ ha _ hb => h hb ha, fun h _ hb _ ha => h ha hb⟩ @[deprecated (since := "2025-07-10")] alias subset_intentClosure_iff_subset_extentClosure := subset_upperPolar_iff_subset_lowerPolar variable (r) theorem gc_upperPolar_lowerPolar : GaloisConnection (toDual ∘ upperPolar r) (lowerPolar r ∘ ofDual) := fun _ _ => subset_upperPolar_iff_subset_lowerPolar @[deprecated (since := "2025-07-10")] alias gc_intentClosure_extentClosure := gc_upperPolar_lowerPolar theorem upperPolar_swap (t : Set β) : upperPolar (swap r) t = lowerPolar r t := rfl @[deprecated (since := "2025-07-10")] alias intentClosure_swap := upperPolar_swap theorem lowerPolar_swap (s : Set α) : lowerPolar (swap r) s = upperPolar r s := rfl @[deprecated (since := "2025-07-10")] alias extentClosure_swap := lowerPolar_swap @[simp] theorem upperPolar_empty : upperPolar r ∅ = univ := eq_univ_of_forall fun _ _ => False.elim @[deprecated (since := "2025-07-10")] alias intentClosure_empty := upperPolar_empty @[simp] theorem lowerPolar_empty : lowerPolar r ∅ = univ := upperPolar_empty _ @[deprecated (since := "2025-07-10")] alias extentClosure_empty := lowerPolar_empty @[simp] theorem upperPolar_union (s₁ s₂ : Set α) : upperPolar r (s₁ ∪ s₂) = upperPolar r s₁ ∩ upperPolar r s₂ := ext fun _ => forall₂_or_left @[deprecated (since := "2025-07-10")] alias intentClosure_union := upperPolar_union @[simp] theorem lowerPolar_union (t₁ t₂ : Set β) : lowerPolar r (t₁ ∪ t₂) = lowerPolar r t₁ ∩ lowerPolar r t₂ := upperPolar_union .. @[deprecated (since := "2025-07-10")] alias extentClosure_union := lowerPolar_union @[simp] theorem upperPolar_iUnion (f : ι → Set α) : upperPolar r (⋃ i, f i) = ⋂ i, upperPolar r (f i) := (gc_upperPolar_lowerPolar r).l_iSup @[deprecated (since := "2025-07-10")] alias intentClosure_iUnion := upperPolar_iUnion @[simp] theorem lowerPolar_iUnion (f : ι → Set β) : lowerPolar r (⋃ i, f i) = ⋂ i, lowerPolar r (f i) := upperPolar_iUnion .. @[deprecated (since := "2025-07-10")] alias extentClosure_iUnion := lowerPolar_iUnion theorem upperPolar_iUnion₂ (f : ∀ i, κ i → Set α) : upperPolar r (⋃ (i) (j), f i j) = ⋂ (i) (j), upperPolar r (f i j) := (gc_upperPolar_lowerPolar r).l_iSup₂ @[deprecated (since := "2025-07-10")] alias intentClosure_iUnion₂ := upperPolar_iUnion₂ theorem lowerPolar_iUnion₂ (f : ∀ i, κ i → Set β) : lowerPolar r (⋃ (i) (j), f i j) = ⋂ (i) (j), lowerPolar r (f i j) := upperPolar_iUnion₂ .. @[deprecated (since := "2025-07-10")] alias extentClosure_iUnion₂ := lowerPolar_iUnion₂ theorem subset_lowerPolar_upperPolar (s : Set α) : s ⊆ lowerPolar r (upperPolar r s) := (gc_upperPolar_lowerPolar r).le_u_l _ @[deprecated (since := "2025-07-10")] alias subset_extentClosure_intentClosure := subset_lowerPolar_upperPolar theorem subset_upperPolar_lowerPolar (t : Set β) : t ⊆ upperPolar r (lowerPolar r t) := subset_lowerPolar_upperPolar _ t @[deprecated (since := "2025-07-10")] alias subset_intentClosure_extentClosure := subset_upperPolar_lowerPolar @[simp] theorem upperPolar_lowerPolar_upperPolar (s : Set α) : upperPolar r (lowerPolar r <| upperPolar r s) = upperPolar r s := (gc_upperPolar_lowerPolar r).l_u_l_eq_l _ @[deprecated (since := "2025-07-10")] alias intentClosure_extentClosure_intentClosure := upperPolar_lowerPolar_upperPolar @[simp] theorem lowerPolar_upperPolar_lowerPolar (t : Set β) : lowerPolar r (upperPolar r <| lowerPolar r t) = lowerPolar r t := upperPolar_lowerPolar_upperPolar _ t @[deprecated (since := "2025-07-10")] alias extentClosure_intentClosure_extentClosure := lowerPolar_upperPolar_lowerPolar theorem upperPolar_anti : Antitone (upperPolar r) := (gc_upperPolar_lowerPolar r).monotone_l @[deprecated (since := "2025-07-10")] alias intentClosure_anti := upperPolar_anti theorem lowerPolar_anti : Antitone (lowerPolar r) := upperPolar_anti _ @[deprecated (since := "2025-07-10")] alias extentClosure_anti := lowerPolar_anti /-! ### Concepts -/ variable (α β) /-- The formal concepts of a relation. A concept of `r : α → β → Prop` is a pair of sets `s`, `t` such that `s` is the set of all elements that are `r`-related to all of `t` and `t` is the set of all elements that are `r`-related to all of `s`. -/ structure Concept where /-- The extent of a concept. -/ extent : Set α /-- The intent of a concept. -/ intent : Set β /-- The intent consists of all elements related to all elements of the extent. -/ upperPolar_extent : upperPolar r extent = intent /-- The extent consists of all elements related to all elements of the intent. -/ lowerPolar_intent : lowerPolar r intent = extent namespace Concept @[deprecated (since := "2025-07-10")] alias fst := extent @[deprecated (since := "2025-07-10")] alias snd := intent @[deprecated (since := "2025-07-10")] alias closure_fst := upperPolar_extent @[deprecated (since := "2025-07-10")] alias closure_snd := lowerPolar_intent variable {r r' α β} variable {c d : Concept α β r} {c' : Concept α α r'} attribute [simp] upperPolar_extent lowerPolar_intent @[ext] theorem ext (h : c.extent = d.extent) : c = d := by obtain ⟨s₁, t₁, rfl, _⟩ := c obtain ⟨s₂, t₂, rfl, _⟩ := d substs h rfl theorem ext' (h : c.intent = d.intent) : c = d := by obtain ⟨s₁, t₁, _, rfl⟩ := c obtain ⟨s₂, t₂, _, rfl⟩ := d substs h rfl theorem extent_injective : Injective (@extent α β r) := fun _ _ => ext @[deprecated (since := "2025-07-10")] alias fst_injective := extent_injective theorem intent_injective : Injective (@intent α β r) := fun _ _ => ext' @[deprecated (since := "2025-07-10")] alias snd_injective := intent_injective theorem rel_extent_intent {x y} (hx : x ∈ c.extent) (hy : y ∈ c.intent) : r x y := by rw [← c.upperPolar_extent] at hy exact hy hx /-- Note that if `r'` is the `≤` relation, this theorem will often not be true! -/ theorem disjoint_extent_intent [IsIrrefl α r'] : Disjoint c'.extent c'.intent := by rw [disjoint_iff_forall_ne] rintro x hx _ hx' rfl exact irrefl x (rel_extent_intent hx hx') theorem mem_extent_of_rel_extent [IsTrans α r'] {x y} (hy : r' y x) (hx : x ∈ c'.extent) : y ∈ c'.extent := by rw [← lowerPolar_intent] exact fun z hz ↦ _root_.trans hy (rel_extent_intent hx hz) theorem mem_intent_of_intent_rel [IsTrans α r'] {x y} (hy : r' x y) (hx : x ∈ c'.intent) : y ∈ c'.intent := by rw [← upperPolar_extent] exact fun z hz ↦ _root_.trans (rel_extent_intent hz hx) hy theorem codisjoint_extent_intent [IsTrichotomous α r'] [IsTrans α r'] : Codisjoint c'.extent c'.intent := by rw [codisjoint_iff_le_sup] refine fun x _ ↦ or_iff_not_imp_left.2 fun hx ↦ ?_ rw [← upperPolar_extent] intro y hy obtain h | rfl | h := trichotomous_of r' x y · cases hx <| mem_extent_of_rel_extent h hy · contradiction · assumption instance instSupConcept : Max (Concept α β r) := ⟨fun c d => { extent := lowerPolar r (c.intent ∩ d.intent) intent := c.intent ∩ d.intent upperPolar_extent := by rw [← c.upperPolar_extent, ← d.upperPolar_extent, ← upperPolar_union, upperPolar_lowerPolar_upperPolar] lowerPolar_intent := rfl }⟩ instance instInfConcept : Min (Concept α β r) := ⟨fun c d => { extent := c.extent ∩ d.extent intent := upperPolar r (c.extent ∩ d.extent) upperPolar_extent := rfl lowerPolar_intent := by rw [← c.lowerPolar_intent, ← d.lowerPolar_intent, ← lowerPolar_union, lowerPolar_upperPolar_lowerPolar] }⟩ instance instSemilatticeInfConcept : SemilatticeInf (Concept α β r) := (extent_injective.semilatticeInf _) fun _ _ => rfl @[simp] theorem extent_subset_extent_iff : c.extent ⊆ d.extent ↔ c ≤ d := Iff.rfl @[deprecated (since := "2025-07-10")] alias fst_subset_fst_iff := extent_subset_extent_iff @[simp] theorem extent_ssubset_extent_iff : c.extent ⊂ d.extent ↔ c < d := Iff.rfl @[deprecated (since := "2025-07-10")] alias fst_ssubset_fst_iff := extent_ssubset_extent_iff @[simp] theorem intent_subset_intent_iff : c.intent ⊆ d.intent ↔ d ≤ c := by refine ⟨fun h => ?_, fun h => ?_⟩ · rw [← extent_subset_extent_iff, ← c.lowerPolar_intent, ← d.lowerPolar_intent] exact lowerPolar_anti _ h · rw [← c.upperPolar_extent, ← d.upperPolar_extent] exact upperPolar_anti _ h @[deprecated (since := "2025-07-10")] alias snd_subset_snd_iff := intent_subset_intent_iff @[simp] theorem intent_ssubset_intent_iff : c.intent ⊂ d.intent ↔ d < c := by rw [ssubset_iff_subset_not_subset, lt_iff_le_not_ge, intent_subset_intent_iff, intent_subset_intent_iff] @[deprecated (since := "2025-07-10")] alias snd_ssubset_snd_iff := intent_ssubset_intent_iff theorem strictMono_extent : StrictMono (@extent α β r) := fun _ _ => extent_ssubset_extent_iff.2 @[deprecated (since := "2025-07-10")] alias strictMono_fst := strictMono_extent theorem strictAnti_intent : StrictAnti (@intent α β r) := fun _ _ => intent_ssubset_intent_iff.2 @[deprecated (since := "2025-07-10")] alias strictMono_snd := strictAnti_intent instance instLatticeConcept : Lattice (Concept α β r) := { Concept.instSemilatticeInfConcept with sup := (· ⊔ ·) le_sup_left := fun _ _ => intent_subset_intent_iff.1 inter_subset_left le_sup_right := fun _ _ => intent_subset_intent_iff.1 inter_subset_right sup_le := fun c d e => by simp_rw [← intent_subset_intent_iff] exact subset_inter } instance instBoundedOrderConcept : BoundedOrder (Concept α β r) where top := ⟨univ, upperPolar r univ, rfl, eq_univ_of_forall fun _ _ hb => hb trivial⟩ le_top _ := subset_univ _ bot := ⟨lowerPolar r univ, univ, eq_univ_of_forall fun _ _ ha => ha trivial, rfl⟩ bot_le _ := intent_subset_intent_iff.1 <| subset_univ _ instance : SupSet (Concept α β r) := ⟨fun S => { extent := lowerPolar r (⋂ c ∈ S, intent c) intent := ⋂ c ∈ S, intent c upperPolar_extent := by simp_rw [← upperPolar_extent, ← upperPolar_iUnion₂, upperPolar_lowerPolar_upperPolar] lowerPolar_intent := rfl }⟩ instance : InfSet (Concept α β r) := ⟨fun S => { extent := ⋂ c ∈ S, extent c intent := upperPolar r (⋂ c ∈ S, extent c) upperPolar_extent := rfl lowerPolar_intent := by simp_rw [← lowerPolar_intent, ← lowerPolar_iUnion₂, lowerPolar_upperPolar_lowerPolar] }⟩ instance : CompleteLattice (Concept α β r) := { Concept.instLatticeConcept, Concept.instBoundedOrderConcept with sup := Concept.instSupConcept.max le_sSup := fun _ _ hc => intent_subset_intent_iff.1 <| biInter_subset_of_mem hc sSup_le := fun _ _ hc => intent_subset_intent_iff.1 <| subset_iInter₂ fun d hd => intent_subset_intent_iff.2 <| hc d hd inf := Concept.instInfConcept.min sInf_le := fun _ _ => biInter_subset_of_mem le_sInf := fun _ _ => subset_iInter₂ } @[simp] theorem extent_top : (⊤ : Concept α β r).extent = univ := rfl @[deprecated (since := "2025-07-10")] alias top_fst := extent_top @[simp] theorem intent_top : (⊤ : Concept α β r).intent = upperPolar r univ := rfl @[deprecated (since := "2025-07-10")] alias top_snd := intent_top @[simp] theorem extent_bot : (⊥ : Concept α β r).extent = lowerPolar r univ := rfl @[deprecated (since := "2025-07-10")] alias bot_fst := extent_bot @[simp] theorem intent_bot : (⊥ : Concept α β r).intent = univ := rfl @[deprecated (since := "2025-07-10")] alias bot_snd := intent_bot @[simp] theorem extent_sup (c d : Concept α β r) : (c ⊔ d).extent = lowerPolar r (c.intent ∩ d.intent) := rfl @[deprecated (since := "2025-07-10")] alias sup_fst := extent_top @[simp] theorem intent_sup (c d : Concept α β r) : (c ⊔ d).intent = c.intent ∩ d.intent := rfl @[deprecated (since := "2025-07-10")] alias sup_snd := intent_sup @[simp] theorem extent_inf (c d : Concept α β r) : (c ⊓ d).extent = c.extent ∩ d.extent := rfl @[deprecated (since := "2025-07-10")] alias inf_fst := extent_inf @[simp] theorem intent_inf (c d : Concept α β r) : (c ⊓ d).intent = upperPolar r (c.extent ∩ d.extent) := rfl @[deprecated (since := "2025-07-10")] alias inf_snd := intent_inf @[simp] theorem extent_sSup (S : Set (Concept α β r)) : (sSup S).extent = lowerPolar r (⋂ c ∈ S, intent c) := rfl @[deprecated (since := "2025-07-10")] alias sSup_fst := extent_sSup @[simp] theorem intent_sSup (S : Set (Concept α β r)) : (sSup S).intent = ⋂ c ∈ S, intent c := rfl @[deprecated (since := "2025-07-10")] alias sSup_snd := intent_sSup @[simp] theorem extent_sInf (S : Set (Concept α β r)) : (sInf S).extent = ⋂ c ∈ S, extent c := rfl @[deprecated (since := "2025-07-10")] alias sInf_fst := extent_sInf @[simp] theorem intent_sInf (S : Set (Concept α β r)) : (sInf S).intent = upperPolar r (⋂ c ∈ S, extent c) := rfl @[deprecated (since := "2025-07-10")] alias sInf_snd := intent_sInf instance : Inhabited (Concept α β r) := ⟨⊥⟩ /-- Swap the sets of a concept to make it a concept of the dual context. -/ @[simps] def swap (c : Concept α β r) : Concept β α (swap r) := ⟨c.intent, c.extent, c.lowerPolar_intent, c.upperPolar_extent⟩ @[simp] theorem swap_swap (c : Concept α β r) : c.swap.swap = c := ext rfl @[simp] theorem swap_le_swap_iff : c.swap ≤ d.swap ↔ d ≤ c := intent_subset_intent_iff @[simp] theorem swap_lt_swap_iff : c.swap < d.swap ↔ d < c := intent_ssubset_intent_iff /-- The dual of a concept lattice is isomorphic to the concept lattice of the dual context. -/ @[simps] def swapEquiv : (Concept α β r)ᵒᵈ ≃o Concept β α (Function.swap r) where toFun := swap ∘ ofDual invFun := toDual ∘ swap left_inv := swap_swap right_inv := swap_swap map_rel_iff' := swap_le_swap_iff end Concept
.lake/packages/mathlib/Mathlib/Order/Notation.lean
import Qq import Mathlib.Lean.PrettyPrinter.Delaborator import Mathlib.Tactic.TypeStar import Mathlib.Tactic.Simps.NotationClass import Mathlib.Tactic.ToDual /-! # Notation classes for lattice operations In this file we introduce typeclasses and definitions for lattice operations. ## Main definitions * `HasCompl`: type class for the `ᶜ` notation * `Top`: type class for the `⊤` notation * `Bot`: type class for the `⊥` notation ## Notation * `xᶜ`: complement in a lattice; * `x ⊔ y`: supremum/join, which is notation for `max x y`; * `x ⊓ y`: infimum/meet, which is notation for `min x y`; We implement a delaborator that pretty prints `max x y`/`min x y` as `x ⊔ y`/`x ⊓ y` if and only if the order on `α` does not have a `LinearOrder α` instance (where `x y : α`). This is so that in a lattice we can use the same underlying constants `max`/`min` as in linear orders, while using the more idiomatic notation `x ⊔ y`/`x ⊓ y`. Lemmas about the operators `⊔` and `⊓` should use the names `sup` and `inf` respectively. -/ /-- Set / lattice complement -/ @[notation_class] class HasCompl (α : Type*) where /-- Set / lattice complement -/ compl : α → α export HasCompl (compl) @[inherit_doc] postfix:1024 "ᶜ" => compl /-! ### `Sup` and `Inf` -/ attribute [ext] Min Max /-- The supremum/join operation: `x ⊔ y`. It is notation for `max x y` and should be used when the type is not a linear order. -/ syntax:68 term:68 " ⊔ " term:69 : term /-- The infimum/meet operation: `x ⊓ y`. It is notation for `min x y` and should be used when the type is not a linear order. -/ syntax:69 term:69 " ⊓ " term:70 : term macro_rules | `($a ⊔ $b) => `(Max.max $a $b) | `($a ⊓ $b) => `(Min.min $a $b) namespace Mathlib.Meta open Lean Meta PrettyPrinter Delaborator SubExpr Qq -- irreducible to not confuse Qq @[irreducible] private def linearOrderExpr (u : Level) : Q(Type u → Type u) := .const `LinearOrder [u] private def linearOrderToMax (u : Level) : Q((a : Type u) → $(linearOrderExpr u) a → Max a) := .const `LinearOrder.toMax [u] private def linearOrderToMin (u : Level) : Q((a : Type u) → $(linearOrderExpr u) a → Min a) := .const `LinearOrder.toMin [u] /-- Return `true` if `LinearOrder` is imported and `inst` comes from a `LinearOrder e` instance. We use a `try catch` block to make sure there are no surprising errors during delaboration. -/ private def hasLinearOrder (u : Level) (α : Q(Type u)) (cls : Q(Type u → Type u)) (toCls : Q((α : Type u) → $(linearOrderExpr u) α → $cls α)) (inst : Q($cls $α)) : MetaM Bool := do try withNewMCtxDepth do -- `isDefEq` may call type class search to instantiate `mvar`, so we need the local instances -- In Lean 4.19 the pretty printer clears local instances, so we re-add them here. -- TODO(Jovan): remove withLocalInstances (← getLCtx).decls.toList.reduceOption do let mvar ← mkFreshExprMVarQ q($(linearOrderExpr u) $α) (kind := .synthetic) let inst' : Q($cls $α) := q($toCls $α $mvar) isDefEq inst inst' catch _ => -- For instance, if `LinearOrder` is not yet imported. return false /-- Delaborate `max x y` into `x ⊔ y` if the type is not a linear order. -/ @[delab app.Max.max] def delabSup : Delab := whenNotPPOption getPPExplicit <| whenPPOption getPPNotation do let_expr f@Max.max α inst _ _ := ← getExpr | failure have u := f.constLevels![0]! if ← hasLinearOrder u α q(Max) q($(linearOrderToMax u)) inst then failure -- use the default delaborator let x ← withNaryArg 2 delab let y ← withNaryArg 3 delab let stx ← `($x ⊔ $y) annotateGoToSyntaxDef stx /-- Delaborate `min x y` into `x ⊓ y` if the type is not a linear order. -/ @[delab app.Min.min] def delabInf : Delab := whenNotPPOption getPPExplicit <| whenPPOption getPPNotation do let_expr f@Min.min α inst _ _ := ← getExpr | failure have u := f.constLevels![0]! if ← hasLinearOrder u α q(Min) q($(linearOrderToMin u)) inst then failure -- use the default delaborator let x ← withNaryArg 2 delab let y ← withNaryArg 3 delab let stx ← `($x ⊓ $y) annotateGoToSyntaxDef stx end Mathlib.Meta /-- Syntax typeclass for Heyting implication `⇨`. -/ @[notation_class] class HImp (α : Type*) where /-- Heyting implication `⇨` -/ himp : α → α → α /-- Syntax typeclass for Heyting negation `¬`. The difference between `HasCompl` and `HNot` is that the former belongs to Heyting algebras, while the latter belongs to co-Heyting algebras. They are both pseudo-complements, but `compl` underestimates while `HNot` overestimates. In Boolean algebras, they are equal. See `hnot_eq_compl`. -/ @[notation_class] class HNot (α : Type*) where /-- Heyting negation `¬` -/ hnot : α → α export HImp (himp) export SDiff (sdiff) export HNot (hnot) /-- Heyting implication -/ infixr:60 " ⇨ " => himp /-- Heyting negation -/ prefix:72 "¬" => hnot /-- Typeclass for the `⊤` (`\top`) notation -/ @[notation_class, ext] class Top (α : Type*) where /-- The top (`⊤`, `\top`) element -/ top : α /-- Typeclass for the `⊥` (`\bot`) notation -/ @[notation_class, ext, to_dual] class Bot (α : Type*) where /-- The bot (`⊥`, `\bot`) element -/ bot : α /-- The top (`⊤`, `\top`) element -/ notation "⊤" => Top.top /-- The bot (`⊥`, `\bot`) element -/ notation "⊥" => Bot.bot @[to_dual] instance (priority := 100) top_nonempty (α : Type*) [Top α] : Nonempty α := ⟨⊤⟩ attribute [match_pattern] Bot.bot Top.top
.lake/packages/mathlib/Mathlib/Order/Zorn.lean
import Mathlib.Order.CompleteLattice.Chain import Mathlib.Order.Minimal /-! # Zorn's lemmas This file proves several formulations of Zorn's Lemma. ## Variants The primary statement of Zorn's lemma is `exists_maximal_of_chains_bounded`. Then it is specialized to particular relations: * `(≤)` with `zorn_le` * `(⊆)` with `zorn_subset` * `(⊇)` with `zorn_superset` Lemma names carry modifiers: * `₀`: Quantifies over a set, as opposed to over a type. * `_nonempty`: Doesn't ask to prove that the empty chain is bounded and lets you give an element that will be smaller than the maximal element found (the maximal element is no smaller than any other element, but it can also be incomparable to some). ## How-to This file comes across as confusing to those who haven't yet used it, so here is a detailed walkthrough: 1. Know what relation on which type/set you're looking for. See Variants above. You can discharge some conditions to Zorn's lemma directly using a `_nonempty` variant. 2. Write down the definition of your type/set, put a `suffices ∃ m, ∀ a, m ≺ a → a ≺ m by ...` (or whatever you actually need) followed by an `apply some_version_of_zorn`. 3. Fill in the details. This is where you start talking about chains. A typical proof using Zorn could look like this ```lean lemma zorny_lemma : zorny_statement := by let s : Set α := {x | whatever x} suffices ∃ x ∈ s, ∀ y ∈ s, y ⊆ x → y = x by -- or with another operator xxx proof_post_zorn apply zorn_subset -- or another variant rintro c hcs hc obtain rfl | hcnemp := c.eq_empty_or_nonempty -- you might need to disjunct on c empty or not · exact ⟨edge_case_construction, proof_that_edge_case_construction_respects_whatever, proof_that_edge_case_construction_contains_all_stuff_in_c⟩ · exact ⟨construction, proof_that_construction_respects_whatever, proof_that_construction_contains_all_stuff_in_c⟩ ``` ## Notes Originally ported from Isabelle/HOL. The [original file](https://isabelle.in.tum.de/dist/library/HOL/HOL/Zorn.html) was written by Jacques D. Fleuriot, Tobias Nipkow, Christian Sternagel. -/ open Set variable {α β : Type*} {r : α → α → Prop} {c : Set α} /-- Local notation for the relation being considered. -/ local infixl:50 " ≺ " => r /-- **Zorn's lemma** If every chain has an upper bound, then there exists a maximal element. -/ theorem exists_maximal_of_chains_bounded (h : ∀ c, IsChain r c → ∃ ub, ∀ a ∈ c, a ≺ ub) (trans : ∀ {a b c}, a ≺ b → b ≺ c → a ≺ c) : ∃ m, ∀ a, m ≺ a → a ≺ m := have : ∃ ub, ∀ a ∈ maxChain r, a ≺ ub := h _ <| maxChain_spec.left let ⟨ub, (hub : ∀ a ∈ maxChain r, a ≺ ub)⟩ := this ⟨ub, fun a ha => have : IsChain r (insert a <| maxChain r) := maxChain_spec.1.insert fun b hb _ => Or.inr <| trans (hub b hb) ha hub a <| by rw [maxChain_spec.right this (subset_insert _ _)] exact mem_insert _ _⟩ /-- A variant of Zorn's lemma. If every nonempty chain of a nonempty type has an upper bound, then there is a maximal element. -/ theorem exists_maximal_of_nonempty_chains_bounded [Nonempty α] (h : ∀ c, IsChain r c → c.Nonempty → ∃ ub, ∀ a ∈ c, a ≺ ub) (trans : ∀ {a b c}, a ≺ b → b ≺ c → a ≺ c) : ∃ m, ∀ a, m ≺ a → a ≺ m := exists_maximal_of_chains_bounded (fun c hc => (eq_empty_or_nonempty c).elim (fun h => ⟨Classical.arbitrary α, fun x hx => (h ▸ hx : x ∈ (∅ : Set α)).elim⟩) (h c hc)) trans section Preorder variable [Preorder α] theorem zorn_le (h : ∀ c : Set α, IsChain (· ≤ ·) c → BddAbove c) : ∃ m : α, IsMax m := exists_maximal_of_chains_bounded h le_trans theorem zorn_le_nonempty [Nonempty α] (h : ∀ c : Set α, IsChain (· ≤ ·) c → c.Nonempty → BddAbove c) : ∃ m : α, IsMax m := exists_maximal_of_nonempty_chains_bounded h le_trans theorem zorn_le₀ (s : Set α) (ih : ∀ c ⊆ s, IsChain (· ≤ ·) c → ∃ ub ∈ s, ∀ z ∈ c, z ≤ ub) : ∃ m, Maximal (· ∈ s) m := let ⟨⟨m, hms⟩, h⟩ := @zorn_le s _ fun c hc => let ⟨ub, hubs, hub⟩ := ih (Subtype.val '' c) (fun _ ⟨⟨_, hx⟩, _, h⟩ => h ▸ hx) (by rintro _ ⟨p, hpc, rfl⟩ _ ⟨q, hqc, rfl⟩ hpq exact hc hpc hqc fun t => hpq (Subtype.ext_iff.1 t)) ⟨⟨ub, hubs⟩, fun ⟨_, _⟩ hc => hub _ ⟨_, hc, rfl⟩⟩ ⟨m, hms, fun z hzs hmz => @h ⟨z, hzs⟩ hmz⟩ theorem zorn_le_nonempty₀ (s : Set α) (ih : ∀ c ⊆ s, IsChain (· ≤ ·) c → ∀ y ∈ c, ∃ ub ∈ s, ∀ z ∈ c, z ≤ ub) (x : α) (hxs : x ∈ s) : ∃ m, x ≤ m ∧ Maximal (· ∈ s) m := by have H := zorn_le₀ ({ y ∈ s | x ≤ y }) fun c hcs hc => ?_ · rcases H with ⟨m, ⟨hms, hxm⟩, hm⟩ exact ⟨m, hxm, hms, fun z hzs hmz => @hm _ ⟨hzs, hxm.trans hmz⟩ hmz⟩ · rcases c.eq_empty_or_nonempty with (rfl | ⟨y, hy⟩) · exact ⟨x, ⟨hxs, le_rfl⟩, fun z => False.elim⟩ · rcases ih c (fun z hz => (hcs hz).1) hc y hy with ⟨z, hzs, hz⟩ exact ⟨z, ⟨hzs, (hcs hy).2.trans <| hz _ hy⟩, hz⟩ theorem zorn_le_nonempty_Ici₀ (a : α) (ih : ∀ c ⊆ Ici a, IsChain (· ≤ ·) c → ∀ y ∈ c, ∃ ub, ∀ z ∈ c, z ≤ ub) (x : α) (hax : a ≤ x) : ∃ m, x ≤ m ∧ IsMax m := by let ⟨m, hxm, ham, hm⟩ := zorn_le_nonempty₀ (Ici a) (fun c hca hc y hy ↦ ?_) x hax · exact ⟨m, hxm, fun z hmz => hm (ham.trans hmz) hmz⟩ · have ⟨ub, hub⟩ := ih c hca hc y hy exact ⟨ub, (hca hy).trans (hub y hy), hub⟩ end Preorder theorem zorn_subset (S : Set (Set α)) (h : ∀ c ⊆ S, IsChain (· ⊆ ·) c → ∃ ub ∈ S, ∀ s ∈ c, s ⊆ ub) : ∃ m, Maximal (· ∈ S) m := zorn_le₀ S h theorem zorn_subset_nonempty (S : Set (Set α)) (H : ∀ c ⊆ S, IsChain (· ⊆ ·) c → c.Nonempty → ∃ ub ∈ S, ∀ s ∈ c, s ⊆ ub) (x) (hx : x ∈ S) : ∃ m, x ⊆ m ∧ Maximal (· ∈ S) m := zorn_le_nonempty₀ _ (fun _ cS hc y yc => H _ cS hc ⟨y, yc⟩) _ hx theorem zorn_superset (S : Set (Set α)) (h : ∀ c ⊆ S, IsChain (· ⊆ ·) c → ∃ lb ∈ S, ∀ s ∈ c, lb ⊆ s) : ∃ m, Minimal (· ∈ S) m := (@zorn_le₀ (Set α)ᵒᵈ _ S) fun c cS hc => h c cS hc.symm theorem zorn_superset_nonempty (S : Set (Set α)) (H : ∀ c ⊆ S, IsChain (· ⊆ ·) c → c.Nonempty → ∃ lb ∈ S, ∀ s ∈ c, lb ⊆ s) (x) (hx : x ∈ S) : ∃ m, m ⊆ x ∧ Minimal (· ∈ S) m := @zorn_le_nonempty₀ (Set α)ᵒᵈ _ S (fun _ cS hc y yc => H _ cS hc.symm ⟨y, yc⟩) _ hx /-- Every chain is contained in a maximal chain. This generalizes Hausdorff's maximality principle. -/ theorem IsChain.exists_maxChain (hc : IsChain r c) : ∃ M, @IsMaxChain _ r M ∧ c ⊆ M := by have H := zorn_subset_nonempty { s | c ⊆ s ∧ IsChain r s } ?_ c ⟨Subset.rfl, hc⟩ · obtain ⟨M, hcM, hM⟩ := H exact ⟨M, ⟨hM.prop.2, fun d hd hMd ↦ hM.eq_of_subset ⟨hcM.trans hMd, hd⟩ hMd⟩, hcM⟩ rintro cs hcs₀ hcs₁ ⟨s, hs⟩ refine ⟨⋃₀cs, ⟨fun _ ha => Set.mem_sUnion_of_mem ((hcs₀ hs).left ha) hs, ?_⟩, fun _ => Set.subset_sUnion_of_mem⟩ rintro y ⟨sy, hsy, hysy⟩ z ⟨sz, hsz, hzsz⟩ hyz obtain rfl | hsseq := eq_or_ne sy sz · exact (hcs₀ hsy).right hysy hzsz hyz rcases hcs₁ hsy hsz hsseq with h | h · exact (hcs₀ hsz).right (h hysy) hzsz hyz · exact (hcs₀ hsy).right hysy (h hzsz) hyz /-! ### Flags -/ namespace Flag variable [Preorder α] {c : Set α} {s : Flag α} {a b : α} lemma _root_.IsChain.exists_subset_flag (hc : IsChain (· ≤ ·) c) : ∃ s : Flag α, c ⊆ s := let ⟨s, hs, hcs⟩ := hc.exists_maxChain; ⟨ofIsMaxChain s hs, hcs⟩ lemma exists_mem (a : α) : ∃ s : Flag α, a ∈ s := let ⟨s, hs⟩ := Set.subsingleton_singleton (a := a).isChain.exists_subset_flag ⟨s, hs rfl⟩ lemma exists_mem_mem (hab : a ≤ b) : ∃ s : Flag α, a ∈ s ∧ b ∈ s := by simpa [Set.insert_subset_iff] using (IsChain.pair hab).exists_subset_flag instance : Nonempty (Flag α) := ⟨.ofIsMaxChain _ maxChain_spec⟩ end Flag
.lake/packages/mathlib/Mathlib/Order/Booleanisation.lean
import Mathlib.Order.BooleanAlgebra.Basic import Mathlib.Order.Hom.Lattice /-! # Adding complements to a generalized Boolean algebra This file embeds any generalized Boolean algebra into a Boolean algebra. This concretely proves that any equation holding true in the theory of Boolean algebras that does not reference `ᶜ` also holds true in the theory of generalized Boolean algebras. Put another way, one does not need the existence of complements to prove something which does not talk about complements. ## Main declarations * `Booleanisation`: Boolean algebra containing a given generalised Boolean algebra as a sublattice. * `Booleanisation.liftLatticeHom`: Boolean algebra containing a given generalised Boolean algebra as a sublattice. ## Future work If mathlib ever acquires `GenBoolAlg`, the category of generalised Boolean algebras, then one could show that `Booleanisation` is the free functor from `GenBoolAlg` to `BoolAlg`. -/ open Function variable {α : Type*} /-- Boolean algebra containing a given generalised Boolean algebra `α` as a sublattice. This should be thought of as made of a copy of `α` (representing elements of `α`) living under another copy of `α` (representing complements of elements of `α`). -/ def Booleanisation (α : Type*) := α ⊕ α namespace Booleanisation instance instDecidableEq [DecidableEq α] : DecidableEq (Booleanisation α) := inferInstanceAs <| DecidableEq (α ⊕ α) /-- The natural inclusion `a ↦ a` from a generalized Boolean algebra to its generated Boolean algebra. -/ @[match_pattern] def lift : α → Booleanisation α := Sum.inl /-- The inclusion `a ↦ aᶜ` from a generalized Boolean algebra to its generated Boolean algebra. -/ @[match_pattern] def comp : α → Booleanisation α := Sum.inr /-- The complement operator on `Booleanisation α` sends `a` to `aᶜ` and `aᶜ` to `a`, for `a : α`. -/ instance instCompl : HasCompl (Booleanisation α) where compl | lift a => comp a | comp a => lift a @[simp] lemma compl_lift (a : α) : (lift a)ᶜ = comp a := rfl @[simp] lemma compl_comp (a : α) : (comp a)ᶜ = lift a := rfl variable [GeneralizedBooleanAlgebra α] {a b : α} /-- The order on `Booleanisation α` is as follows: For `a b : α`, * `a ≤ b` iff `a ≤ b` in `α` * `a ≤ bᶜ` iff `a` and `b` are disjoint in `α` * `aᶜ ≤ bᶜ` iff `b ≤ a` in `α` * `¬ aᶜ ≤ b` -/ protected inductive LE : Booleanisation α → Booleanisation α → Prop | protected lift {a b} : a ≤ b → Booleanisation.LE (lift a) (lift b) | protected comp {a b} : a ≤ b → Booleanisation.LE (comp b) (comp a) | protected sep {a b} : Disjoint a b → Booleanisation.LE (lift a) (comp b) /-- The order on `Booleanisation α` is as follows: For `a b : α`, * `a < b` iff `a < b` in `α` * `a < bᶜ` iff `a` and `b` are disjoint in `α` * `aᶜ < bᶜ` iff `b < a` in `α` * `¬ aᶜ < b` -/ protected inductive LT : Booleanisation α → Booleanisation α → Prop | protected lift {a b} : a < b → Booleanisation.LT (lift a) (lift b) | protected comp {a b} : a < b → Booleanisation.LT (comp b) (comp a) | protected sep {a b} : Disjoint a b → Booleanisation.LT (lift a) (comp b) @[inherit_doc Booleanisation.LE] instance instLE : LE (Booleanisation α) where le := Booleanisation.LE @[inherit_doc Booleanisation.LT] instance instLT : LT (Booleanisation α) where lt := Booleanisation.LT /-- The supremum on `Booleanisation α` is as follows: For `a b : α`, * `a ⊔ b` is `a ⊔ b` * `a ⊔ bᶜ` is `(b \ a)ᶜ` * `aᶜ ⊔ b` is `(a \ b)ᶜ` * `aᶜ ⊔ bᶜ` is `(a ⊓ b)ᶜ` -/ instance instSup : Max (Booleanisation α) where max | lift a, lift b => lift (a ⊔ b) | lift a, comp b => comp (b \ a) | comp a, lift b => comp (a \ b) | comp a, comp b => comp (a ⊓ b) /-- The infimum on `Booleanisation α` is as follows: For `a b : α`, * `a ⊓ b` is `a ⊓ b` * `a ⊓ bᶜ` is `a \ b` * `aᶜ ⊓ b` is `b \ a` * `aᶜ ⊓ bᶜ` is `(a ⊔ b)ᶜ` -/ instance instInf : Min (Booleanisation α) where min | lift a, lift b => lift (a ⊓ b) | lift a, comp b => lift (a \ b) | comp a, lift b => lift (b \ a) | comp a, comp b => comp (a ⊔ b) /-- The bottom element of `Booleanisation α` is the bottom element of `α`. -/ instance instBot : Bot (Booleanisation α) where bot := lift ⊥ /-- The top element of `Booleanisation α` is the complement of the bottom element of `α`. -/ instance instTop : Top (Booleanisation α) where top := comp ⊥ /-- The difference operator on `Booleanisation α` is as follows: For `a b : α`, * `a \ b` is `a \ b` * `a \ bᶜ` is `a ⊓ b` * `aᶜ \ b` is `(a ⊔ b)ᶜ` * `aᶜ \ bᶜ` is `b \ a` -/ instance instSDiff : SDiff (Booleanisation α) where sdiff | lift a, lift b => lift (a \ b) | lift a, comp b => lift (a ⊓ b) | comp a, lift b => comp (a ⊔ b) | comp a, comp b => lift (b \ a) @[simp] lemma lift_le_lift : lift a ≤ lift b ↔ a ≤ b := ⟨by rintro ⟨_⟩; assumption, LE.lift⟩ @[simp] lemma comp_le_comp : comp a ≤ comp b ↔ b ≤ a := ⟨by rintro ⟨_⟩; assumption, LE.comp⟩ @[simp] lemma lift_le_comp : lift a ≤ comp b ↔ Disjoint a b := ⟨by rintro ⟨_⟩; assumption, LE.sep⟩ @[simp] lemma not_comp_le_lift : ¬ comp a ≤ lift b := fun h ↦ nomatch h @[simp] lemma lift_lt_lift : lift a < lift b ↔ a < b := ⟨by rintro ⟨_⟩; assumption, LT.lift⟩ @[simp] lemma comp_lt_comp : comp a < comp b ↔ b < a := ⟨by rintro ⟨_⟩; assumption, LT.comp⟩ @[simp] lemma lift_lt_comp : lift a < comp b ↔ Disjoint a b := ⟨by rintro ⟨_⟩; assumption, LT.sep⟩ @[simp] lemma not_comp_lt_lift : ¬ comp a < lift b := fun h ↦ nomatch h @[simp] lemma lift_sup_lift (a b : α) : lift a ⊔ lift b = lift (a ⊔ b) := rfl @[simp] lemma lift_sup_comp (a b : α) : lift a ⊔ comp b = comp (b \ a) := rfl @[simp] lemma comp_sup_lift (a b : α) : comp a ⊔ lift b = comp (a \ b) := rfl @[simp] lemma comp_sup_comp (a b : α) : comp a ⊔ comp b = comp (a ⊓ b) := rfl @[simp] lemma lift_inf_lift (a b : α) : lift a ⊓ lift b = lift (a ⊓ b) := rfl @[simp] lemma lift_inf_comp (a b : α) : lift a ⊓ comp b = lift (a \ b) := rfl @[simp] lemma comp_inf_lift (a b : α) : comp a ⊓ lift b = lift (b \ a) := rfl @[simp] lemma comp_inf_comp (a b : α) : comp a ⊓ comp b = comp (a ⊔ b) := rfl @[simp] lemma lift_bot : lift (⊥ : α) = ⊥ := rfl @[simp] lemma comp_bot : comp (⊥ : α) = ⊤ := rfl @[simp] lemma lift_sdiff_lift (a b : α) : lift a \ lift b = lift (a \ b) := rfl @[simp] lemma lift_sdiff_comp (a b : α) : lift a \ comp b = lift (a ⊓ b) := rfl @[simp] lemma comp_sdiff_lift (a b : α) : comp a \ lift b = comp (a ⊔ b) := rfl @[simp] lemma comp_sdiff_comp (a b : α) : comp a \ comp b = lift (b \ a) := rfl instance instPreorder : Preorder (Booleanisation α) where lt := (· < ·) lt_iff_le_not_ge | lift a, lift b => by simp [lt_iff_le_not_ge] | lift a, comp b => by simp | comp a, lift b => by simp | comp a, comp b => by simp [lt_iff_le_not_ge] le_refl | lift _ => LE.lift le_rfl | comp _ => LE.comp le_rfl le_trans | lift _, lift _, lift _, LE.lift hab, LE.lift hbc => LE.lift <| hab.trans hbc | lift _, lift _, comp _, LE.lift hab, LE.sep hbc => LE.sep <| hbc.mono_left hab | lift _, comp _, comp _, LE.sep hab, LE.comp hcb => LE.sep <| hab.mono_right hcb | comp _, comp _, comp _, LE.comp hba, LE.comp hcb => LE.comp <| hcb.trans hba instance instPartialOrder : PartialOrder (Booleanisation α) where le_antisymm | lift a, lift b, LE.lift hab, LE.lift hba => by rw [hab.antisymm hba] | comp a, comp b, LE.comp hab, LE.comp hba => by rw [hab.antisymm hba] -- The linter significantly hinders readability here. set_option linter.unusedVariables false in instance instSemilatticeSup : SemilatticeSup (Booleanisation α) where sup x y := max x y le_sup_left | lift a, lift b => LE.lift le_sup_left | lift a, comp b => LE.sep disjoint_sdiff_self_right | comp a, lift b => LE.comp sdiff_le | comp a, comp b => LE.comp inf_le_left le_sup_right | lift a, lift b => LE.lift le_sup_right | lift a, comp b => LE.comp sdiff_le | comp a, lift b => LE.sep disjoint_sdiff_self_right | comp a, comp b => LE.comp inf_le_right sup_le | lift a, lift b, lift c, LE.lift hac, LE.lift hbc => LE.lift <| sup_le hac hbc | lift a, lift b, comp c, LE.sep hac, LE.sep hbc => LE.sep <| hac.sup_left hbc | lift a, comp b, comp c, LE.sep hac, LE.comp hcb => LE.comp <| le_sdiff.2 ⟨hcb, hac.symm⟩ | comp a, lift b, comp c, LE.comp hca, LE.sep hbc => LE.comp <| le_sdiff.2 ⟨hca, hbc.symm⟩ | comp a, comp b, comp c, LE.comp hca, LE.comp hcb => LE.comp <| le_inf hca hcb -- The linter significantly hinders readability here. set_option linter.unusedVariables false in instance instSemilatticeInf : SemilatticeInf (Booleanisation α) where inf x y := min x y inf_le_left | lift a, lift b => LE.lift inf_le_left | lift a, comp b => LE.lift sdiff_le | comp a, lift b => LE.sep disjoint_sdiff_self_left | comp a, comp b => LE.comp le_sup_left inf_le_right | lift a, lift b => LE.lift inf_le_right | lift a, comp b => LE.sep disjoint_sdiff_self_left | comp a, lift b => LE.lift sdiff_le | comp a, comp b => LE.comp le_sup_right le_inf | lift a, lift b, lift c, LE.lift hab, LE.lift hac => LE.lift <| le_inf hab hac | lift a, lift b, comp c, LE.lift hab, LE.sep hac => LE.lift <| le_sdiff.2 ⟨hab, hac⟩ | lift a, comp b, lift c, LE.sep hab, LE.lift hac => LE.lift <| le_sdiff.2 ⟨hac, hab⟩ | lift a, comp b, comp c, LE.sep hab, LE.sep hac => LE.sep <| hab.sup_right hac | comp a, comp b, comp c, LE.comp hba, LE.comp hca => LE.comp <| sup_le hba hca instance instDistribLattice : DistribLattice (Booleanisation α) where inf x y := x ⊓ y inf_le_left _ _ := inf_le_left inf_le_right _ _ := inf_le_right le_inf _ _ _ := le_inf le_sup_inf | lift _, lift _, lift _ => LE.lift le_sup_inf | lift a, lift b, comp c => LE.lift <| by simp [sup_comm, sup_assoc] | lift a, comp b, lift c => LE.lift <| by simp [sup_left_comm (a := b \ a), sup_comm (a := b \ a)] | lift a, comp b, comp c => LE.comp <| by rw [sup_sdiff] | comp a, lift b, lift c => LE.comp <| by rw [sdiff_inf] | comp a, lift b, comp c => LE.comp <| by rw [sdiff_sdiff_right'] | comp a, comp b, lift c => LE.comp <| by rw [sdiff_sdiff_right', sup_comm] | comp _, comp _, comp _ => LE.comp (inf_sup_left _ _ _).le -- The linter significantly hinders readability here. set_option linter.unusedVariables false in instance instBoundedOrder : BoundedOrder (Booleanisation α) where le_top | lift a => LE.sep disjoint_bot_right | comp a => LE.comp bot_le bot_le | lift a => LE.lift bot_le | comp a => LE.sep disjoint_bot_left instance instBooleanAlgebra : BooleanAlgebra (Booleanisation α) where le_top _ := le_top bot_le _ := bot_le inf_compl_le_bot | lift a => by simp | comp a => by simp top_le_sup_compl | lift a => by simp | comp a => by simp sdiff_eq | lift a, lift b => by simp | lift a, comp b => by simp | comp a, lift b => by simp | comp a, comp b => by simp /-- The embedding from a generalised Boolean algebra to its generated Boolean algebra. -/ def liftLatticeHom : LatticeHom α (Booleanisation α) where toFun := lift map_sup' _ _ := rfl map_inf' _ _ := rfl lemma liftLatticeHom_injective : Injective (liftLatticeHom (α := α)) := Sum.inl_injective end Booleanisation
.lake/packages/mathlib/Mathlib/Order/InitialSeg.lean
import Mathlib.Data.Sum.Order import Mathlib.Order.Hom.Lex import Mathlib.Order.RelIso.Set import Mathlib.Order.UpperLower.Basic import Mathlib.Order.WellFounded /-! # Initial and principal segments This file defines initial and principal segment embeddings. Though these definitions make sense for arbitrary relations, they're intended for use with well orders. An initial segment is simply a lower set, i.e. if `x` belongs to the range, then any `y < x` also belongs to the range. A principal segment is a set of the form `Set.Iio x` for some `x`. An initial segment embedding `r ≼i s` is an order embedding `r ↪ s` such that its range is an initial segment. Likewise, a principal segment embedding `r ≺i s` has a principal segment for a range. ## Main definitions * `InitialSeg r s`: Type of initial segment embeddings of `r` into `s`, denoted by `r ≼i s`. * `PrincipalSeg r s`: Type of principal segment embeddings of `r` into `s`, denoted by `r ≺i s`. The lemmas `Ordinal.type_le_iff` and `Ordinal.type_lt_iff` tell us that `≼i` corresponds to the `≤` relation on ordinals, while `≺i` corresponds to the `<` relation. This prompts us to think of `PrincipalSeg` as a "strict" version of `InitialSeg`. ## Notation These notations belong to the `InitialSeg` locale. * `r ≼i s`: the type of initial segment embeddings of `r` into `s`. * `r ≺i s`: the type of principal segment embeddings of `r` into `s`. * `α ≤i β` is an abbreviation for `(· < ·) ≼i (· < ·)`. * `α <i β` is an abbreviation for `(· < ·) ≺i (· < ·)`. -/ /-! ### Initial segment embeddings -/ universe u variable {α β γ : Type*} {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop} open Function /-- If `r` is a relation on `α` and `s` in a relation on `β`, then `f : r ≼i s` is an order embedding whose `Set.range` is a lower set. That is, whenever `b < f a` in `β` then `b` is in the range of `f`. -/ structure InitialSeg {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) extends r ↪r s where /-- The order embedding is an initial segment -/ mem_range_of_rel' : ∀ a b, s b (toRelEmbedding a) → b ∈ Set.range toRelEmbedding @[inherit_doc] scoped[InitialSeg] infixl:25 " ≼i " => InitialSeg /-- An `InitialSeg` between the `<` relations of two types. -/ notation:25 α:24 " ≤i " β:25 => @InitialSeg α β (· < ·) (· < ·) namespace InitialSeg instance : Coe (r ≼i s) (r ↪r s) := ⟨InitialSeg.toRelEmbedding⟩ instance : FunLike (r ≼i s) α β where coe f := f.toFun coe_injective' := by rintro ⟨f, hf⟩ ⟨g, hg⟩ h congr with x exact congr_fun h x instance : EmbeddingLike (r ≼i s) α β where injective' f := f.inj' instance : RelHomClass (r ≼i s) r s where map_rel f := f.map_rel_iff.2 /-- An initial segment embedding between the `<` relations of two partial orders is an order embedding. -/ def toOrderEmbedding [PartialOrder α] [PartialOrder β] (f : α ≤i β) : α ↪o β := f.orderEmbeddingOfLTEmbedding @[simp] theorem toOrderEmbedding_apply [PartialOrder α] [PartialOrder β] (f : α ≤i β) (x : α) : f.toOrderEmbedding x = f x := rfl @[simp] theorem coe_toOrderEmbedding [PartialOrder α] [PartialOrder β] (f : α ≤i β) : (f.toOrderEmbedding : α → β) = f := rfl instance [PartialOrder α] [PartialOrder β] : OrderHomClass (α ≤i β) α β where map_rel f := f.toOrderEmbedding.map_rel_iff.2 @[ext] lemma ext {f g : r ≼i s} (h : ∀ x, f x = g x) : f = g := DFunLike.ext f g h @[simp] theorem coe_coe_fn (f : r ≼i s) : ((f : r ↪r s) : α → β) = f := rfl theorem mem_range_of_rel (f : r ≼i s) {a : α} {b : β} : s b (f a) → b ∈ Set.range f := f.mem_range_of_rel' _ _ theorem map_rel_iff {a b : α} (f : r ≼i s) : s (f a) (f b) ↔ r a b := f.map_rel_iff' theorem inj (f : r ≼i s) {a b : α} : f a = f b ↔ a = b := f.toRelEmbedding.inj theorem exists_eq_iff_rel (f : r ≼i s) {a : α} {b : β} : s b (f a) ↔ ∃ a', f a' = b ∧ r a' a := ⟨fun h => by rcases f.mem_range_of_rel h with ⟨a', rfl⟩ exact ⟨a', rfl, f.map_rel_iff.1 h⟩, fun ⟨_, e, h⟩ => e ▸ f.map_rel_iff.2 h⟩ /-- A relation isomorphism is an initial segment embedding -/ @[simps!] def _root_.RelIso.toInitialSeg (f : r ≃r s) : r ≼i s := ⟨f, by simp⟩ /-- The identity function shows that `≼i` is reflexive -/ @[refl] protected def refl (r : α → α → Prop) : r ≼i r := (RelIso.refl r).toInitialSeg instance (r : α → α → Prop) : Inhabited (r ≼i r) := ⟨InitialSeg.refl r⟩ /-- Composition of functions shows that `≼i` is transitive -/ @[trans] protected def trans (f : r ≼i s) (g : s ≼i t) : r ≼i t := ⟨f.1.trans g.1, fun a c h => by simp only [RelEmbedding.coe_trans, coe_coe_fn, comp_apply] at h ⊢ rcases g.2 _ _ h with ⟨b, rfl⟩; have h := g.map_rel_iff.1 h rcases f.2 _ _ h with ⟨a', rfl⟩; exact ⟨a', rfl⟩⟩ @[simp] theorem refl_apply (x : α) : InitialSeg.refl r x = x := rfl @[simp] theorem trans_apply (f : r ≼i s) (g : s ≼i t) (a : α) : (f.trans g) a = g (f a) := rfl instance subsingleton_of_trichotomous_of_irrefl [IsTrichotomous β s] [IsIrrefl β s] [IsWellFounded α r] : Subsingleton (r ≼i s) where allEq f g := by ext a refine IsWellFounded.induction r a fun b IH => extensional_of_trichotomous_of_irrefl s fun x => ?_ rw [f.exists_eq_iff_rel, g.exists_eq_iff_rel] exact exists_congr fun x => and_congr_left fun hx => IH _ hx ▸ Iff.rfl /-- Given a well order `s`, there is at most one initial segment embedding of `r` into `s`. -/ instance [IsWellOrder β s] : Subsingleton (r ≼i s) := ⟨fun a => have := a.isWellFounded; Subsingleton.elim a⟩ protected theorem eq [IsWellOrder β s] (f g : r ≼i s) (a) : f a = g a := by rw [Subsingleton.elim f g] theorem eq_relIso [IsWellOrder β s] (f : r ≼i s) (g : r ≃r s) (a : α) : g a = f a := InitialSeg.eq g.toInitialSeg f a private theorem antisymm_aux [IsWellOrder α r] (f : r ≼i s) (g : s ≼i r) : LeftInverse g f := (f.trans g).eq (InitialSeg.refl _) /-- If we have order embeddings between `α` and `β` whose ranges are initial segments, and `β` is a well order, then `α` and `β` are order-isomorphic. -/ def antisymm [IsWellOrder β s] (f : r ≼i s) (g : s ≼i r) : r ≃r s := have := f.toRelEmbedding.isWellOrder ⟨⟨f, g, antisymm_aux f g, antisymm_aux g f⟩, f.map_rel_iff'⟩ @[simp] theorem antisymm_toFun [IsWellOrder β s] (f : r ≼i s) (g : s ≼i r) : (antisymm f g : α → β) = f := rfl @[simp] theorem antisymm_symm [IsWellOrder α r] [IsWellOrder β s] (f : r ≼i s) (g : s ≼i r) : (antisymm f g).symm = antisymm g f := RelIso.coe_fn_injective rfl /-- An initial segment embedding is either an isomorphism, or a principal segment embedding. See also `InitialSeg.ltOrEq`. -/ theorem eq_or_principal [IsWellOrder β s] (f : r ≼i s) : Surjective f ∨ ∃ b, ∀ x, x ∈ Set.range f ↔ s x b := by apply or_iff_not_imp_right.2 intro h b push_neg at h apply IsWellFounded.induction s b intro x IH obtain ⟨y, ⟨hy, hs⟩ | ⟨hy, hs⟩⟩ := h x · obtain (rfl | h) := (trichotomous y x).resolve_left hs · exact hy · obtain ⟨z, rfl⟩ := hy exact f.mem_range_of_rel h · obtain ⟨z, rfl⟩ := IH y hs cases hy (Set.mem_range_self z) /-- Restrict the codomain of an initial segment -/ def codRestrict (p : Set β) (f : r ≼i s) (H : ∀ a, f a ∈ p) : r ≼i Subrel s (· ∈ p) := ⟨RelEmbedding.codRestrict p f H, fun a ⟨b, m⟩ h => let ⟨a', e⟩ := f.mem_range_of_rel h ⟨a', by subst e; rfl⟩⟩ @[simp] theorem codRestrict_apply (p) (f : r ≼i s) (H a) : codRestrict p f H a = ⟨f a, H a⟩ := rfl /-- Initial segment embedding from an empty type. -/ def ofIsEmpty (r : α → α → Prop) (s : β → β → Prop) [IsEmpty α] : r ≼i s := ⟨RelEmbedding.ofIsEmpty r s, isEmptyElim⟩ /-- Initial segment embedding of an order `r` into the disjoint union of `r` and `s`. -/ def leAdd (r : α → α → Prop) (s : β → β → Prop) : r ≼i Sum.Lex r s := ⟨⟨⟨Sum.inl, fun _ _ => Sum.inl.inj⟩, Sum.lex_inl_inl⟩, fun a b => by cases b <;> [exact fun _ => ⟨_, rfl⟩; exact False.elim ∘ Sum.lex_inr_inl]⟩ @[simp] theorem leAdd_apply (r : α → α → Prop) (s : β → β → Prop) (a) : leAdd r s a = Sum.inl a := rfl protected theorem acc (f : r ≼i s) (a : α) : Acc r a ↔ Acc s (f a) := ⟨by refine fun h => Acc.recOn h fun a _ ha => Acc.intro _ fun b hb => ?_ obtain ⟨a', rfl⟩ := f.mem_range_of_rel hb exact ha _ (f.map_rel_iff.mp hb), f.toRelEmbedding.acc a⟩ end InitialSeg /-! ### Principal segments -/ /-- If `r` is a relation on `α` and `s` in a relation on `β`, then `f : r ≺i s` is an initial segment embedding whose range is `Set.Iio x` for some element `x`. If `β` is a well order, this is equivalent to the embedding not being surjective. -/ structure PrincipalSeg {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) extends r ↪r s where /-- The supremum of the principal segment -/ top : β /-- The range of the order embedding is the set of elements `b` such that `s b top` -/ mem_range_iff_rel' : ∀ b, b ∈ Set.range toRelEmbedding ↔ s b top @[inherit_doc] scoped[InitialSeg] infixl:25 " ≺i " => PrincipalSeg /-- A `PrincipalSeg` between the `<` relations of two types. -/ notation:25 α:24 " <i " β:25 => @PrincipalSeg α β (· < ·) (· < ·) open scoped InitialSeg namespace PrincipalSeg instance : CoeOut (r ≺i s) (r ↪r s) := ⟨PrincipalSeg.toRelEmbedding⟩ instance : CoeFun (r ≺i s) fun _ => α → β := ⟨fun f => f⟩ theorem toRelEmbedding_injective [IsIrrefl β s] [IsTrichotomous β s] : Function.Injective (@toRelEmbedding α β r s) := by rintro ⟨f, a, hf⟩ ⟨g, b, hg⟩ rfl congr refine extensional_of_trichotomous_of_irrefl s fun x ↦ ?_ rw [← hf, hg] @[simp] theorem toRelEmbedding_inj [IsIrrefl β s] [IsTrichotomous β s] {f g : r ≺i s} : f.toRelEmbedding = g.toRelEmbedding ↔ f = g := toRelEmbedding_injective.eq_iff @[ext] theorem ext [IsIrrefl β s] [IsTrichotomous β s] {f g : r ≺i s} (h : ∀ x, f x = g x) : f = g := by rw [← toRelEmbedding_inj] ext exact h _ @[simp] theorem coe_fn_mk (f : r ↪r s) (t o) : (@PrincipalSeg.mk _ _ r s f t o : α → β) = f := rfl theorem mem_range_iff_rel (f : r ≺i s) : ∀ {b : β}, b ∈ Set.range f ↔ s b f.top := f.mem_range_iff_rel' _ theorem lt_top (f : r ≺i s) (a : α) : s (f a) f.top := f.mem_range_iff_rel.1 ⟨_, rfl⟩ theorem mem_range_of_rel_top (f : r ≺i s) {b : β} (h : s b f.top) : b ∈ Set.range f := f.mem_range_iff_rel.2 h theorem mem_range_of_rel [IsTrans β s] (f : r ≺i s) {a : α} {b : β} (h : s b (f a)) : b ∈ Set.range f := f.mem_range_of_rel_top <| _root_.trans h <| f.lt_top _ theorem surjOn (f : r ≺i s) : Set.SurjOn f Set.univ { b | s b f.top } := by intro b h simpa using mem_range_of_rel_top _ h /-- A principal segment embedding is in particular an initial segment embedding. -/ instance hasCoeInitialSeg [IsTrans β s] : Coe (r ≺i s) (r ≼i s) := ⟨fun f => ⟨f.toRelEmbedding, fun _ _ => f.mem_range_of_rel⟩⟩ theorem coe_coe_fn' [IsTrans β s] (f : r ≺i s) : ((f : r ≼i s) : α → β) = f := rfl theorem _root_.InitialSeg.eq_principalSeg [IsWellOrder β s] (f : r ≼i s) (g : r ≺i s) (a : α) : g a = f a := InitialSeg.eq g f a theorem exists_eq_iff_rel [IsTrans β s] (f : r ≺i s) {a : α} {b : β} : s b (f a) ↔ ∃ a', f a' = b ∧ r a' a := @InitialSeg.exists_eq_iff_rel α β r s f a b /-- A principal segment is the same as a non-surjective initial segment. -/ noncomputable def _root_.InitialSeg.toPrincipalSeg [IsWellOrder β s] (f : r ≼i s) (hf : ¬ Surjective f) : r ≺i s := ⟨f, _, Classical.choose_spec (f.eq_or_principal.resolve_left hf)⟩ @[simp] theorem _root_.InitialSeg.toPrincipalSeg_apply [IsWellOrder β s] (f : r ≼i s) (hf : ¬ Surjective f) (x : α) : f.toPrincipalSeg hf x = f x := rfl theorem irrefl {r : α → α → Prop} [IsWellOrder α r] (f : r ≺i r) : False := by have h := f.lt_top f.top rw [show f f.top = f.top from InitialSeg.eq f (InitialSeg.refl r) f.top] at h exact _root_.irrefl _ h instance (r : α → α → Prop) [IsWellOrder α r] : IsEmpty (r ≺i r) := ⟨fun f => f.irrefl⟩ /-- Composition of a principal segment embedding with an initial segment embedding, as a principal segment embedding -/ def transInitial (f : r ≺i s) (g : s ≼i t) : r ≺i t := ⟨@RelEmbedding.trans _ _ _ r s t f g, g f.top, fun a => by simp [g.exists_eq_iff_rel, ← PrincipalSeg.mem_range_iff_rel, exists_swap, ← exists_and_left]⟩ @[simp] theorem transInitial_apply (f : r ≺i s) (g : s ≼i t) (a : α) : f.transInitial g a = g (f a) := rfl @[simp] theorem transInitial_top (f : r ≺i s) (g : s ≼i t) : (f.transInitial g).top = g f.top := rfl /-- Composition of two principal segment embeddings as a principal segment embedding -/ @[trans] protected def trans [IsTrans γ t] (f : r ≺i s) (g : s ≺i t) : r ≺i t := transInitial f g @[simp] theorem trans_apply [IsTrans γ t] (f : r ≺i s) (g : s ≺i t) (a : α) : f.trans g a = g (f a) := rfl @[simp] theorem trans_top [IsTrans γ t] (f : r ≺i s) (g : s ≺i t) : (f.trans g).top = g f.top := rfl /-- Composition of an order isomorphism with a principal segment embedding, as a principal segment embedding -/ def relIsoTrans (f : r ≃r s) (g : s ≺i t) : r ≺i t := ⟨@RelEmbedding.trans _ _ _ r s t f g, g.top, fun c => by simp [g.mem_range_iff_rel]⟩ @[simp] theorem relIsoTrans_apply (f : r ≃r s) (g : s ≺i t) (a : α) : relIsoTrans f g a = g (f a) := rfl @[simp] theorem relIsoTrans_top (f : r ≃r s) (g : s ≺i t) : (relIsoTrans f g).top = g.top := rfl /-- Composition of a principal segment embedding with a relation isomorphism, as a principal segment embedding -/ def transRelIso (f : r ≺i s) (g : s ≃r t) : r ≺i t := transInitial f g.toInitialSeg @[simp] theorem transRelIso_apply (f : r ≺i s) (g : s ≃r t) (a : α) : transRelIso f g a = g (f a) := rfl @[simp] theorem transRelIso_top (f : r ≺i s) (g : s ≃r t) : (transRelIso f g).top = g f.top := rfl /-- Given a well order `s`, there is a most one principal segment embedding of `r` into `s`. -/ instance [IsWellOrder β s] : Subsingleton (r ≺i s) where allEq f g := ext ((f : r ≼i s).eq g) protected theorem eq [IsWellOrder β s] (f g : r ≺i s) (a) : f a = g a := by rw [Subsingleton.elim f g] theorem top_eq [IsWellOrder γ t] (e : r ≃r s) (f : r ≺i t) (g : s ≺i t) : f.top = g.top := by rw [Subsingleton.elim f (PrincipalSeg.relIsoTrans e g)]; rfl theorem top_rel_top {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop} [IsWellOrder γ t] (f : r ≺i s) (g : s ≺i t) (h : r ≺i t) : t h.top g.top := by rw [Subsingleton.elim h (f.trans g)] apply PrincipalSeg.lt_top /-- Any element of a well order yields a principal segment. -/ @[simps!] def ofElement {α : Type*} (r : α → α → Prop) (a : α) : Subrel r (r · a) ≺i r := ⟨Subrel.relEmbedding _ _, a, fun _ => ⟨fun ⟨⟨_, h⟩, rfl⟩ => h, fun h => ⟨⟨_, h⟩, rfl⟩⟩⟩ @[simp] theorem ofElement_apply {α : Type*} (r : α → α → Prop) (a : α) (b) : ofElement r a b = b.1 := rfl /-- For any principal segment `r ≺i s`, there is a `Subrel` of `s` order isomorphic to `r`. -/ @[simps! symm_apply] noncomputable def subrelIso (f : r ≺i s) : Subrel s (s · f.top) ≃r r := RelIso.symm ⟨(Equiv.ofInjective f f.injective).trans (Equiv.setCongr (funext fun _ ↦ propext f.mem_range_iff_rel)), f.map_rel_iff⟩ @[simp] theorem apply_subrelIso (f : r ≺i s) (b : {b // s b f.top}) : f (f.subrelIso b) = b := Equiv.apply_ofInjective_symm f.injective _ @[simp] theorem subrelIso_apply (f : r ≺i s) (a : α) : f.subrelIso ⟨f a, f.lt_top a⟩ = a := Equiv.ofInjective_symm_apply f.injective _ /-- Restrict the codomain of a principal segment embedding. -/ def codRestrict (p : Set β) (f : r ≺i s) (H : ∀ a, f a ∈ p) (H₂ : f.top ∈ p) : r ≺i Subrel s (· ∈ p) := ⟨RelEmbedding.codRestrict p f H, ⟨f.top, H₂⟩, fun ⟨_, _⟩ => by simp [← f.mem_range_iff_rel]⟩ @[simp] theorem codRestrict_apply (p) (f : r ≺i s) (H H₂ a) : codRestrict p f H H₂ a = ⟨f a, H a⟩ := rfl @[simp] theorem codRestrict_top (p) (f : r ≺i s) (H H₂) : (codRestrict p f H H₂).top = ⟨f.top, H₂⟩ := rfl /-- Principal segment from an empty type into a type with a minimal element. -/ def ofIsEmpty (r : α → α → Prop) [IsEmpty α] {b : β} (H : ∀ b', ¬s b' b) : r ≺i s := { RelEmbedding.ofIsEmpty r s with top := b mem_range_iff_rel' := by simp [H] } @[simp] theorem ofIsEmpty_top (r : α → α → Prop) [IsEmpty α] {b : β} (H : ∀ b', ¬s b' b) : (ofIsEmpty r H).top = b := rfl /-- Principal segment from the empty relation on `PEmpty` to the empty relation on `PUnit`. -/ abbrev pemptyToPunit : @EmptyRelation PEmpty ≺i @EmptyRelation PUnit := (@ofIsEmpty _ _ EmptyRelation _ _ PUnit.unit) fun _ => not_false protected theorem acc [IsTrans β s] (f : r ≺i s) (a : α) : Acc r a ↔ Acc s (f a) := (f : r ≼i s).acc a end PrincipalSeg theorem wellFounded_iff_principalSeg {β : Type u} {s : β → β → Prop} [IsTrans β s] : WellFounded s ↔ ∀ (α : Type u) (r : α → α → Prop) (_ : r ≺i s), WellFounded r := ⟨fun wf _ _ f => RelHomClass.wellFounded f.toRelEmbedding wf, fun h => wellFounded_iff_wellFounded_subrel.mpr fun b => h _ _ (PrincipalSeg.ofElement s b)⟩ /-! ### Properties of initial and principal segments -/ namespace InitialSeg open Classical in /-- Every initial segment embedding into a well order can be turned into an isomorphism if surjective, or into a principal segment embedding if not. -/ noncomputable def principalSumRelIso [IsWellOrder β s] (f : r ≼i s) : (r ≺i s) ⊕ (r ≃r s) := if h : Surjective f then Sum.inr (RelIso.ofSurjective f h) else Sum.inl (f.toPrincipalSeg h) /-- Composition of an initial segment embedding and a principal segment embedding as a principal segment embedding -/ noncomputable def transPrincipal [IsWellOrder β s] [IsTrans γ t] (f : r ≼i s) (g : s ≺i t) : r ≺i t := match f.principalSumRelIso with | Sum.inl f' => f'.trans g | Sum.inr f' => PrincipalSeg.relIsoTrans f' g @[simp] theorem transPrincipal_apply [IsWellOrder β s] [IsTrans γ t] (f : r ≼i s) (g : s ≺i t) (a : α) : f.transPrincipal g a = g (f a) := by rw [InitialSeg.transPrincipal] obtain f' | f' := f.principalSumRelIso · rw [PrincipalSeg.trans_apply, f.eq_principalSeg] · rw [PrincipalSeg.relIsoTrans_apply, f.eq_relIso] /-- An initial segment can be extended to an isomorphism by joining a second well order to the domain. -/ theorem exists_sum_relIso {β : Type u} {s : β → β → Prop} [IsWellOrder β s] (f : r ≼i s) : ∃ (γ : Type u) (t : γ → γ → Prop), IsWellOrder γ t ∧ Nonempty (Sum.Lex r t ≃r s) := by classical obtain f | f := f.principalSumRelIso · exact ⟨_, _, inferInstance, ⟨(RelIso.sumLexCongr f.subrelIso.symm (.refl _)).trans <| .sumLexComplLeft ..⟩⟩ · exact ⟨PEmpty, nofun, inferInstance, ⟨(RelIso.sumLexEmpty r _).trans f⟩⟩ end InitialSeg /-- The function in `collapse`. -/ private noncomputable def collapseF [IsWellOrder β s] (f : r ↪r s) : Π a, { b // ¬s (f a) b } := (RelEmbedding.isWellFounded f).fix _ fun a IH => have H : f a ∈ { b | ∀ a h, s (IH a h).1 b } := fun b h => trans_trichotomous_left (IH b h).2 (f.map_rel_iff.2 h) ⟨_, IsWellFounded.wf.not_lt_min _ ⟨_, H⟩ H⟩ private theorem collapseF_lt [IsWellOrder β s] (f : r ↪r s) {a : α} : ∀ {a'}, r a' a → s (collapseF f a') (collapseF f a) := by change _ ∈ { b | ∀ a', r a' a → s (collapseF f a') b } rw [collapseF, IsWellFounded.fix_eq] dsimp only exact WellFounded.min_mem _ _ _ private theorem collapseF_not_lt [IsWellOrder β s] (f : r ↪r s) (a : α) {b} (h : ∀ a', r a' a → s (collapseF f a') b) : ¬s b (collapseF f a) := by rw [collapseF, IsWellFounded.fix_eq] dsimp only exact WellFounded.not_lt_min _ _ _ h /-- Construct an initial segment embedding `r ≼i s` by "filling in the gaps". That is, each subsequent element in `α` is mapped to the least element in `β` that hasn't been used yet. This construction is guaranteed to work as long as there exists some relation embedding `r ↪r s`. -/ noncomputable def RelEmbedding.collapse [IsWellOrder β s] (f : r ↪r s) : r ≼i s := have H := RelEmbedding.isWellOrder f ⟨RelEmbedding.ofMonotone _ fun a b => collapseF_lt f, fun a b h ↦ by obtain ⟨m, hm, hm'⟩ := H.wf.has_min { a | ¬s _ b } ⟨_, asymm h⟩ use m obtain lt | rfl | gt := trichotomous_of s b (collapseF f m) · refine (collapseF_not_lt f m (fun c h ↦ ?_) lt).elim by_contra hn exact hm' _ hn h · rfl · exact (hm gt).elim⟩ /-- For any two well orders, one is an initial segment of the other. -/ noncomputable def InitialSeg.total (r s) [IsWellOrder α r] [IsWellOrder β s] : (r ≼i s) ⊕ (s ≼i r) := match (leAdd r s).principalSumRelIso, (RelEmbedding.sumLexInr r s).collapse.principalSumRelIso with | Sum.inl f, Sum.inr g => Sum.inl <| f.transRelIso g.symm | Sum.inr f, Sum.inl g => Sum.inr <| g.transRelIso f.symm | Sum.inr f, Sum.inr g => Sum.inl <| (f.trans g.symm).toInitialSeg | Sum.inl f, Sum.inl g => Classical.choice <| by obtain h | h | h := trichotomous_of (Sum.Lex r s) f.top g.top · exact ⟨Sum.inl <| (f.codRestrict {x | Sum.Lex r s x g.top} (fun a => _root_.trans (f.lt_top a) h) h).transRelIso g.subrelIso⟩ · let f := f.subrelIso rw [h] at f exact ⟨Sum.inl <| (f.symm.trans g.subrelIso).toInitialSeg⟩ · exact ⟨Sum.inr <| (g.codRestrict {x | Sum.Lex r s x f.top} (fun a => _root_.trans (g.lt_top a) h) h).transRelIso f.subrelIso⟩ /-! ### Initial or principal segments with `<` -/ namespace InitialSeg /-- An order isomorphism is an initial segment -/ @[simps!] def _root_.OrderIso.toInitialSeg [Preorder α] [Preorder β] (f : α ≃o β) : α ≤i β := f.toRelIsoLT.toInitialSeg variable [PartialOrder β] {a a' : α} {b : β} theorem mem_range_of_le [LT α] (f : α ≤i β) (h : b ≤ f a) : b ∈ Set.range f := by obtain rfl | hb := h.eq_or_lt exacts [⟨a, rfl⟩, f.mem_range_of_rel hb] theorem isLowerSet_range [LT α] (f : α ≤i β) : IsLowerSet (Set.range f) := by rintro _ b h ⟨a, rfl⟩ exact mem_range_of_le f h -- TODO: this would follow immediately if we had a `RelEmbeddingClass` @[simp] theorem le_iff_le [PartialOrder α] (f : α ≤i β) : f a ≤ f a' ↔ a ≤ a' := f.toOrderEmbedding.le_iff_le -- TODO: this would follow immediately if we had a `RelEmbeddingClass` @[simp] theorem lt_iff_lt [PartialOrder α] (f : α ≤i β) : f a < f a' ↔ a < a' := f.toOrderEmbedding.lt_iff_lt theorem monotone [PartialOrder α] (f : α ≤i β) : Monotone f := f.toOrderEmbedding.monotone theorem strictMono [PartialOrder α] (f : α ≤i β) : StrictMono f := f.toOrderEmbedding.strictMono @[simp] theorem isMin_apply_iff [PartialOrder α] (f : α ≤i β) : IsMin (f a) ↔ IsMin a := by refine ⟨StrictMono.isMin_of_apply f.strictMono, fun h b hb ↦ ?_⟩ obtain ⟨x, rfl⟩ := f.mem_range_of_le hb rw [f.le_iff_le] at hb ⊢ exact h hb alias ⟨_, map_isMin⟩ := isMin_apply_iff @[simp] theorem map_bot [PartialOrder α] [OrderBot α] [OrderBot β] (f : α ≤i β) : f ⊥ = ⊥ := (map_isMin f isMin_bot).eq_bot theorem image_Iio [PartialOrder α] (f : α ≤i β) (a : α) : f '' Set.Iio a = Set.Iio (f a) := f.toOrderEmbedding.image_Iio f.isLowerSet_range a theorem le_apply_iff [PartialOrder α] (f : α ≤i β) : b ≤ f a ↔ ∃ c ≤ a, f c = b := by constructor · intro h obtain ⟨c, hc⟩ := f.mem_range_of_le h refine ⟨c, ?_, hc⟩ rwa [← hc, f.le_iff_le] at h · rintro ⟨c, hc, rfl⟩ exact f.monotone hc theorem lt_apply_iff [PartialOrder α] (f : α ≤i β) : b < f a ↔ ∃ a' < a, f a' = b := by constructor · intro h obtain ⟨c, hc⟩ := f.mem_range_of_rel h refine ⟨c, ?_, hc⟩ rwa [← hc, f.lt_iff_lt] at h · rintro ⟨c, hc, rfl⟩ exact f.strictMono hc end InitialSeg namespace PrincipalSeg variable [PartialOrder β] {a a' : α} {b : β} theorem mem_range_of_le [LT α] (f : α <i β) (h : b ≤ f a) : b ∈ Set.range f := (f : α ≤i β).mem_range_of_le h theorem isLowerSet_range [LT α] (f : α <i β) : IsLowerSet (Set.range f) := (f : α ≤i β).isLowerSet_range -- TODO: this would follow immediately if we had a `RelEmbeddingClass` @[simp] theorem le_iff_le [PartialOrder α] (f : α <i β) : f a ≤ f a' ↔ a ≤ a' := (f : α ≤i β).le_iff_le -- TODO: this would follow immediately if we had a `RelEmbeddingClass` @[simp] theorem lt_iff_lt [PartialOrder α] (f : α <i β) : f a < f a' ↔ a < a' := (f : α ≤i β).lt_iff_lt theorem monotone [PartialOrder α] (f : α <i β) : Monotone f := (f : α ≤i β).monotone theorem strictMono [PartialOrder α] (f : α <i β) : StrictMono f := (f : α ≤i β).strictMono @[simp] theorem isMin_apply_iff [PartialOrder α] (f : α <i β) : IsMin (f a) ↔ IsMin a := (f : α ≤i β).isMin_apply_iff alias ⟨_, map_isMin⟩ := isMin_apply_iff @[simp] theorem map_bot [PartialOrder α] [OrderBot α] [OrderBot β] (f : α <i β) : f ⊥ = ⊥ := (f : α ≤i β).map_bot theorem image_Iio [PartialOrder α] (f : α <i β) (a : α) : f '' Set.Iio a = Set.Iio (f a) := (f : α ≤i β).image_Iio a theorem le_apply_iff [PartialOrder α] (f : α <i β) : b ≤ f a ↔ ∃ c ≤ a, f c = b := (f : α ≤i β).le_apply_iff theorem lt_apply_iff [PartialOrder α] (f : α <i β) : b < f a ↔ ∃ a' < a, f a' = b := (f : α ≤i β).lt_apply_iff end PrincipalSeg
.lake/packages/mathlib/Mathlib/Order/Shrink.lean
import Mathlib.Order.SuccPred.Basic import Mathlib.Logic.Small.Defs /-! # Order instances on Shrink If `α : Type v` is `u`-small, we transport various order related instances on `α` to `Shrink.{u} α`. -/ universe u v variable (α : Type v) [Small.{u} α] instance [Preorder α] : Preorder (Shrink.{u} α) where le a b := (equivShrink α).symm a ≤ (equivShrink _).symm b le_refl a := le_refl _ le_trans _ _ _ h₁ h₂ := h₁.trans h₂ /-- The order isomorphism `α ≃o Shrink.{u} α`. -/ noncomputable def orderIsoShrink [Preorder α] : α ≃o Shrink.{u} α where toEquiv := equivShrink α map_rel_iff' {a b} := by obtain ⟨a, rfl⟩ := (equivShrink.{u} α).symm.surjective a obtain ⟨b, rfl⟩ := (equivShrink.{u} α).symm.surjective b simp only [Equiv.apply_symm_apply] rfl variable {α} @[simp] lemma orderIsoShrink_apply [Preorder α] (a : α) : orderIsoShrink α a = equivShrink α a := rfl @[simp] lemma orderIsoShrink_symm_apply [Preorder α] (a : Shrink.{u} α) : (orderIsoShrink α).symm a = (equivShrink α).symm a := rfl instance [PartialOrder α] : PartialOrder (Shrink.{u} α) where le_antisymm _ _ h₁ h₂ := (equivShrink _).symm.injective (le_antisymm h₁ h₂) noncomputable instance [LinearOrder α] : LinearOrder (Shrink.{u} α) where le_total _ _ := le_total _ _ toDecidableLE _ _ := LinearOrder.toDecidableLE _ _ noncomputable instance [Bot α] : Bot (Shrink.{u} α) where bot := equivShrink _ ⊥ @[simp] lemma equivShrink_bot [Bot α] : equivShrink.{u} α ⊥ = ⊥ := rfl @[simp] lemma equivShrink_symm_bot [Bot α] : (equivShrink.{u} α).symm ⊥ = ⊥ := (equivShrink.{u} α).injective (by simp) noncomputable instance [Top α] : Top (Shrink.{u} α) where top := equivShrink _ ⊤ @[simp] lemma equivShrink_top [Top α] : equivShrink.{u} α ⊤ = ⊤ := rfl @[simp] lemma equivShrink_symm_top [Top α] : (equivShrink.{u} α).symm ⊤ = ⊤ := (equivShrink.{u} α).injective (by simp) section Preorder variable [Preorder α] noncomputable instance [OrderBot α] : OrderBot (Shrink.{u} α) where bot_le a := by simp only [← (orderIsoShrink.{u} α).symm.le_iff_le, orderIsoShrink_symm_apply, equivShrink_symm_bot, bot_le] noncomputable instance [OrderTop α] : OrderTop (Shrink.{u} α) where le_top a := by simp only [← (orderIsoShrink.{u} α).symm.le_iff_le, orderIsoShrink_symm_apply, equivShrink_symm_top, le_top] noncomputable instance [SuccOrder α] : SuccOrder (Shrink.{u} α) := SuccOrder.ofOrderIso (orderIsoShrink.{u} α) noncomputable instance [PredOrder α] : PredOrder (Shrink.{u} α) := PredOrder.ofOrderIso (orderIsoShrink.{u} α) instance [WellFoundedLT α] : WellFoundedLT (Shrink.{u} α) where wf := (orderIsoShrink.{u} α).symm.toRelIsoLT.toRelEmbedding.isWellFounded.wf end Preorder
.lake/packages/mathlib/Mathlib/Order/Set.lean
import Mathlib.Data.Set.Image import Mathlib.Order.TypeTags /-! # `Set.range` on `WithBot` and `WithTop` -/ open Set variable {α β : Type*} theorem WithBot.range_eq (f : WithBot α → β) : range f = insert (f ⊥) (range (f ∘ WithBot.some : α → β)) := Option.range_eq f theorem WithTop.range_eq (f : WithTop α → β) : range f = insert (f ⊤) (range (f ∘ WithBot.some : α → β)) := Option.range_eq f
.lake/packages/mathlib/Mathlib/Order/CompleteSublattice.lean
import Mathlib.Data.Set.Functor import Mathlib.Order.Sublattice import Mathlib.Order.Hom.CompleteLattice /-! # Complete Sublattices This file defines complete sublattices. These are subsets of complete lattices which are closed under arbitrary suprema and infima. As a standard example one could take the complete sublattice of invariant submodules of some module with respect to a linear map. ## Main definitions: * `CompleteSublattice`: the definition of a complete sublattice * `CompleteSublattice.mk'`: an alternate constructor for a complete sublattice, demanding fewer hypotheses * `CompleteSublattice.instCompleteLattice`: a complete sublattice is a complete lattice * `CompleteSublattice.map`: complete sublattices push forward under complete lattice morphisms. * `CompleteSublattice.comap`: complete sublattices pull back under complete lattice morphisms. -/ open Function Set variable (α β : Type*) [CompleteLattice α] [CompleteLattice β] (f : CompleteLatticeHom α β) /-- A complete sublattice is a subset of a complete lattice that is closed under arbitrary suprema and infima. -/ structure CompleteSublattice extends Sublattice α where sSupClosed' : ∀ ⦃s : Set α⦄, s ⊆ carrier → sSup s ∈ carrier sInfClosed' : ∀ ⦃s : Set α⦄, s ⊆ carrier → sInf s ∈ carrier variable {α β} namespace CompleteSublattice /-- To check that a subset is a complete sublattice, one does not need to check that it is closed under binary `Sup` since this follows from the stronger `sSup` condition. Likewise for infima. -/ @[simps] def mk' (carrier : Set α) (sSupClosed' : ∀ ⦃s : Set α⦄, s ⊆ carrier → sSup s ∈ carrier) (sInfClosed' : ∀ ⦃s : Set α⦄, s ⊆ carrier → sInf s ∈ carrier) : CompleteSublattice α where carrier := carrier sSupClosed' := sSupClosed' sInfClosed' := sInfClosed' supClosed' := fun x hx y hy ↦ by suffices x ⊔ y = sSup {x, y} by exact this ▸ sSupClosed' (fun z hz ↦ by aesop) simp [sSup_singleton] infClosed' := fun x hx y hy ↦ by suffices x ⊓ y = sInf {x, y} by exact this ▸ sInfClosed' (fun z hz ↦ by aesop) simp [sInf_singleton] variable {L : CompleteSublattice α} instance instSetLike : SetLike (CompleteSublattice α) α where coe L := L.carrier coe_injective' L M h := by cases L; cases M; congr; exact SetLike.coe_injective' h theorem top_mem : ⊤ ∈ L := by simpa using L.sInfClosed' <| empty_subset _ theorem bot_mem : ⊥ ∈ L := by simpa using L.sSupClosed' <| empty_subset _ instance instBot : Bot L where bot := ⟨⊥, bot_mem⟩ instance instTop : Top L where top := ⟨⊤, top_mem⟩ instance instSupSet : SupSet L where sSup s := ⟨sSup <| (↑) '' s, L.sSupClosed' image_val_subset⟩ instance instInfSet : InfSet L where sInf s := ⟨sInf <| (↑) '' s, L.sInfClosed' image_val_subset⟩ theorem sSupClosed {s : Set α} (h : s ⊆ L) : sSup s ∈ L := L.sSupClosed' h theorem sInfClosed {s : Set α} (h : s ⊆ L) : sInf s ∈ L := L.sInfClosed' h @[simp] theorem coe_bot : (↑(⊥ : L) : α) = ⊥ := rfl @[simp] theorem coe_top : (↑(⊤ : L) : α) = ⊤ := rfl @[simp] theorem coe_sSup (S : Set L) : (↑(sSup S) : α) = sSup {(s : α) | s ∈ S} := rfl theorem coe_sSup' (S : Set L) : (↑(sSup S) : α) = ⨆ N ∈ S, (N : α) := by rw [coe_sSup, ← Set.image, sSup_image] @[simp] theorem coe_sInf (S : Set L) : (↑(sInf S) : α) = sInf {(s : α) | s ∈ S} := rfl theorem coe_sInf' (S : Set L) : (↑(sInf S) : α) = ⨅ N ∈ S, (N : α) := by rw [coe_sInf, ← Set.image, sInf_image] @[simp] theorem coe_iSup {ι} (f : ι → L) : (↑(iSup f) : α) = ⨆ i, (f i : α) := by rw [iSup, coe_sSup', iSup_range] @[simp] theorem coe_iInf {ι} (f : ι → L) : (↑(iInf f) : α) = ⨅ i, (f i : α) := by rw [iInf, coe_sInf', iInf_range] -- Redeclaring to get proper keys for these instances instance : Max {x // x ∈ L} := Sublattice.instSupCoe instance : Min {x // x ∈ L} := Sublattice.instInfCoe instance instCompleteLattice : CompleteLattice L := Subtype.coe_injective.completeLattice _ Sublattice.coe_sup Sublattice.coe_inf coe_sSup' coe_sInf' coe_top coe_bot /-- The natural complete lattice hom from a complete sublattice to the original lattice. -/ def subtype (L : CompleteSublattice α) : CompleteLatticeHom L α where toFun := Subtype.val map_sInf' _ := rfl map_sSup' _ := rfl @[simp, norm_cast] lemma coe_subtype (L : CompleteSublattice α) : L.subtype = ((↑) : L → α) := rfl lemma subtype_apply (L : Sublattice α) (a : L) : L.subtype a = a := rfl lemma subtype_injective (L : CompleteSublattice α) : Injective <| subtype L := Subtype.coe_injective /-- The push forward of a complete sublattice under a complete lattice hom is a complete sublattice. -/ @[simps] def map (L : CompleteSublattice α) : CompleteSublattice β where carrier := f '' L supClosed' := L.supClosed.image f infClosed' := L.infClosed.image f sSupClosed' := fun s hs ↦ by obtain ⟨t, ht, rfl⟩ := subset_image_iff.mp hs rw [← map_sSup] exact mem_image_of_mem f (sSupClosed ht) sInfClosed' := fun s hs ↦ by obtain ⟨t, ht, rfl⟩ := subset_image_iff.mp hs rw [← map_sInf] exact mem_image_of_mem f (sInfClosed ht) @[simp] theorem mem_map {b : β} : b ∈ L.map f ↔ ∃ a ∈ L, f a = b := Iff.rfl /-- The pull back of a complete sublattice under a complete lattice hom is a complete sublattice. -/ @[simps] def comap (L : CompleteSublattice β) : CompleteSublattice α where carrier := f ⁻¹' L supClosed' := L.supClosed.preimage f infClosed' := L.infClosed.preimage f sSupClosed' s hs := by simpa only [mem_preimage, map_sSup, SetLike.mem_coe] using sSupClosed <| mapsTo_iff_image_subset.mp hs sInfClosed' s hs := by simpa only [mem_preimage, map_sInf, SetLike.mem_coe] using sInfClosed <| mapsTo_iff_image_subset.mp hs @[simp] theorem mem_comap {L : CompleteSublattice β} {a : α} : a ∈ L.comap f ↔ f a ∈ L := Iff.rfl protected lemma disjoint_iff {a b : L} : Disjoint a b ↔ Disjoint (a : α) (b : α) := by rw [disjoint_iff, disjoint_iff, ← Sublattice.coe_inf, ← coe_bot (L := L), Subtype.coe_injective.eq_iff] protected lemma codisjoint_iff {a b : L} : Codisjoint a b ↔ Codisjoint (a : α) (b : α) := by rw [codisjoint_iff, codisjoint_iff, ← Sublattice.coe_sup, ← coe_top (L := L), Subtype.coe_injective.eq_iff] protected lemma isCompl_iff {a b : L} : IsCompl a b ↔ IsCompl (a : α) (b : α) := by rw [isCompl_iff, isCompl_iff, CompleteSublattice.disjoint_iff, CompleteSublattice.codisjoint_iff] lemma isComplemented_iff : ComplementedLattice L ↔ ∀ a ∈ L, ∃ b ∈ L, IsCompl a b := by refine ⟨fun ⟨h⟩ a ha ↦ ?_, fun h ↦ ⟨fun ⟨a, ha⟩ ↦ ?_⟩⟩ · obtain ⟨b, hb⟩ := h ⟨a, ha⟩ exact ⟨b, b.property, CompleteSublattice.isCompl_iff.mp hb⟩ · obtain ⟨b, hb, hb'⟩ := h a ha exact ⟨⟨b, hb⟩, CompleteSublattice.isCompl_iff.mpr hb'⟩ instance : Top (CompleteSublattice α) := ⟨mk' univ (fun _ _ ↦ mem_univ _) (fun _ _ ↦ mem_univ _)⟩ variable (L) /-- Copy of a complete sublattice with a new `carrier` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (s : Set α) (hs : s = L) : CompleteSublattice α := mk' s (hs ▸ L.sSupClosed') (hs ▸ L.sInfClosed') @[simp, norm_cast] lemma coe_copy (s : Set α) (hs) : L.copy s hs = s := rfl lemma copy_eq (s : Set α) (hs) : L.copy s hs = L := SetLike.coe_injective hs end CompleteSublattice namespace CompleteLatticeHom /-- The range of a `CompleteLatticeHom` is a `CompleteSublattice`. See Note [range copy pattern]. -/ protected def range : CompleteSublattice β := (CompleteSublattice.map f ⊤).copy (range f) image_univ.symm theorem range_coe : (f.range : Set β) = range f := rfl /-- We can regard a complete lattice homomorphism as an order equivalence to its range. -/ @[simps! apply] noncomputable def toOrderIsoRangeOfInjective (hf : Injective f) : α ≃o f.range := (orderEmbeddingOfInjective f hf).orderIso end CompleteLatticeHom
.lake/packages/mathlib/Mathlib/Order/GameAdd.lean
import Mathlib.Data.Sym.Sym2 import Mathlib.Logic.Relation /-! # Game addition relation This file defines, given relations `rα : α → α → Prop` and `rβ : β → β → Prop`, a relation `Prod.GameAdd` on pairs, such that `GameAdd rα rβ x y` iff `x` can be reached from `y` by decreasing either entry (with respect to `rα` and `rβ`). It is so called since it models the subsequency relation on the addition of combinatorial games. We also define `Sym2.GameAdd`, which is the unordered pair analog of `Prod.GameAdd`. ## Main definitions and results - `Prod.GameAdd`: the game addition relation on ordered pairs. - `WellFounded.prod_gameAdd`: formalizes induction on ordered pairs, where exactly one entry decreases at a time. - `Sym2.GameAdd`: the game addition relation on unordered pairs. - `WellFounded.sym2_gameAdd`: formalizes induction on unordered pairs, where exactly one entry decreases at a time. -/ variable {α β : Type*} {rα : α → α → Prop} {rβ : β → β → Prop} {a : α} {b : β} /-! ### `Prod.GameAdd` -/ namespace Prod variable (rα rβ) /-- `Prod.GameAdd rα rβ x y` means that `x` can be reached from `y` by decreasing either entry with respect to the relations `rα` and `rβ`. It is so called, as it models game addition within combinatorial game theory. If `rα a₁ a₂` means that `a₂ ⟶ a₁` is a valid move in game `α`, and `rβ b₁ b₂` means that `b₂ ⟶ b₁` is a valid move in game `β`, then `GameAdd rα rβ` specifies the valid moves in the juxtaposition of `α` and `β`: the player is free to choose one of the games and make a move in it, while leaving the other game unchanged. See `Sym2.GameAdd` for the unordered pair analog. -/ inductive GameAdd : α × β → α × β → Prop | fst {a₁ a₂ b} : rα a₁ a₂ → GameAdd (a₁, b) (a₂, b) | snd {a b₁ b₂} : rβ b₁ b₂ → GameAdd (a, b₁) (a, b₂) theorem gameAdd_iff {rα rβ} {x y : α × β} : GameAdd rα rβ x y ↔ rα x.1 y.1 ∧ x.2 = y.2 ∨ rβ x.2 y.2 ∧ x.1 = y.1 := by constructor · rintro (@⟨a₁, a₂, b, h⟩ | @⟨a, b₁, b₂, h⟩) exacts [Or.inl ⟨h, rfl⟩, Or.inr ⟨h, rfl⟩] · revert x y rintro ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ (⟨h, rfl : b₁ = b₂⟩ | ⟨h, rfl : a₁ = a₂⟩) exacts [GameAdd.fst h, GameAdd.snd h] theorem gameAdd_mk_iff {rα rβ} {a₁ a₂ : α} {b₁ b₂ : β} : GameAdd rα rβ (a₁, b₁) (a₂, b₂) ↔ rα a₁ a₂ ∧ b₁ = b₂ ∨ rβ b₁ b₂ ∧ a₁ = a₂ := gameAdd_iff @[simp] theorem gameAdd_swap_swap : ∀ a b : α × β, GameAdd rβ rα a.swap b.swap ↔ GameAdd rα rβ a b := fun ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ => by rw [Prod.swap, Prod.swap, gameAdd_mk_iff, gameAdd_mk_iff, or_comm] theorem gameAdd_swap_swap_mk (a₁ a₂ : α) (b₁ b₂ : β) : GameAdd rα rβ (a₁, b₁) (a₂, b₂) ↔ GameAdd rβ rα (b₁, a₁) (b₂, a₂) := gameAdd_swap_swap rβ rα (b₁, a₁) (b₂, a₂) /-- `Prod.GameAdd` is a subrelation of `Prod.Lex`. -/ theorem gameAdd_le_lex : GameAdd rα rβ ≤ Prod.Lex rα rβ := fun _ _ h => h.rec (Prod.Lex.left _ _) (Prod.Lex.right _) /-- `Prod.RProd` is a subrelation of the transitive closure of `Prod.GameAdd`. -/ theorem rprod_le_transGen_gameAdd : RProd rα rβ ≤ Relation.TransGen (GameAdd rα rβ) | _, _, h => h.rec (by intro _ _ _ _ hα hβ exact Relation.TransGen.tail (Relation.TransGen.single <| GameAdd.fst hα) (GameAdd.snd hβ)) end Prod /-- If `a` is accessible under `rα` and `b` is accessible under `rβ`, then `(a, b)` is accessible under `Prod.GameAdd rα rβ`. Notice that `Prod.lexAccessible` requires the stronger condition `∀ b, Acc rβ b`. -/ theorem Acc.prod_gameAdd (ha : Acc rα a) (hb : Acc rβ b) : Acc (Prod.GameAdd rα rβ) (a, b) := by induction ha generalizing b with | _ a _ iha induction hb with | _ b hb ihb refine Acc.intro _ fun h => ?_ rintro (⟨ra⟩ | ⟨rb⟩) exacts [iha _ ra (Acc.intro b hb), ihb _ rb] /-- The `Prod.GameAdd` relation on well-founded inputs is well-founded. In particular, the sum of two well-founded games is well-founded. -/ theorem WellFounded.prod_gameAdd (hα : WellFounded rα) (hβ : WellFounded rβ) : WellFounded (Prod.GameAdd rα rβ) := ⟨fun ⟨a, b⟩ => (hα.apply a).prod_gameAdd (hβ.apply b)⟩ namespace Prod /-- Recursion on the well-founded `Prod.GameAdd` relation. Note that it's strictly more general to recurse on the lexicographic order instead. -/ def GameAdd.fix {C : α → β → Sort*} (hα : WellFounded rα) (hβ : WellFounded rβ) (IH : ∀ a₁ b₁, (∀ a₂ b₂, GameAdd rα rβ (a₂, b₂) (a₁, b₁) → C a₂ b₂) → C a₁ b₁) (a : α) (b : β) : C a b := @WellFounded.fix (α × β) (fun x => C x.1 x.2) _ (hα.prod_gameAdd hβ) (fun ⟨x₁, x₂⟩ IH' => IH x₁ x₂ fun a' b' => IH' ⟨a', b'⟩) ⟨a, b⟩ theorem GameAdd.fix_eq {C : α → β → Sort*} (hα : WellFounded rα) (hβ : WellFounded rβ) (IH : ∀ a₁ b₁, (∀ a₂ b₂, GameAdd rα rβ (a₂, b₂) (a₁, b₁) → C a₂ b₂) → C a₁ b₁) (a : α) (b : β) : GameAdd.fix hα hβ IH a b = IH a b fun a' b' _ => GameAdd.fix hα hβ IH a' b' := WellFounded.fix_eq _ _ _ /-- Induction on the well-founded `Prod.GameAdd` relation. Note that it's strictly more general to induct on the lexicographic order instead. -/ theorem GameAdd.induction {C : α → β → Prop} : WellFounded rα → WellFounded rβ → (∀ a₁ b₁, (∀ a₂ b₂, GameAdd rα rβ (a₂, b₂) (a₁, b₁) → C a₂ b₂) → C a₁ b₁) → ∀ a b, C a b := GameAdd.fix end Prod /-! ### `Sym2.GameAdd` -/ namespace Sym2 /-- `Sym2.GameAdd rα x y` means that `x` can be reached from `y` by decreasing either entry with respect to the relation `rα`. See `Prod.GameAdd` for the ordered pair analog. -/ def GameAdd (rα : α → α → Prop) : Sym2 α → Sym2 α → Prop := Sym2.lift₂ ⟨fun a₁ b₁ a₂ b₂ => Prod.GameAdd rα rα (a₁, b₁) (a₂, b₂) ∨ Prod.GameAdd rα rα (b₁, a₁) (a₂, b₂), fun a₁ b₁ a₂ b₂ => by dsimp rw [Prod.gameAdd_swap_swap_mk _ _ b₁ b₂ a₁ a₂, Prod.gameAdd_swap_swap_mk _ _ a₁ b₂ b₁ a₂] simp [or_comm]⟩ theorem gameAdd_iff : ∀ {x y : α × α}, GameAdd rα (Sym2.mk x) (Sym2.mk y) ↔ Prod.GameAdd rα rα x y ∨ Prod.GameAdd rα rα x.swap y := by rintro ⟨_, _⟩ ⟨_, _⟩ rfl theorem gameAdd_mk'_iff {a₁ a₂ b₁ b₂ : α} : GameAdd rα s(a₁, b₁) s(a₂, b₂) ↔ Prod.GameAdd rα rα (a₁, b₁) (a₂, b₂) ∨ Prod.GameAdd rα rα (b₁, a₁) (a₂, b₂) := Iff.rfl theorem _root_.Prod.GameAdd.to_sym2 {a₁ a₂ b₁ b₂ : α} (h : Prod.GameAdd rα rα (a₁, b₁) (a₂, b₂)) : Sym2.GameAdd rα s(a₁, b₁) s(a₂, b₂) := gameAdd_mk'_iff.2 <| Or.inl <| h theorem GameAdd.fst {a₁ a₂ b : α} (h : rα a₁ a₂) : GameAdd rα s(a₁, b) s(a₂, b) := (Prod.GameAdd.fst h).to_sym2 theorem GameAdd.snd {a b₁ b₂ : α} (h : rα b₁ b₂) : GameAdd rα s(a, b₁) s(a, b₂) := (Prod.GameAdd.snd h).to_sym2 theorem GameAdd.fst_snd {a₁ a₂ b : α} (h : rα a₁ a₂) : GameAdd rα s(a₁, b) s(b, a₂) := by rw [Sym2.eq_swap] exact GameAdd.snd h theorem GameAdd.snd_fst {a₁ a₂ b : α} (h : rα a₁ a₂) : GameAdd rα s(b, a₁) s(a₂, b) := by rw [Sym2.eq_swap] exact GameAdd.fst h end Sym2 theorem Acc.sym2_gameAdd {a b} (ha : Acc rα a) (hb : Acc rα b) : Acc (Sym2.GameAdd rα) s(a, b) := by induction ha generalizing b with | _ a _ iha induction hb with | _ b hb ihb refine Acc.intro _ fun s => ?_ induction s with | _ c d rw [Sym2.GameAdd] dsimp rintro ((rc | rd) | (rd | rc)) · exact iha c rc ⟨b, hb⟩ · exact ihb d rd · rw [Sym2.eq_swap] exact iha d rd ⟨b, hb⟩ · rw [Sym2.eq_swap] exact ihb c rc /-- The `Sym2.GameAdd` relation on well-founded inputs is well-founded. -/ theorem WellFounded.sym2_gameAdd (h : WellFounded rα) : WellFounded (Sym2.GameAdd rα) := ⟨fun i => Sym2.inductionOn i fun x y => (h.apply x).sym2_gameAdd (h.apply y)⟩ namespace Sym2 attribute [local instance] Sym2.Rel.setoid /-- Recursion on the well-founded `Sym2.GameAdd` relation. -/ def GameAdd.fix {C : α → α → Sort*} (hr : WellFounded rα) (IH : ∀ a₁ b₁, (∀ a₂ b₂, Sym2.GameAdd rα s(a₂, b₂) s(a₁, b₁) → C a₂ b₂) → C a₁ b₁) (a b : α) : C a b := @WellFounded.fix (α × α) (fun x => C x.1 x.2) (fun x y ↦ Prod.GameAdd rα rα x y ∨ Prod.GameAdd rα rα x.swap y) (by simpa [← Sym2.gameAdd_iff] using hr.sym2_gameAdd.onFun) (fun ⟨x₁, x₂⟩ IH' => IH x₁ x₂ fun a' b' => IH' ⟨a', b'⟩) (a, b) theorem GameAdd.fix_eq {C : α → α → Sort*} (hr : WellFounded rα) (IH : ∀ a₁ b₁, (∀ a₂ b₂, Sym2.GameAdd rα s(a₂, b₂) s(a₁, b₁) → C a₂ b₂) → C a₁ b₁) (a b : α) : GameAdd.fix hr IH a b = IH a b fun a' b' _ => GameAdd.fix hr IH a' b' := WellFounded.fix_eq .. /-- Induction on the well-founded `Sym2.GameAdd` relation. -/ theorem GameAdd.induction {C : α → α → Prop} : WellFounded rα → (∀ a₁ b₁, (∀ a₂ b₂, Sym2.GameAdd rα s(a₂, b₂) s(a₁, b₁) → C a₂ b₂) → C a₁ b₁) → ∀ a b, C a b := GameAdd.fix end Sym2
.lake/packages/mathlib/Mathlib/Order/PropInstances.lean
import Mathlib.Order.Disjoint /-! # The order on `Prop` Instances on `Prop` such as `DistribLattice`, `BoundedOrder`, `LinearOrder`. -/ /-- Propositions form a distributive lattice. -/ instance Prop.instDistribLattice : DistribLattice Prop where sup := Or le_sup_left := @Or.inl le_sup_right := @Or.inr sup_le := fun _ _ _ => Or.rec inf := And inf_le_left := @And.left inf_le_right := @And.right le_inf := fun _ _ _ Hab Hac Ha => And.intro (Hab Ha) (Hac Ha) le_sup_inf := fun _ _ _ => or_and_left.2 /-- Propositions form a bounded order. -/ instance Prop.instBoundedOrder : BoundedOrder Prop where top := True le_top _ _ := True.intro bot := False bot_le := @False.elim @[simp] theorem Prop.bot_eq_false : (⊥ : Prop) = False := rfl @[simp] theorem Prop.top_eq_true : (⊤ : Prop) = True := rfl instance Prop.le_isTotal : IsTotal Prop (· ≤ ·) := ⟨fun p q => by by_cases h : q <;> simp [h]⟩ noncomputable instance Prop.linearOrder : LinearOrder Prop := by classical exact Lattice.toLinearOrder Prop @[simp] theorem sup_Prop_eq : (· ⊔ ·) = (· ∨ ·) := rfl @[simp] theorem inf_Prop_eq : (· ⊓ ·) = (· ∧ ·) := rfl namespace Pi variable {ι : Type*} {α' : ι → Type*} [∀ i, PartialOrder (α' i)] theorem disjoint_iff [∀ i, OrderBot (α' i)] {f g : ∀ i, α' i} : Disjoint f g ↔ ∀ i, Disjoint (f i) (g i) := by classical constructor · intro h i x hf hg exact (update_le_iff.mp <| h (update_le_iff.mpr ⟨hf, fun _ _ => bot_le⟩) (update_le_iff.mpr ⟨hg, fun _ _ => bot_le⟩)).1 · intro h x hf hg i apply h i (hf i) (hg i) theorem codisjoint_iff [∀ i, OrderTop (α' i)] {f g : ∀ i, α' i} : Codisjoint f g ↔ ∀ i, Codisjoint (f i) (g i) := @disjoint_iff _ (fun i => (α' i)ᵒᵈ) _ _ _ _ theorem isCompl_iff [∀ i, BoundedOrder (α' i)] {f g : ∀ i, α' i} : IsCompl f g ↔ ∀ i, IsCompl (f i) (g i) := by simp_rw [_root_.isCompl_iff, disjoint_iff, codisjoint_iff, forall_and] end Pi @[simp] theorem Prop.disjoint_iff {P Q : Prop} : Disjoint P Q ↔ ¬(P ∧ Q) := disjoint_iff_inf_le @[simp] theorem Prop.codisjoint_iff {P Q : Prop} : Codisjoint P Q ↔ P ∨ Q := codisjoint_iff_le_sup.trans <| forall_const True @[simp] theorem Prop.isCompl_iff {P Q : Prop} : IsCompl P Q ↔ ¬(P ↔ Q) := by rw [_root_.isCompl_iff, Prop.disjoint_iff, Prop.codisjoint_iff, not_iff] by_cases P <;> by_cases Q <;> simp [*] section decidable_instances universe u variable {α : Type u} instance Prop.decidablePredBot : DecidablePred (⊥ : α → Prop) := fun _ => instDecidableFalse instance Prop.decidablePredTop : DecidablePred (⊤ : α → Prop) := fun _ => instDecidableTrue instance Prop.decidableRelBot : DecidableRel (⊥ : α → α → Prop) := fun _ _ => instDecidableFalse instance Prop.decidableRelTop : DecidableRel (⊤ : α → α → Prop) := fun _ _ => instDecidableTrue end decidable_instances
.lake/packages/mathlib/Mathlib/Order/SymmDiff.lean
import Mathlib.Order.BooleanAlgebra.Basic import Mathlib.Logic.Equiv.Basic /-! # Symmetric difference and bi-implication This file defines the symmetric difference and bi-implication operators in (co-)Heyting algebras. ## Examples Some examples are * The symmetric difference of two sets is the set of elements that are in either but not both. * The symmetric difference on propositions is `Xor'`. * The symmetric difference on `Bool` is `Bool.xor`. * The equivalence of propositions. Two propositions are equivalent if they imply each other. * The symmetric difference translates to addition when considering a Boolean algebra as a Boolean ring. ## Main declarations * `symmDiff`: The symmetric difference operator, defined as `(a \ b) ⊔ (b \ a)` * `bihimp`: The bi-implication operator, defined as `(b ⇨ a) ⊓ (a ⇨ b)` In generalized Boolean algebras, the symmetric difference operator is: * `symmDiff_comm`: commutative, and * `symmDiff_assoc`: associative. ## Notation * `a ∆ b`: `symmDiff a b` * `a ⇔ b`: `bihimp a b` ## References The proof of associativity follows the note "Associativity of the Symmetric Difference of Sets: A Proof from the Book" by John McCuan: * <https://people.math.gatech.edu/~mccuan/courses/4317/symmetricdifference.pdf> ## Tags boolean ring, generalized boolean algebra, boolean algebra, symmetric difference, bi-implication, Heyting -/ assert_not_exists RelIso open Function OrderDual variable {ι α β : Type*} {π : ι → Type*} /-- The symmetric difference operator on a type with `⊔` and `\` is `(A \ B) ⊔ (B \ A)`. -/ def symmDiff [Max α] [SDiff α] (a b : α) : α := a \ b ⊔ b \ a /-- The Heyting bi-implication is `(b ⇨ a) ⊓ (a ⇨ b)`. This generalizes equivalence of propositions. -/ def bihimp [Min α] [HImp α] (a b : α) : α := (b ⇨ a) ⊓ (a ⇨ b) /-- Notation for symmDiff -/ scoped[symmDiff] infixl:100 " ∆ " => symmDiff /-- Notation for bihimp -/ scoped[symmDiff] infixl:100 " ⇔ " => bihimp open scoped symmDiff theorem symmDiff_def [Max α] [SDiff α] (a b : α) : a ∆ b = a \ b ⊔ b \ a := rfl theorem bihimp_def [Min α] [HImp α] (a b : α) : a ⇔ b = (b ⇨ a) ⊓ (a ⇨ b) := rfl theorem symmDiff_eq_Xor' (p q : Prop) : p ∆ q = Xor' p q := rfl @[simp] theorem bihimp_iff_iff {p q : Prop} : p ⇔ q ↔ (p ↔ q) := iff_iff_implies_and_implies.symm.trans Iff.comm @[simp] theorem Bool.symmDiff_eq_xor : ∀ p q : Bool, p ∆ q = xor p q := by decide section GeneralizedCoheytingAlgebra variable [GeneralizedCoheytingAlgebra α] (a b c : α) @[simp] theorem toDual_symmDiff : toDual (a ∆ b) = toDual a ⇔ toDual b := rfl @[simp] theorem ofDual_bihimp (a b : αᵒᵈ) : ofDual (a ⇔ b) = ofDual a ∆ ofDual b := rfl theorem symmDiff_comm : a ∆ b = b ∆ a := by simp only [symmDiff, sup_comm] instance symmDiff_isCommutative : Std.Commutative (α := α) (· ∆ ·) := ⟨symmDiff_comm⟩ @[simp] theorem symmDiff_self : a ∆ a = ⊥ := by rw [symmDiff, sup_idem, sdiff_self] @[simp] theorem symmDiff_bot : a ∆ ⊥ = a := by rw [symmDiff, sdiff_bot, bot_sdiff, sup_bot_eq] @[simp] theorem bot_symmDiff : ⊥ ∆ a = a := by rw [symmDiff_comm, symmDiff_bot] @[simp] theorem symmDiff_eq_bot {a b : α} : a ∆ b = ⊥ ↔ a = b := by simp_rw [symmDiff, sup_eq_bot_iff, sdiff_eq_bot_iff, le_antisymm_iff] theorem symmDiff_of_le {a b : α} (h : a ≤ b) : a ∆ b = b \ a := by rw [symmDiff, sdiff_eq_bot_iff.2 h, bot_sup_eq] theorem symmDiff_of_ge {a b : α} (h : b ≤ a) : a ∆ b = a \ b := by rw [symmDiff, sdiff_eq_bot_iff.2 h, sup_bot_eq] theorem symmDiff_le {a b c : α} (ha : a ≤ b ⊔ c) (hb : b ≤ a ⊔ c) : a ∆ b ≤ c := sup_le (sdiff_le_iff.2 ha) <| sdiff_le_iff.2 hb theorem symmDiff_le_iff {a b c : α} : a ∆ b ≤ c ↔ a ≤ b ⊔ c ∧ b ≤ a ⊔ c := by simp_rw [symmDiff, sup_le_iff, sdiff_le_iff] @[simp] theorem symmDiff_le_sup {a b : α} : a ∆ b ≤ a ⊔ b := sup_le_sup sdiff_le sdiff_le theorem symmDiff_eq_sup_sdiff_inf : a ∆ b = (a ⊔ b) \ (a ⊓ b) := by simp [sup_sdiff, symmDiff] theorem Disjoint.symmDiff_eq_sup {a b : α} (h : Disjoint a b) : a ∆ b = a ⊔ b := by rw [symmDiff, h.sdiff_eq_left, h.sdiff_eq_right] theorem symmDiff_sdiff : a ∆ b \ c = a \ (b ⊔ c) ⊔ b \ (a ⊔ c) := by rw [symmDiff, sup_sdiff_distrib, sdiff_sdiff_left, sdiff_sdiff_left] @[simp] theorem symmDiff_sdiff_inf : a ∆ b \ (a ⊓ b) = a ∆ b := by rw [symmDiff_sdiff] simp [symmDiff] @[simp] theorem symmDiff_sdiff_eq_sup : a ∆ (b \ a) = a ⊔ b := by rw [symmDiff, sdiff_idem] exact le_antisymm (sup_le_sup sdiff_le sdiff_le) (sup_le le_sdiff_sup <| le_sdiff_sup.trans <| sup_le le_sup_right le_sdiff_sup) @[simp] theorem sdiff_symmDiff_eq_sup : (a \ b) ∆ b = a ⊔ b := by rw [symmDiff_comm, symmDiff_sdiff_eq_sup, sup_comm] @[simp] theorem symmDiff_sup_inf : a ∆ b ⊔ a ⊓ b = a ⊔ b := by refine le_antisymm (sup_le symmDiff_le_sup inf_le_sup) ?_ rw [sup_inf_left, symmDiff] refine sup_le (le_inf le_sup_right ?_) (le_inf ?_ le_sup_right) · rw [sup_right_comm] exact le_sup_of_le_left le_sdiff_sup · rw [sup_assoc] exact le_sup_of_le_right le_sdiff_sup @[simp] theorem inf_sup_symmDiff : a ⊓ b ⊔ a ∆ b = a ⊔ b := by rw [sup_comm, symmDiff_sup_inf] @[simp] theorem symmDiff_symmDiff_inf : a ∆ b ∆ (a ⊓ b) = a ⊔ b := by rw [← symmDiff_sdiff_inf a, sdiff_symmDiff_eq_sup, symmDiff_sup_inf] @[simp] theorem inf_symmDiff_symmDiff : (a ⊓ b) ∆ (a ∆ b) = a ⊔ b := by rw [symmDiff_comm, symmDiff_symmDiff_inf] theorem symmDiff_triangle : a ∆ c ≤ a ∆ b ⊔ b ∆ c := by refine (sup_le_sup (sdiff_triangle a b c) <| sdiff_triangle _ b _).trans_eq ?_ rw [sup_comm (c \ b), sup_sup_sup_comm, symmDiff, symmDiff] theorem le_symmDiff_sup_right (a b : α) : a ≤ (a ∆ b) ⊔ b := by convert symmDiff_triangle a b ⊥ <;> rw [symmDiff_bot] theorem le_symmDiff_sup_left (a b : α) : b ≤ (a ∆ b) ⊔ a := symmDiff_comm a b ▸ le_symmDiff_sup_right .. end GeneralizedCoheytingAlgebra section GeneralizedHeytingAlgebra variable [GeneralizedHeytingAlgebra α] (a b c : α) @[simp] theorem toDual_bihimp : toDual (a ⇔ b) = toDual a ∆ toDual b := rfl @[simp] theorem ofDual_symmDiff (a b : αᵒᵈ) : ofDual (a ∆ b) = ofDual a ⇔ ofDual b := rfl theorem bihimp_comm : a ⇔ b = b ⇔ a := by simp only [(· ⇔ ·), inf_comm] instance bihimp_isCommutative : Std.Commutative (α := α) (· ⇔ ·) := ⟨bihimp_comm⟩ @[simp] theorem bihimp_self : a ⇔ a = ⊤ := by rw [bihimp, inf_idem, himp_self] @[simp] theorem bihimp_top : a ⇔ ⊤ = a := by rw [bihimp, himp_top, top_himp, inf_top_eq] @[simp] theorem top_bihimp : ⊤ ⇔ a = a := by rw [bihimp_comm, bihimp_top] @[simp] theorem bihimp_eq_top {a b : α} : a ⇔ b = ⊤ ↔ a = b := @symmDiff_eq_bot αᵒᵈ _ _ _ theorem bihimp_of_le {a b : α} (h : a ≤ b) : a ⇔ b = b ⇨ a := by rw [bihimp, himp_eq_top_iff.2 h, inf_top_eq] theorem bihimp_of_ge {a b : α} (h : b ≤ a) : a ⇔ b = a ⇨ b := by rw [bihimp, himp_eq_top_iff.2 h, top_inf_eq] theorem le_bihimp {a b c : α} (hb : a ⊓ b ≤ c) (hc : a ⊓ c ≤ b) : a ≤ b ⇔ c := le_inf (le_himp_iff.2 hc) <| le_himp_iff.2 hb theorem le_bihimp_iff {a b c : α} : a ≤ b ⇔ c ↔ a ⊓ b ≤ c ∧ a ⊓ c ≤ b := by simp_rw [bihimp, le_inf_iff, le_himp_iff, and_comm] @[simp] theorem inf_le_bihimp {a b : α} : a ⊓ b ≤ a ⇔ b := inf_le_inf le_himp le_himp theorem bihimp_eq_sup_himp_inf : a ⇔ b = a ⊔ b ⇨ a ⊓ b := by simp [himp_inf_distrib, bihimp] @[deprecated (since := "2025-06-05")] alias bihimp_eq_inf_himp_inf := bihimp_eq_sup_himp_inf theorem Codisjoint.bihimp_eq_inf {a b : α} (h : Codisjoint a b) : a ⇔ b = a ⊓ b := by rw [bihimp, h.himp_eq_left, h.himp_eq_right] theorem himp_bihimp : a ⇨ b ⇔ c = (a ⊓ c ⇨ b) ⊓ (a ⊓ b ⇨ c) := by rw [bihimp, himp_inf_distrib, himp_himp, himp_himp] @[simp] theorem sup_himp_bihimp : a ⊔ b ⇨ a ⇔ b = a ⇔ b := by rw [himp_bihimp] simp [bihimp] @[simp] theorem bihimp_himp_eq_inf : a ⇔ (a ⇨ b) = a ⊓ b := @symmDiff_sdiff_eq_sup αᵒᵈ _ _ _ @[simp] theorem himp_bihimp_eq_inf : (b ⇨ a) ⇔ b = a ⊓ b := @sdiff_symmDiff_eq_sup αᵒᵈ _ _ _ @[simp] theorem bihimp_inf_sup : a ⇔ b ⊓ (a ⊔ b) = a ⊓ b := @symmDiff_sup_inf αᵒᵈ _ _ _ @[simp] theorem sup_inf_bihimp : (a ⊔ b) ⊓ a ⇔ b = a ⊓ b := @inf_sup_symmDiff αᵒᵈ _ _ _ @[simp] theorem bihimp_bihimp_sup : a ⇔ b ⇔ (a ⊔ b) = a ⊓ b := @symmDiff_symmDiff_inf αᵒᵈ _ _ _ @[simp] theorem sup_bihimp_bihimp : (a ⊔ b) ⇔ (a ⇔ b) = a ⊓ b := @inf_symmDiff_symmDiff αᵒᵈ _ _ _ theorem bihimp_triangle : a ⇔ b ⊓ b ⇔ c ≤ a ⇔ c := @symmDiff_triangle αᵒᵈ _ _ _ _ end GeneralizedHeytingAlgebra section CoheytingAlgebra variable [CoheytingAlgebra α] (a : α) @[simp] theorem symmDiff_top' : a ∆ ⊤ = ¬a := by simp [symmDiff] @[simp] theorem top_symmDiff' : ⊤ ∆ a = ¬a := by simp [symmDiff] @[simp] theorem hnot_symmDiff_self : (¬a) ∆ a = ⊤ := by rw [eq_top_iff, symmDiff, hnot_sdiff, sup_sdiff_self] exact Codisjoint.top_le codisjoint_hnot_left @[simp] theorem symmDiff_hnot_self : a ∆ (¬a) = ⊤ := by rw [symmDiff_comm, hnot_symmDiff_self] theorem IsCompl.symmDiff_eq_top {a b : α} (h : IsCompl a b) : a ∆ b = ⊤ := by rw [h.eq_hnot, hnot_symmDiff_self] end CoheytingAlgebra section HeytingAlgebra variable [HeytingAlgebra α] (a : α) @[simp] theorem bihimp_bot : a ⇔ ⊥ = aᶜ := by simp [bihimp] @[simp] theorem bot_bihimp : ⊥ ⇔ a = aᶜ := by simp [bihimp] @[simp] theorem compl_bihimp_self : aᶜ ⇔ a = ⊥ := @hnot_symmDiff_self αᵒᵈ _ _ @[simp] theorem bihimp_hnot_self : a ⇔ aᶜ = ⊥ := @symmDiff_hnot_self αᵒᵈ _ _ theorem IsCompl.bihimp_eq_bot {a b : α} (h : IsCompl a b) : a ⇔ b = ⊥ := by rw [h.eq_compl, compl_bihimp_self] end HeytingAlgebra section GeneralizedBooleanAlgebra variable [GeneralizedBooleanAlgebra α] (a b c d : α) @[simp] theorem sup_sdiff_symmDiff : (a ⊔ b) \ a ∆ b = a ⊓ b := sdiff_eq_symm inf_le_sup (by rw [symmDiff_eq_sup_sdiff_inf]) theorem disjoint_symmDiff_inf : Disjoint (a ∆ b) (a ⊓ b) := by rw [symmDiff_eq_sup_sdiff_inf] exact disjoint_sdiff_self_left theorem inf_symmDiff_distrib_left : a ⊓ b ∆ c = (a ⊓ b) ∆ (a ⊓ c) := by rw [symmDiff_eq_sup_sdiff_inf, inf_sdiff_distrib_left, inf_sup_left, inf_inf_distrib_left, symmDiff_eq_sup_sdiff_inf] theorem inf_symmDiff_distrib_right : a ∆ b ⊓ c = (a ⊓ c) ∆ (b ⊓ c) := by simp_rw [inf_comm _ c, inf_symmDiff_distrib_left] theorem sdiff_symmDiff : c \ a ∆ b = c ⊓ a ⊓ b ⊔ c \ a ⊓ c \ b := by simp only [(· ∆ ·), sdiff_sdiff_sup_sdiff'] theorem sdiff_symmDiff' : c \ a ∆ b = c ⊓ a ⊓ b ⊔ c \ (a ⊔ b) := by rw [sdiff_symmDiff, sdiff_sup] @[simp] theorem symmDiff_sdiff_left : a ∆ b \ a = b \ a := by rw [symmDiff_def, sup_sdiff, sdiff_idem, sdiff_sdiff_self, bot_sup_eq] @[simp] theorem symmDiff_sdiff_right : a ∆ b \ b = a \ b := by rw [symmDiff_comm, symmDiff_sdiff_left] @[simp] theorem sdiff_symmDiff_left : a \ a ∆ b = a ⊓ b := by simp [sdiff_symmDiff] @[simp] theorem sdiff_symmDiff_right : b \ a ∆ b = a ⊓ b := by rw [symmDiff_comm, inf_comm, sdiff_symmDiff_left] theorem symmDiff_eq_sup : a ∆ b = a ⊔ b ↔ Disjoint a b := by refine ⟨fun h => ?_, Disjoint.symmDiff_eq_sup⟩ rw [symmDiff_eq_sup_sdiff_inf, sdiff_eq_self_iff_disjoint] at h exact h.of_disjoint_inf_of_le le_sup_left @[simp] theorem le_symmDiff_iff_left : a ≤ a ∆ b ↔ Disjoint a b := by refine ⟨fun h => ?_, fun h => h.symmDiff_eq_sup.symm ▸ le_sup_left⟩ rw [symmDiff_eq_sup_sdiff_inf] at h exact disjoint_iff_inf_le.mpr (le_sdiff_right.1 <| inf_le_of_left_le h).le @[simp] theorem le_symmDiff_iff_right : b ≤ a ∆ b ↔ Disjoint a b := by rw [symmDiff_comm, le_symmDiff_iff_left, disjoint_comm] theorem symmDiff_symmDiff_left : a ∆ b ∆ c = a \ (b ⊔ c) ⊔ b \ (a ⊔ c) ⊔ c \ (a ⊔ b) ⊔ a ⊓ b ⊓ c := calc a ∆ b ∆ c = a ∆ b \ c ⊔ c \ a ∆ b := symmDiff_def _ _ _ = a \ (b ⊔ c) ⊔ b \ (a ⊔ c) ⊔ (c \ (a ⊔ b) ⊔ c ⊓ a ⊓ b) := by { rw [sdiff_symmDiff', sup_comm (c ⊓ a ⊓ b), symmDiff_sdiff] } _ = a \ (b ⊔ c) ⊔ b \ (a ⊔ c) ⊔ c \ (a ⊔ b) ⊔ a ⊓ b ⊓ c := by ac_rfl theorem symmDiff_symmDiff_right : a ∆ (b ∆ c) = a \ (b ⊔ c) ⊔ b \ (a ⊔ c) ⊔ c \ (a ⊔ b) ⊔ a ⊓ b ⊓ c := calc a ∆ (b ∆ c) = a \ b ∆ c ⊔ b ∆ c \ a := symmDiff_def _ _ _ = a \ (b ⊔ c) ⊔ a ⊓ b ⊓ c ⊔ (b \ (c ⊔ a) ⊔ c \ (b ⊔ a)) := by { rw [sdiff_symmDiff', sup_comm (a ⊓ b ⊓ c), symmDiff_sdiff] } _ = a \ (b ⊔ c) ⊔ b \ (a ⊔ c) ⊔ c \ (a ⊔ b) ⊔ a ⊓ b ⊓ c := by ac_rfl theorem symmDiff_assoc : a ∆ b ∆ c = a ∆ (b ∆ c) := by rw [symmDiff_symmDiff_left, symmDiff_symmDiff_right] instance symmDiff_isAssociative : Std.Associative (α := α) (· ∆ ·) := ⟨symmDiff_assoc⟩ theorem symmDiff_left_comm : a ∆ (b ∆ c) = b ∆ (a ∆ c) := by simp_rw [← symmDiff_assoc, symmDiff_comm] theorem symmDiff_right_comm : a ∆ b ∆ c = a ∆ c ∆ b := by simp_rw [symmDiff_assoc, symmDiff_comm] theorem symmDiff_symmDiff_symmDiff_comm : a ∆ b ∆ (c ∆ d) = a ∆ c ∆ (b ∆ d) := by simp_rw [symmDiff_assoc, symmDiff_left_comm] @[simp] theorem symmDiff_symmDiff_cancel_left : a ∆ (a ∆ b) = b := by simp [← symmDiff_assoc] @[simp] theorem symmDiff_symmDiff_cancel_right : b ∆ a ∆ a = b := by simp [symmDiff_assoc] @[simp] theorem symmDiff_symmDiff_self' : a ∆ b ∆ a = b := by rw [symmDiff_comm, symmDiff_symmDiff_cancel_left] theorem symmDiff_left_involutive (a : α) : Involutive (· ∆ a) := symmDiff_symmDiff_cancel_right _ theorem symmDiff_right_involutive (a : α) : Involutive (a ∆ ·) := symmDiff_symmDiff_cancel_left _ theorem symmDiff_left_injective (a : α) : Injective (· ∆ a) := Function.Involutive.injective (symmDiff_left_involutive a) theorem symmDiff_right_injective (a : α) : Injective (a ∆ ·) := Function.Involutive.injective (symmDiff_right_involutive _) theorem symmDiff_left_surjective (a : α) : Surjective (· ∆ a) := Function.Involutive.surjective (symmDiff_left_involutive _) theorem symmDiff_right_surjective (a : α) : Surjective (a ∆ ·) := Function.Involutive.surjective (symmDiff_right_involutive _) variable {a b c} @[simp] theorem symmDiff_left_inj : a ∆ b = c ∆ b ↔ a = c := (symmDiff_left_injective _).eq_iff @[simp] theorem symmDiff_right_inj : a ∆ b = a ∆ c ↔ b = c := (symmDiff_right_injective _).eq_iff @[simp] theorem symmDiff_eq_left : a ∆ b = a ↔ b = ⊥ := calc a ∆ b = a ↔ a ∆ b = a ∆ ⊥ := by rw [symmDiff_bot] _ ↔ b = ⊥ := by rw [symmDiff_right_inj] @[simp] theorem symmDiff_eq_right : a ∆ b = b ↔ a = ⊥ := by rw [symmDiff_comm, symmDiff_eq_left] protected theorem Disjoint.symmDiff_left (ha : Disjoint a c) (hb : Disjoint b c) : Disjoint (a ∆ b) c := by rw [symmDiff_eq_sup_sdiff_inf] exact (ha.sup_left hb).disjoint_sdiff_left protected theorem Disjoint.symmDiff_right (ha : Disjoint a b) (hb : Disjoint a c) : Disjoint a (b ∆ c) := (ha.symm.symmDiff_left hb.symm).symm theorem symmDiff_eq_iff_sdiff_eq (ha : a ≤ c) : a ∆ b = c ↔ c \ a = b := by rw [← symmDiff_of_le ha] exact ((symmDiff_right_involutive a).toPerm _).apply_eq_iff_eq_symm_apply.trans eq_comm end GeneralizedBooleanAlgebra section BooleanAlgebra variable [BooleanAlgebra α] (a b c d : α) /-! `CogeneralizedBooleanAlgebra` isn't actually a typeclass, but the lemmas in here are dual to the `GeneralizedBooleanAlgebra` ones -/ section CogeneralizedBooleanAlgebra @[simp] theorem inf_himp_bihimp : a ⇔ b ⇨ a ⊓ b = a ⊔ b := @sup_sdiff_symmDiff αᵒᵈ _ _ _ theorem codisjoint_bihimp_sup : Codisjoint (a ⇔ b) (a ⊔ b) := @disjoint_symmDiff_inf αᵒᵈ _ _ _ @[simp] theorem himp_bihimp_left : a ⇨ a ⇔ b = a ⇨ b := @symmDiff_sdiff_left αᵒᵈ _ _ _ @[simp] theorem himp_bihimp_right : b ⇨ a ⇔ b = b ⇨ a := @symmDiff_sdiff_right αᵒᵈ _ _ _ @[simp] theorem bihimp_himp_left : a ⇔ b ⇨ a = a ⊔ b := @sdiff_symmDiff_left αᵒᵈ _ _ _ @[simp] theorem bihimp_himp_right : a ⇔ b ⇨ b = a ⊔ b := @sdiff_symmDiff_right αᵒᵈ _ _ _ @[simp] theorem bihimp_eq_inf : a ⇔ b = a ⊓ b ↔ Codisjoint a b := @symmDiff_eq_sup αᵒᵈ _ _ _ @[simp] theorem bihimp_le_iff_left : a ⇔ b ≤ a ↔ Codisjoint a b := @le_symmDiff_iff_left αᵒᵈ _ _ _ @[simp] theorem bihimp_le_iff_right : a ⇔ b ≤ b ↔ Codisjoint a b := @le_symmDiff_iff_right αᵒᵈ _ _ _ theorem bihimp_assoc : a ⇔ b ⇔ c = a ⇔ (b ⇔ c) := @symmDiff_assoc αᵒᵈ _ _ _ _ instance bihimp_isAssociative : Std.Associative (α := α) (· ⇔ ·) := ⟨bihimp_assoc⟩ theorem bihimp_left_comm : a ⇔ (b ⇔ c) = b ⇔ (a ⇔ c) := by simp_rw [← bihimp_assoc, bihimp_comm] theorem bihimp_right_comm : a ⇔ b ⇔ c = a ⇔ c ⇔ b := by simp_rw [bihimp_assoc, bihimp_comm] theorem bihimp_bihimp_bihimp_comm : a ⇔ b ⇔ (c ⇔ d) = a ⇔ c ⇔ (b ⇔ d) := by simp_rw [bihimp_assoc, bihimp_left_comm] @[simp] theorem bihimp_bihimp_cancel_left : a ⇔ (a ⇔ b) = b := by simp [← bihimp_assoc] @[simp] theorem bihimp_bihimp_cancel_right : b ⇔ a ⇔ a = b := by simp [bihimp_assoc] @[simp] theorem bihimp_bihimp_self : a ⇔ b ⇔ a = b := by rw [bihimp_comm, bihimp_bihimp_cancel_left] theorem bihimp_left_involutive (a : α) : Involutive (· ⇔ a) := bihimp_bihimp_cancel_right _ theorem bihimp_right_involutive (a : α) : Involutive (a ⇔ ·) := bihimp_bihimp_cancel_left _ theorem bihimp_left_injective (a : α) : Injective (· ⇔ a) := @symmDiff_left_injective αᵒᵈ _ _ theorem bihimp_right_injective (a : α) : Injective (a ⇔ ·) := @symmDiff_right_injective αᵒᵈ _ _ theorem bihimp_left_surjective (a : α) : Surjective (· ⇔ a) := @symmDiff_left_surjective αᵒᵈ _ _ theorem bihimp_right_surjective (a : α) : Surjective (a ⇔ ·) := @symmDiff_right_surjective αᵒᵈ _ _ variable {a b c} @[simp] theorem bihimp_left_inj : a ⇔ b = c ⇔ b ↔ a = c := (bihimp_left_injective _).eq_iff @[simp] theorem bihimp_right_inj : a ⇔ b = a ⇔ c ↔ b = c := (bihimp_right_injective _).eq_iff @[simp] theorem bihimp_eq_left : a ⇔ b = a ↔ b = ⊤ := @symmDiff_eq_left αᵒᵈ _ _ _ @[simp] theorem bihimp_eq_right : a ⇔ b = b ↔ a = ⊤ := @symmDiff_eq_right αᵒᵈ _ _ _ protected theorem Codisjoint.bihimp_left (ha : Codisjoint a c) (hb : Codisjoint b c) : Codisjoint (a ⇔ b) c := (ha.inf_left hb).mono_left inf_le_bihimp protected theorem Codisjoint.bihimp_right (ha : Codisjoint a b) (hb : Codisjoint a c) : Codisjoint a (b ⇔ c) := (ha.inf_right hb).mono_right inf_le_bihimp end CogeneralizedBooleanAlgebra theorem symmDiff_eq : a ∆ b = a ⊓ bᶜ ⊔ b ⊓ aᶜ := by simp only [(· ∆ ·), sdiff_eq] theorem bihimp_eq : a ⇔ b = (a ⊔ bᶜ) ⊓ (b ⊔ aᶜ) := by simp only [(· ⇔ ·), himp_eq] theorem symmDiff_eq' : a ∆ b = (a ⊔ b) ⊓ (aᶜ ⊔ bᶜ) := by rw [symmDiff_eq_sup_sdiff_inf, sdiff_eq, compl_inf] theorem bihimp_eq' : a ⇔ b = a ⊓ b ⊔ aᶜ ⊓ bᶜ := @symmDiff_eq' αᵒᵈ _ _ _ theorem symmDiff_top : a ∆ ⊤ = aᶜ := symmDiff_top' _ theorem top_symmDiff : ⊤ ∆ a = aᶜ := top_symmDiff' _ @[simp] theorem compl_symmDiff : (a ∆ b)ᶜ = a ⇔ b := by simp_rw [symmDiff, compl_sup_distrib, compl_sdiff, bihimp, inf_comm] @[simp] theorem compl_bihimp : (a ⇔ b)ᶜ = a ∆ b := @compl_symmDiff αᵒᵈ _ _ _ @[simp] theorem compl_symmDiff_compl : aᶜ ∆ bᶜ = a ∆ b := (sup_comm _ _).trans <| by simp_rw [compl_sdiff_compl, sdiff_eq, symmDiff_eq] @[simp] theorem compl_bihimp_compl : aᶜ ⇔ bᶜ = a ⇔ b := @compl_symmDiff_compl αᵒᵈ _ _ _ @[simp] theorem symmDiff_eq_top : a ∆ b = ⊤ ↔ IsCompl a b := by rw [symmDiff_eq', ← compl_inf, inf_eq_top_iff, compl_eq_top, isCompl_iff, disjoint_iff, codisjoint_iff, and_comm] @[simp] theorem bihimp_eq_bot : a ⇔ b = ⊥ ↔ IsCompl a b := by rw [bihimp_eq', ← compl_sup, sup_eq_bot_iff, compl_eq_bot, isCompl_iff, disjoint_iff, codisjoint_iff] @[simp] theorem compl_symmDiff_self : aᶜ ∆ a = ⊤ := hnot_symmDiff_self _ @[simp] theorem symmDiff_compl_self : a ∆ aᶜ = ⊤ := symmDiff_hnot_self _ theorem symmDiff_symmDiff_right' : a ∆ (b ∆ c) = a ⊓ b ⊓ c ⊔ a ⊓ bᶜ ⊓ cᶜ ⊔ aᶜ ⊓ b ⊓ cᶜ ⊔ aᶜ ⊓ bᶜ ⊓ c := calc a ∆ (b ∆ c) = a ⊓ (b ⊓ c ⊔ bᶜ ⊓ cᶜ) ⊔ (b ⊓ cᶜ ⊔ c ⊓ bᶜ) ⊓ aᶜ := by { rw [symmDiff_eq, compl_symmDiff, bihimp_eq', symmDiff_eq] } _ = a ⊓ b ⊓ c ⊔ a ⊓ bᶜ ⊓ cᶜ ⊔ b ⊓ cᶜ ⊓ aᶜ ⊔ c ⊓ bᶜ ⊓ aᶜ := by { rw [inf_sup_left, inf_sup_right, ← sup_assoc, ← inf_assoc, ← inf_assoc] } _ = a ⊓ b ⊓ c ⊔ a ⊓ bᶜ ⊓ cᶜ ⊔ aᶜ ⊓ b ⊓ cᶜ ⊔ aᶜ ⊓ bᶜ ⊓ c := (by congr 1 · congr 1 rw [inf_comm, inf_assoc] · apply inf_left_right_swap) variable {a b c} theorem Disjoint.le_symmDiff_sup_symmDiff_left (h : Disjoint a b) : c ≤ a ∆ c ⊔ b ∆ c := by trans c \ (a ⊓ b) · rw [h.eq_bot, sdiff_bot] · rw [sdiff_inf] exact sup_le_sup le_sup_right le_sup_right theorem Disjoint.le_symmDiff_sup_symmDiff_right (h : Disjoint b c) : a ≤ a ∆ b ⊔ a ∆ c := by simp_rw [symmDiff_comm a] exact h.le_symmDiff_sup_symmDiff_left theorem Codisjoint.bihimp_inf_bihimp_le_left (h : Codisjoint a b) : a ⇔ c ⊓ b ⇔ c ≤ c := h.dual.le_symmDiff_sup_symmDiff_left theorem Codisjoint.bihimp_inf_bihimp_le_right (h : Codisjoint b c) : a ⇔ b ⊓ a ⇔ c ≤ a := h.dual.le_symmDiff_sup_symmDiff_right end BooleanAlgebra /-! ### Prod -/ section Prod @[simp] theorem symmDiff_fst [GeneralizedCoheytingAlgebra α] [GeneralizedCoheytingAlgebra β] (a b : α × β) : (a ∆ b).1 = a.1 ∆ b.1 := rfl @[simp] theorem symmDiff_snd [GeneralizedCoheytingAlgebra α] [GeneralizedCoheytingAlgebra β] (a b : α × β) : (a ∆ b).2 = a.2 ∆ b.2 := rfl @[simp] theorem bihimp_fst [GeneralizedHeytingAlgebra α] [GeneralizedHeytingAlgebra β] (a b : α × β) : (a ⇔ b).1 = a.1 ⇔ b.1 := rfl @[simp] theorem bihimp_snd [GeneralizedHeytingAlgebra α] [GeneralizedHeytingAlgebra β] (a b : α × β) : (a ⇔ b).2 = a.2 ⇔ b.2 := rfl end Prod /-! ### Pi -/ namespace Pi @[push ←] theorem symmDiff_def [∀ i, GeneralizedCoheytingAlgebra (π i)] (a b : ∀ i, π i) : a ∆ b = fun i => a i ∆ b i := rfl @[push ←] theorem bihimp_def [∀ i, GeneralizedHeytingAlgebra (π i)] (a b : ∀ i, π i) : a ⇔ b = fun i => a i ⇔ b i := rfl @[simp] theorem symmDiff_apply [∀ i, GeneralizedCoheytingAlgebra (π i)] (a b : ∀ i, π i) (i : ι) : (a ∆ b) i = a i ∆ b i := rfl @[simp] theorem bihimp_apply [∀ i, GeneralizedHeytingAlgebra (π i)] (a b : ∀ i, π i) (i : ι) : (a ⇔ b) i = a i ⇔ b i := rfl end Pi
.lake/packages/mathlib/Mathlib/Order/ZornAtoms.lean
import Mathlib.Order.Zorn import Mathlib.Order.Atoms /-! # Zorn lemma for (co)atoms In this file we use Zorn's lemma to prove that a partial order is atomic if every nonempty chain `c`, `⊥ ∉ c`, has a lower bound not equal to `⊥`. We also prove the order dual version of this statement. -/ open Set /-- **Zorn's lemma**: A partial order is coatomic if every nonempty chain `c`, `⊤ ∉ c`, has an upper bound not equal to `⊤`. -/ theorem IsCoatomic.of_isChain_bounded {α : Type*} [PartialOrder α] [OrderTop α] (h : ∀ c : Set α, IsChain (· ≤ ·) c → c.Nonempty → ⊤ ∉ c → ∃ x ≠ ⊤, x ∈ upperBounds c) : IsCoatomic α := by refine ⟨fun x => le_top.eq_or_lt.imp_right fun hx => ?_⟩ have := zorn_le_nonempty₀ (Ico x ⊤) (fun c hxc hc y hy => ?_) x (left_mem_Ico.2 hx) · obtain ⟨y, hxy, hmax⟩ := this refine ⟨y, ⟨hmax.prop.2.ne, fun z hyz ↦ le_top.eq_or_lt.resolve_right fun hz => ?_⟩, hxy⟩ exact hyz.ne <| hmax.eq_of_le ⟨hxy.trans hyz.le, hz⟩ hyz.le rcases h c hc ⟨y, hy⟩ fun h => (hxc h).2.ne rfl with ⟨z, hz, hcz⟩ exact ⟨z, ⟨le_trans (hxc hy).1 (hcz hy), hz.lt_top⟩, hcz⟩ /-- **Zorn's lemma**: A partial order is atomic if every nonempty chain `c`, `⊥ ∉ c`, has a lower bound not equal to `⊥`. -/ theorem IsAtomic.of_isChain_bounded {α : Type*} [PartialOrder α] [OrderBot α] (h : ∀ c : Set α, IsChain (· ≤ ·) c → c.Nonempty → ⊥ ∉ c → ∃ x ≠ ⊥, x ∈ lowerBounds c) : IsAtomic α := isCoatomic_dual_iff_isAtomic.mp <| IsCoatomic.of_isChain_bounded fun c hc => h c hc.symm
.lake/packages/mathlib/Mathlib/Order/Grade.lean
import Mathlib.Data.Int.SuccPred import Mathlib.Order.Fin.Basic /-! # Graded orders This file defines graded orders, also known as ranked orders. An `𝕆`-graded order is an order `α` equipped with a distinguished "grade" function `α → 𝕆` which should be understood as giving the "height" of the elements. Usual graded orders are `ℕ`-graded, cograded orders are `ℕᵒᵈ`-graded, but we can also grade by `ℤ`, and polytopes are naturally `Fin n`-graded. Visually, `grade ℕ a` is the height of `a` in the Hasse diagram of `α`. ## Main declarations * `GradeOrder`: Graded order. * `GradeMinOrder`: Graded order where minimal elements have minimal grades. * `GradeMaxOrder`: Graded order where maximal elements have maximal grades. * `GradeBoundedOrder`: Graded order where minimal elements have minimal grades and maximal elements have maximal grades. * `grade`: The grade of an element. Because an order can admit several gradings, the first argument is the order we grade by. ## How to grade your order Here are the translations between common references and our `GradeOrder`: * [Stanley][stanley2012] defines a graded order of rank `n` as an order where all maximal chains have "length" `n` (so the number of elements of a chain is `n + 1`). This corresponds to `GradeBoundedOrder (Fin (n + 1)) α`. * [Engel][engel1997]'s ranked orders are somewhere between `GradeOrder ℕ α` and `GradeMinOrder ℕ α`, in that he requires `∃ a, IsMin a ∧ grade ℕ a = 0` rather than `∀ a, IsMin a → grade ℕ a = 0`. He defines a graded order as an order where all minimal elements have grade `0` and all maximal elements have the same grade. This is roughly a less bundled version of `GradeBoundedOrder (Fin n) α`, assuming we discard orders with infinite chains. ## Implementation notes One possible definition of graded orders is as the bounded orders whose flags (maximal chains) all have the same finite length (see Stanley p. 99). However, this means that all graded orders must have minimal and maximal elements and that the grade is not data. Instead, we define graded orders by their grade function, without talking about flags yet. ## References * [Konrad Engel, *Sperner Theory*][engel1997] * [Richard Stanley, *Enumerative Combinatorics*][stanley2012] -/ open Nat OrderDual variable {𝕆 ℙ α β : Type*} /-- An `𝕆`-graded order is an order `α` equipped with a strictly monotone function `grade 𝕆 : α → 𝕆` which preserves order covering (`CovBy`). -/ class GradeOrder (𝕆 α : Type*) [Preorder 𝕆] [Preorder α] where /-- The grading function. -/ protected grade : α → 𝕆 /-- `grade` is strictly monotonic. -/ grade_strictMono : StrictMono grade /-- `grade` preserves `CovBy`. -/ covBy_grade ⦃a b : α⦄ : a ⋖ b → grade a ⋖ grade b /-- An `𝕆`-graded order where minimal elements have minimal grades. -/ class GradeMinOrder (𝕆 α : Type*) [Preorder 𝕆] [Preorder α] extends GradeOrder 𝕆 α where /-- Minimal elements have minimal grades. -/ isMin_grade ⦃a : α⦄ : IsMin a → IsMin (grade a) /-- An `𝕆`-graded order where maximal elements have maximal grades. -/ class GradeMaxOrder (𝕆 α : Type*) [Preorder 𝕆] [Preorder α] extends GradeOrder 𝕆 α where /-- Maximal elements have maximal grades. -/ isMax_grade ⦃a : α⦄ : IsMax a → IsMax (grade a) /-- An `𝕆`-graded order where minimal elements have minimal grades and maximal elements have maximal grades. -/ class GradeBoundedOrder (𝕆 α : Type*) [Preorder 𝕆] [Preorder α] extends GradeMinOrder 𝕆 α, GradeMaxOrder 𝕆 α section Preorder -- grading variable [Preorder 𝕆] section Preorder -- graded order variable [Preorder α] section GradeOrder variable (𝕆) variable [GradeOrder 𝕆 α] {a b : α} /-- The grade of an element in a graded order. Morally, this is the number of elements you need to go down by to get to `⊥`. -/ def grade : α → 𝕆 := GradeOrder.grade protected theorem CovBy.grade (h : a ⋖ b) : grade 𝕆 a ⋖ grade 𝕆 b := GradeOrder.covBy_grade h variable {𝕆} theorem grade_strictMono : StrictMono (grade 𝕆 : α → 𝕆) := GradeOrder.grade_strictMono theorem covBy_iff_lt_covBy_grade : a ⋖ b ↔ a < b ∧ grade 𝕆 a ⋖ grade 𝕆 b := ⟨fun h => ⟨h.1, h.grade _⟩, And.imp_right fun h _ ha hb => h.2 (grade_strictMono ha) <| grade_strictMono hb⟩ end GradeOrder section GradeMinOrder variable (𝕆) variable [GradeMinOrder 𝕆 α] {a : α} protected theorem IsMin.grade (h : IsMin a) : IsMin (grade 𝕆 a) := GradeMinOrder.isMin_grade h variable {𝕆} @[simp] theorem isMin_grade_iff : IsMin (grade 𝕆 a) ↔ IsMin a := ⟨grade_strictMono.isMin_of_apply, IsMin.grade _⟩ end GradeMinOrder section GradeMaxOrder variable (𝕆) variable [GradeMaxOrder 𝕆 α] {a : α} protected theorem IsMax.grade (h : IsMax a) : IsMax (grade 𝕆 a) := GradeMaxOrder.isMax_grade h variable {𝕆} @[simp] theorem isMax_grade_iff : IsMax (grade 𝕆 a) ↔ IsMax a := ⟨grade_strictMono.isMax_of_apply, IsMax.grade _⟩ end GradeMaxOrder end Preorder -- graded order theorem grade_mono [PartialOrder α] [GradeOrder 𝕆 α] : Monotone (grade 𝕆 : α → 𝕆) := grade_strictMono.monotone section LinearOrder -- graded order variable [LinearOrder α] [GradeOrder 𝕆 α] {a b : α} theorem grade_injective : Function.Injective (grade 𝕆 : α → 𝕆) := grade_strictMono.injective @[simp] theorem grade_le_grade_iff : grade 𝕆 a ≤ grade 𝕆 b ↔ a ≤ b := grade_strictMono.le_iff_le @[simp] theorem grade_lt_grade_iff : grade 𝕆 a < grade 𝕆 b ↔ a < b := grade_strictMono.lt_iff_lt @[simp] theorem grade_eq_grade_iff : grade 𝕆 a = grade 𝕆 b ↔ a = b := grade_injective.eq_iff theorem grade_ne_grade_iff : grade 𝕆 a ≠ grade 𝕆 b ↔ a ≠ b := grade_injective.ne_iff theorem grade_covBy_grade_iff : grade 𝕆 a ⋖ grade 𝕆 b ↔ a ⋖ b := (covBy_iff_lt_covBy_grade.trans <| and_iff_right_of_imp fun h => grade_lt_grade_iff.1 h.1).symm end LinearOrder -- graded order end Preorder -- grading section PartialOrder variable [PartialOrder 𝕆] [Preorder α] @[simp] theorem grade_bot [OrderBot 𝕆] [OrderBot α] [GradeMinOrder 𝕆 α] : grade 𝕆 (⊥ : α) = ⊥ := (isMin_bot.grade _).eq_bot @[simp] theorem grade_top [OrderTop 𝕆] [OrderTop α] [GradeMaxOrder 𝕆 α] : grade 𝕆 (⊤ : α) = ⊤ := (isMax_top.grade _).eq_top end PartialOrder /-! ### Instances -/ section Preorder variable [Preorder 𝕆] [Preorder ℙ] [Preorder α] [Preorder β] instance Preorder.toGradeBoundedOrder : GradeBoundedOrder α α where grade := id isMin_grade _ := id isMax_grade _ := id grade_strictMono := strictMono_id covBy_grade _ _ := id @[simp] theorem grade_self (a : α) : grade α a = a := rfl /-! #### Dual -/ instance OrderDual.gradeOrder [GradeOrder 𝕆 α] : GradeOrder 𝕆ᵒᵈ αᵒᵈ where grade := toDual ∘ grade 𝕆 ∘ ofDual grade_strictMono := grade_strictMono.dual covBy_grade _ _ h := (h.ofDual.grade _).toDual instance OrderDual.gradeMinOrder [GradeMaxOrder 𝕆 α] : GradeMinOrder 𝕆ᵒᵈ αᵒᵈ := { OrderDual.gradeOrder with isMin_grade := fun _ => IsMax.grade (α := α) 𝕆 } instance OrderDual.gradeMaxOrder [GradeMinOrder 𝕆 α] : GradeMaxOrder 𝕆ᵒᵈ αᵒᵈ := { OrderDual.gradeOrder with isMax_grade := fun _ => IsMin.grade (α := α) 𝕆 } instance [GradeBoundedOrder 𝕆 α] : GradeBoundedOrder 𝕆ᵒᵈ αᵒᵈ := { OrderDual.gradeMinOrder, OrderDual.gradeMaxOrder with } @[simp] theorem grade_toDual [GradeOrder 𝕆 α] (a : α) : grade 𝕆ᵒᵈ (toDual a) = toDual (grade 𝕆 a) := rfl @[simp] theorem grade_ofDual [GradeOrder 𝕆 α] (a : αᵒᵈ) : grade 𝕆 (ofDual a) = ofDual (grade 𝕆ᵒᵈ a) := rfl /-! #### Lifting a graded order -/ -- See note [reducible non-instances] /-- Lifts a graded order along a strictly monotone function. -/ abbrev GradeOrder.liftLeft [GradeOrder 𝕆 α] (f : 𝕆 → ℙ) (hf : StrictMono f) (hcovBy : ∀ a b, a ⋖ b → f a ⋖ f b) : GradeOrder ℙ α where grade := f ∘ grade 𝕆 grade_strictMono := hf.comp grade_strictMono covBy_grade _ _ h := hcovBy _ _ <| h.grade _ -- See note [reducible non-instances] /-- Lifts a graded order along a strictly monotone function. -/ abbrev GradeMinOrder.liftLeft [GradeMinOrder 𝕆 α] (f : 𝕆 → ℙ) (hf : StrictMono f) (hcovBy : ∀ a b, a ⋖ b → f a ⋖ f b) (hmin : ∀ a, IsMin a → IsMin (f a)) : GradeMinOrder ℙ α := { GradeOrder.liftLeft f hf hcovBy with isMin_grade := fun _ ha => hmin _ <| ha.grade _ } -- See note [reducible non-instances] /-- Lifts a graded order along a strictly monotone function. -/ abbrev GradeMaxOrder.liftLeft [GradeMaxOrder 𝕆 α] (f : 𝕆 → ℙ) (hf : StrictMono f) (hcovBy : ∀ a b, a ⋖ b → f a ⋖ f b) (hmax : ∀ a, IsMax a → IsMax (f a)) : GradeMaxOrder ℙ α := { GradeOrder.liftLeft f hf hcovBy with isMax_grade := fun _ ha => hmax _ <| ha.grade _ } -- See note [reducible non-instances] /-- Lifts a graded order along a strictly monotone function. -/ abbrev GradeBoundedOrder.liftLeft [GradeBoundedOrder 𝕆 α] (f : 𝕆 → ℙ) (hf : StrictMono f) (hcovBy : ∀ a b, a ⋖ b → f a ⋖ f b) (hmin : ∀ a, IsMin a → IsMin (f a)) (hmax : ∀ a, IsMax a → IsMax (f a)) : GradeBoundedOrder ℙ α := { GradeMinOrder.liftLeft f hf hcovBy hmin, GradeMaxOrder.liftLeft f hf hcovBy hmax with } -- See note [reducible non-instances] /-- Lifts a graded order along a strictly monotone function. -/ abbrev GradeOrder.liftRight [GradeOrder 𝕆 β] (f : α → β) (hf : StrictMono f) (hcovBy : ∀ a b, a ⋖ b → f a ⋖ f b) : GradeOrder 𝕆 α where grade := grade 𝕆 ∘ f grade_strictMono := grade_strictMono.comp hf covBy_grade _ _ h := (hcovBy _ _ h).grade _ -- See note [reducible non-instances] /-- Lifts a graded order along a strictly monotone function. -/ abbrev GradeMinOrder.liftRight [GradeMinOrder 𝕆 β] (f : α → β) (hf : StrictMono f) (hcovBy : ∀ a b, a ⋖ b → f a ⋖ f b) (hmin : ∀ a, IsMin a → IsMin (f a)) : GradeMinOrder 𝕆 α := { GradeOrder.liftRight f hf hcovBy with isMin_grade := fun _ ha => (hmin _ ha).grade _ } -- See note [reducible non-instances] /-- Lifts a graded order along a strictly monotone function. -/ abbrev GradeMaxOrder.liftRight [GradeMaxOrder 𝕆 β] (f : α → β) (hf : StrictMono f) (hcovBy : ∀ a b, a ⋖ b → f a ⋖ f b) (hmax : ∀ a, IsMax a → IsMax (f a)) : GradeMaxOrder 𝕆 α := { GradeOrder.liftRight f hf hcovBy with isMax_grade := fun _ ha => (hmax _ ha).grade _ } -- See note [reducible non-instances] /-- Lifts a graded order along a strictly monotone function. -/ abbrev GradeBoundedOrder.liftRight [GradeBoundedOrder 𝕆 β] (f : α → β) (hf : StrictMono f) (hcovBy : ∀ a b, a ⋖ b → f a ⋖ f b) (hmin : ∀ a, IsMin a → IsMin (f a)) (hmax : ∀ a, IsMax a → IsMax (f a)) : GradeBoundedOrder 𝕆 α := { GradeMinOrder.liftRight f hf hcovBy hmin, GradeMaxOrder.liftRight f hf hcovBy hmax with } /-! #### `Fin n`-graded to `ℕ`-graded to `ℤ`-graded -/ -- See note [reducible non-instances] /-- A `Fin n`-graded order is also `ℕ`-graded. We do not mark this an instance because `n` is not inferable. -/ abbrev GradeOrder.finToNat (n : ℕ) [GradeOrder (Fin n) α] : GradeOrder ℕ α := (GradeOrder.liftLeft (_ : Fin n → ℕ) Fin.val_strictMono) fun _ _ => CovBy.coe_fin -- See note [reducible non-instances] /-- A `Fin n`-graded order is also `ℕ`-graded. We do not mark this an instance because `n` is not inferable. -/ abbrev GradeMinOrder.finToNat (n : ℕ) [GradeMinOrder (Fin n) α] : GradeMinOrder ℕ α := (GradeMinOrder.liftLeft (_ : Fin n → ℕ) Fin.val_strictMono fun _ _ => CovBy.coe_fin) fun a h => by cases n · exact a.elim0 rw [h.eq_bot, Fin.bot_eq_zero] exact isMin_bot instance GradeOrder.natToInt [GradeOrder ℕ α] : GradeOrder ℤ α := (GradeOrder.liftLeft _ Int.natCast_strictMono) fun _ _ => CovBy.intCast theorem GradeOrder.wellFoundedLT (𝕆 : Type*) [Preorder 𝕆] [GradeOrder 𝕆 α] [WellFoundedLT 𝕆] : WellFoundedLT α := (grade_strictMono (𝕆 := 𝕆)).wellFoundedLT theorem GradeOrder.wellFoundedGT (𝕆 : Type*) [Preorder 𝕆] [GradeOrder 𝕆 α] [WellFoundedGT 𝕆] : WellFoundedGT α := (grade_strictMono (𝕆 := 𝕆)).wellFoundedGT instance [GradeOrder ℕ α] : WellFoundedLT α := GradeOrder.wellFoundedLT ℕ instance [GradeOrder ℕᵒᵈ α] : WellFoundedGT α := GradeOrder.wellFoundedGT ℕᵒᵈ end Preorder /-! ### Grading a flag A flag inherits the grading of its ambient order. -/ namespace Flag variable [PartialOrder α] {s : Flag α} {a b : s} @[simp, norm_cast] lemma coe_wcovBy_coe : (a : α) ⩿ b ↔ a ⩿ b := by refine and_congr_right' ⟨fun h c hac ↦ h hac, fun h c hac hcb ↦ @h ⟨c, mem_iff_forall_le_or_ge.2 fun d hd ↦ ?_⟩ hac hcb⟩ classical obtain hda | had := le_or_gt (⟨d, hd⟩ : s) a · exact .inr ((Subtype.coe_le_coe.2 hda).trans hac.le) obtain hbd | hdb := le_or_gt b ⟨d, hd⟩ · exact .inl (hcb.le.trans hbd) · cases h had hdb @[simp, norm_cast] lemma coe_covBy_coe : (a : α) ⋖ b ↔ a ⋖ b := by simp [covBy_iff_wcovBy_and_not_le] @[simp] lemma isMax_coe : IsMax (a : α) ↔ IsMax a where mp h b hab := h hab mpr h b hab := by refine @h ⟨b, mem_iff_forall_le_or_ge.2 fun c hc ↦ ?_⟩ hab classical exact .inr <| hab.trans' <| h.isTop ⟨c, hc⟩ @[simp] lemma isMin_coe : IsMin (a : α) ↔ IsMin a where mp h b hba := h hba mpr h b hba := by refine @h ⟨b, mem_iff_forall_le_or_ge.2 fun c hc ↦ ?_⟩ hba classical exact .inl <| hba.trans <| h.isBot ⟨c, hc⟩ variable [Preorder 𝕆] instance [GradeOrder 𝕆 α] (s : Flag α) : GradeOrder 𝕆 s := .liftRight _ (Subtype.strictMono_coe _) fun _ _ ↦ coe_covBy_coe.2 instance [GradeMinOrder 𝕆 α] (s : Flag α) : GradeMinOrder 𝕆 s := .liftRight _ (Subtype.strictMono_coe _) (fun _ _ ↦ coe_covBy_coe.2) fun _ ↦ isMin_coe.2 instance [GradeMaxOrder 𝕆 α] (s : Flag α) : GradeMaxOrder 𝕆 s := .liftRight _ (Subtype.strictMono_coe _) (fun _ _ ↦ coe_covBy_coe.2) fun _ ↦ isMax_coe.2 instance [GradeBoundedOrder 𝕆 α] (s : Flag α) : GradeBoundedOrder 𝕆 s := .liftRight _ (Subtype.strictMono_coe _) (fun _ _ ↦ coe_covBy_coe.2) (fun _ ↦ isMin_coe.2) fun _ ↦ isMax_coe.2 @[simp, norm_cast] lemma grade_coe [GradeOrder 𝕆 α] (a : s) : grade 𝕆 (a : α) = grade 𝕆 a := rfl end Flag
.lake/packages/mathlib/Mathlib/Order/WithBot.lean
import Mathlib.Logic.Nontrivial.Basic import Mathlib.Order.TypeTags import Mathlib.Data.Option.NAry import Mathlib.Tactic.Contrapose import Mathlib.Tactic.Lift import Mathlib.Data.Option.Basic import Mathlib.Order.Lattice import Mathlib.Order.BoundedOrder.Basic /-! # `WithBot`, `WithTop` Adding a `bot` or a `top` to an order. ## Main declarations * `With<Top/Bot> α`: Equips `Option α` with the order on `α` plus `none` as the top/bottom element. -/ variable {α β γ δ : Type*} namespace WithBot variable {a b : α} instance nontrivial [Nonempty α] : Nontrivial (WithBot α) := Option.nontrivial instance [IsEmpty α] : Unique (WithBot α) := Option.instUniqueOfIsEmpty open Function theorem coe_injective : Injective ((↑) : α → WithBot α) := Option.some_injective _ @[simp, norm_cast] theorem coe_inj : (a : WithBot α) = b ↔ a = b := Option.some_inj protected theorem «forall» {p : WithBot α → Prop} : (∀ x, p x) ↔ p ⊥ ∧ ∀ x : α, p x := Option.forall protected theorem «exists» {p : WithBot α → Prop} : (∃ x, p x) ↔ p ⊥ ∨ ∃ x : α, p x := Option.exists theorem none_eq_bot : (none : WithBot α) = (⊥ : WithBot α) := rfl theorem some_eq_coe (a : α) : (Option.some a : WithBot α) = (↑a : WithBot α) := rfl @[simp] theorem bot_ne_coe : ⊥ ≠ (a : WithBot α) := nofun @[simp] theorem coe_ne_bot : (a : WithBot α) ≠ ⊥ := nofun /-- Specialization of `Option.getD` to values in `WithBot α` that respects API boundaries. -/ def unbotD (d : α) (x : WithBot α) : α := recBotCoe d id x @[simp] theorem unbotD_bot {α} (d : α) : unbotD d ⊥ = d := rfl @[simp] theorem unbotD_coe {α} (d x : α) : unbotD d x = x := rfl theorem coe_eq_coe : (a : WithBot α) = b ↔ a = b := coe_inj theorem unbotD_eq_iff {d y : α} {x : WithBot α} : unbotD d x = y ↔ x = y ∨ x = ⊥ ∧ y = d := by induction x <;> simp [@eq_comm _ d] @[simp] theorem unbotD_eq_self_iff {d : α} {x : WithBot α} : unbotD d x = d ↔ x = d ∨ x = ⊥ := by simp [unbotD_eq_iff] theorem unbotD_eq_unbotD_iff {d : α} {x y : WithBot α} : unbotD d x = unbotD d y ↔ x = y ∨ x = d ∧ y = ⊥ ∨ x = ⊥ ∧ y = d := by induction y <;> simp [unbotD_eq_iff, or_comm] /-- Lift a map `f : α → β` to `WithBot α → WithBot β`. Implemented using `Option.map`. -/ def map (f : α → β) : WithBot α → WithBot β := Option.map f @[simp] theorem map_bot (f : α → β) : map f ⊥ = ⊥ := rfl @[simp] theorem map_coe (f : α → β) (a : α) : map f a = f a := rfl @[simp] lemma map_eq_bot_iff {f : α → β} {a : WithBot α} : map f a = ⊥ ↔ a = ⊥ := Option.map_eq_none_iff theorem map_eq_some_iff {f : α → β} {y : β} {v : WithBot α} : WithBot.map f v = .some y ↔ ∃ x, v = .some x ∧ f x = y := Option.map_eq_some_iff theorem some_eq_map_iff {f : α → β} {y : β} {v : WithBot α} : .some y = WithBot.map f v ↔ ∃ x, v = .some x ∧ f x = y := by cases v <;> simp [eq_comm] theorem map_id : map (id : α → α) = id := Option.map_id @[simp] theorem map_map (h : β → γ) (g : α → β) (a : WithBot α) : map h (map g a) = map (h ∘ g) a := Option.map_map h g a theorem comp_map (h : β → γ) (g : α → β) (x : WithBot α) : x.map (h ∘ g) = (x.map g).map h := (map_map ..).symm @[simp] theorem map_comp_map (f : α → β) (g : β → γ) : WithBot.map g ∘ WithBot.map f = WithBot.map (g ∘ f) := Option.map_comp_map f g theorem map_comm {f₁ : α → β} {f₂ : α → γ} {g₁ : β → δ} {g₂ : γ → δ} (h : g₁ ∘ f₁ = g₂ ∘ f₂) (a : α) : map g₁ (map f₁ a) = map g₂ (map f₂ a) := Option.map_comm h _ theorem map_injective {f : α → β} (Hf : Injective f) : Injective (WithBot.map f) := Option.map_injective Hf /-- The image of a binary function `f : α → β → γ` as a function `WithBot α → WithBot β → WithBot γ`. Mathematically this should be thought of as the image of the corresponding function `α × β → γ`. -/ def map₂ : (α → β → γ) → WithBot α → WithBot β → WithBot γ := Option.map₂ lemma map₂_coe_coe (f : α → β → γ) (a : α) (b : β) : map₂ f a b = f a b := rfl @[simp] lemma map₂_bot_left (f : α → β → γ) (b) : map₂ f ⊥ b = ⊥ := rfl @[simp] lemma map₂_bot_right (f : α → β → γ) (a) : map₂ f a ⊥ = ⊥ := by cases a <;> rfl @[simp] lemma map₂_coe_left (f : α → β → γ) (a : α) (b) : map₂ f a b = b.map fun b ↦ f a b := rfl @[simp] lemma map₂_coe_right (f : α → β → γ) (a) (b : β) : map₂ f a b = a.map (f · b) := by cases a <;> rfl @[simp] lemma map₂_eq_bot_iff {f : α → β → γ} {a : WithBot α} {b : WithBot β} : map₂ f a b = ⊥ ↔ a = ⊥ ∨ b = ⊥ := Option.map₂_eq_none_iff lemma ne_bot_iff_exists {x : WithBot α} : x ≠ ⊥ ↔ ∃ a : α, ↑a = x := Option.ne_none_iff_exists lemma eq_bot_iff_forall_ne {x : WithBot α} : x = ⊥ ↔ ∀ a : α, ↑a ≠ x := Option.eq_none_iff_forall_some_ne theorem forall_ne_bot {p : WithBot α → Prop} : (∀ x, x ≠ ⊥ → p x) ↔ ∀ x : α, p x := by simp [ne_bot_iff_exists] theorem exists_ne_bot {p : WithBot α → Prop} : (∃ x ≠ ⊥, p x) ↔ ∃ x : α, p x := by simp [ne_bot_iff_exists] /-- Deconstruct a `x : WithBot α` to the underlying value in `α`, given a proof that `x ≠ ⊥`. -/ def unbot : ∀ x : WithBot α, x ≠ ⊥ → α | (x : α), _ => x @[simp] lemma coe_unbot : ∀ (x : WithBot α) hx, x.unbot hx = x | (x : α), _ => rfl @[simp] theorem unbot_coe (x : α) (h : (x : WithBot α) ≠ ⊥ := coe_ne_bot) : (x : WithBot α).unbot h = x := rfl instance canLift : CanLift (WithBot α) α (↑) fun r => r ≠ ⊥ where prf x h := ⟨x.unbot h, coe_unbot _ _⟩ instance instTop [Top α] : Top (WithBot α) where top := (⊤ : α) @[simp, norm_cast] lemma coe_top [Top α] : ((⊤ : α) : WithBot α) = ⊤ := rfl @[simp, norm_cast] lemma coe_eq_top [Top α] {a : α} : (a : WithBot α) = ⊤ ↔ a = ⊤ := coe_eq_coe @[simp, norm_cast] lemma top_eq_coe [Top α] {a : α} : ⊤ = (a : WithBot α) ↔ ⊤ = a := coe_eq_coe theorem unbot_eq_iff {a : WithBot α} {b : α} (h : a ≠ ⊥) : a.unbot h = b ↔ a = b := by induction a · simpa using h rfl · simp theorem eq_unbot_iff {a : α} {b : WithBot α} (h : b ≠ ⊥) : a = b.unbot h ↔ a = b := by induction b · simpa using h rfl · simp /-- The equivalence between the non-bottom elements of `WithBot α` and `α`. -/ @[simps] def _root_.Equiv.withBotSubtypeNe : {y : WithBot α // y ≠ ⊥} ≃ α where toFun := fun ⟨x,h⟩ => WithBot.unbot x h invFun x := ⟨x, WithBot.coe_ne_bot⟩ left_inv _ := by simp right_inv _ := by simp /-- Function that sends an element of `WithBot α` to `α`, with an arbitrary default value for `⊥`. -/ noncomputable abbrev unbotA [Nonempty α] : WithBot α → α := unbotD (Classical.arbitrary α) lemma unbotA_eq_unbot [Nonempty α] {a : WithBot α} (ha : a ≠ ⊥) : unbotA a = unbot a ha := by cases a with | bot => contradiction | coe a => simp end WithBot namespace Equiv /-- A universe-polymorphic version of `EquivFunctor.mapEquiv WithBot e`. -/ @[simps apply] def withBotCongr (e : α ≃ β) : WithBot α ≃ WithBot β where toFun := WithBot.map e invFun := WithBot.map e.symm left_inv x := by cases x <;> simp right_inv x := by cases x <;> simp attribute [grind =] withBotCongr_apply @[simp] theorem withBotCongr_refl : withBotCongr (Equiv.refl α) = Equiv.refl _ := Equiv.ext <| congr_fun WithBot.map_id @[simp, grind =] theorem withBotCongr_symm (e : α ≃ β) : withBotCongr e.symm = (withBotCongr e).symm := rfl @[simp] theorem withBotCongr_trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : withBotCongr (e₁.trans e₂) = (withBotCongr e₁).trans (withBotCongr e₂) := by ext x simp end Equiv namespace WithBot variable {a b : α} section LE variable [LE α] {x y : WithBot α} /-- Auxiliary definition for the order on `WithBot`. -/ @[mk_iff le_def_aux] protected inductive LE : WithBot α → WithBot α → Prop | protected bot_le (x : WithBot α) : WithBot.LE ⊥ x | protected coe_le_coe {a b : α} : a ≤ b → WithBot.LE a b /-- The order on `WithBot α`, defined by `⊥ ≤ y` and `a ≤ b → ↑a ≤ ↑b`. Equivalently, `x ≤ y` can be defined as `∀ a : α, x = ↑a → ∃ b : α, y = ↑b ∧ a ≤ b`, see `le_iff_forall`. The definition as an inductive predicate is preferred since it cannot be accidentally unfolded too far. -/ instance (priority := 10) instLE : LE (WithBot α) where le := WithBot.LE lemma le_def : x ≤ y ↔ x = ⊥ ∨ ∃ a b : α, a ≤ b ∧ x = a ∧ y = b := le_def_aux .. lemma le_iff_forall : x ≤ y ↔ ∀ a : α, x = ↑a → ∃ b : α, y = ↑b ∧ a ≤ b := by cases x <;> cases y <;> simp [le_def] @[simp, norm_cast] lemma coe_le_coe : (a : WithBot α) ≤ b ↔ a ≤ b := by simp [le_def] lemma not_coe_le_bot (a : α) : ¬(a : WithBot α) ≤ ⊥ := by simp [le_def] instance instOrderBot : OrderBot (WithBot α) where bot_le := by simp [le_def] instance instBoundedOrder [OrderTop α] : BoundedOrder (WithBot α) where le_top x := by cases x <;> simp [le_def] /-- There is a general version `le_bot_iff`, but this lemma does not require a `PartialOrder`. -/ @[simp] protected theorem le_bot_iff : ∀ {x : WithBot α}, x ≤ ⊥ ↔ x = ⊥ | (a : α) => by simp [not_coe_le_bot] | ⊥ => by simp theorem coe_le : ∀ {o : Option α}, b ∈ o → ((a : WithBot α) ≤ o ↔ a ≤ b) | _, rfl => coe_le_coe theorem coe_le_iff : a ≤ x ↔ ∃ b : α, x = b ∧ a ≤ b := by simp [le_iff_forall] theorem le_coe_iff : x ≤ b ↔ ∀ a : α, x = ↑a → a ≤ b := by simp [le_iff_forall] protected theorem _root_.IsMax.withBot (h : IsMax a) : IsMax (a : WithBot α) := fun x ↦ by cases x <;> simp; simpa using @h _ lemma le_unbot_iff (hy : y ≠ ⊥) : a ≤ unbot y hy ↔ a ≤ y := by lift y to α using id hy; simp lemma unbot_le_iff (hx : x ≠ ⊥) : unbot x hx ≤ b ↔ x ≤ b := by lift x to α using id hx; simp lemma unbotD_le_iff (hx : x = ⊥ → a ≤ b) : x.unbotD a ≤ b ↔ x ≤ b := by cases x <;> simp [hx] @[simp] lemma unbot_le_unbot (hx hy) : unbot x hx ≤ unbot y hy ↔ x ≤ y := by lift x to α using hx lift y to α using hy simp end LE section LT variable [LT α] {x y : WithBot α} /-- Auxiliary definition for the order on `WithBot`. -/ @[mk_iff lt_def_aux] protected inductive LT : WithBot α → WithBot α → Prop | protected bot_lt (b : α) : WithBot.LT ⊥ b | protected coe_lt_coe {a b : α} : a < b → WithBot.LT a b /-- The order on `WithBot α`, defined by `⊥ < ↑a` and `a < b → ↑a < ↑b`. Equivalently, `x < y` can be defined as `∃ b : α, y = ↑b ∧ ∀ a : α, x = ↑a → a < b`, see `lt_iff_exists`. The definition as an inductive predicate is preferred since it cannot be accidentally unfolded too far. -/ instance (priority := 10) instLT : LT (WithBot α) where lt := WithBot.LT lemma lt_def : x < y ↔ (x = ⊥ ∧ ∃ b : α, y = b) ∨ ∃ a b : α, a < b ∧ x = a ∧ y = b := (lt_def_aux ..).trans <| by simp lemma lt_iff_exists : x < y ↔ ∃ b : α, y = ↑b ∧ ∀ a : α, x = ↑a → a < b := by cases x <;> cases y <;> simp [lt_def] @[simp, norm_cast] lemma coe_lt_coe : (a : WithBot α) < b ↔ a < b := by simp [lt_def] @[simp] lemma bot_lt_coe (a : α) : ⊥ < (a : WithBot α) := by simp [lt_def] @[simp] protected lemma not_lt_bot (a : WithBot α) : ¬a < ⊥ := by simp [lt_def] lemma lt_iff_exists_coe : x < y ↔ ∃ b : α, y = b ∧ x < b := by cases y <;> simp lemma lt_coe_iff : x < b ↔ ∀ a : α, x = a → a < b := by simp [lt_iff_exists] /-- A version of `bot_lt_iff_ne_bot` for `WithBot` that only requires `LT α`, not `PartialOrder α`. -/ protected lemma bot_lt_iff_ne_bot : ⊥ < x ↔ x ≠ ⊥ := by cases x <;> simp lemma lt_unbot_iff (hy : y ≠ ⊥) : a < unbot y hy ↔ a < y := by lift y to α using hy; simp lemma unbot_lt_iff (hx : x ≠ ⊥) : unbot x hx < b ↔ x < b := by lift x to α using hx; simp lemma unbotD_lt_iff (hx : x = ⊥ → a < b) : x.unbotD a < b ↔ x < b := by cases x <;> simp [hx] @[simp] lemma unbot_lt_unbot (hx hy) : unbot x hx < unbot y hy ↔ x < y := by lift x to α using hx lift y to α using hy simp end LT instance instPreorder [Preorder α] : Preorder (WithBot α) where lt_iff_le_not_ge x y := by cases x <;> cases y <;> simp [lt_iff_le_not_ge] le_refl x := by cases x <;> simp [le_def] le_trans x y z := by cases x <;> cases y <;> cases z <;> simp [le_def]; simpa using le_trans instance instPartialOrder [PartialOrder α] : PartialOrder (WithBot α) where le_antisymm x y := by cases x <;> cases y <;> simp [le_def]; simpa using le_antisymm section Preorder variable [Preorder α] [Preorder β] {x y : WithBot α} theorem coe_strictMono : StrictMono (fun (a : α) => (a : WithBot α)) := fun _ _ => coe_lt_coe.2 theorem coe_mono : Monotone (fun (a : α) => (a : WithBot α)) := fun _ _ => coe_le_coe.2 theorem monotone_iff {f : WithBot α → β} : Monotone f ↔ Monotone (fun a ↦ f a : α → β) ∧ ∀ x : α, f ⊥ ≤ f x := ⟨fun h ↦ ⟨h.comp WithBot.coe_mono, fun _ ↦ h bot_le⟩, fun h ↦ WithBot.forall.2 ⟨WithBot.forall.2 ⟨fun _ => le_rfl, fun x _ => h.2 x⟩, fun _ => WithBot.forall.2 ⟨fun h => (not_coe_le_bot _ h).elim, fun _ hle => h.1 (coe_le_coe.1 hle)⟩⟩⟩ @[simp] theorem monotone_map_iff {f : α → β} : Monotone (WithBot.map f) ↔ Monotone f := monotone_iff.trans <| by simp [Monotone] alias ⟨_, _root_.Monotone.withBot_map⟩ := monotone_map_iff theorem strictMono_iff {f : WithBot α → β} : StrictMono f ↔ StrictMono (fun a => f a : α → β) ∧ ∀ x : α, f ⊥ < f x := ⟨fun h => ⟨h.comp WithBot.coe_strictMono, fun _ => h (bot_lt_coe _)⟩, fun h => WithBot.forall.2 ⟨WithBot.forall.2 ⟨flip absurd (lt_irrefl _), fun x _ => h.2 x⟩, fun _ => WithBot.forall.2 ⟨fun h => (not_lt_bot h).elim, fun _ hle => h.1 (coe_lt_coe.1 hle)⟩⟩⟩ theorem strictAnti_iff {f : WithBot α → β} : StrictAnti f ↔ StrictAnti (fun a ↦ f a : α → β) ∧ ∀ x : α, f x < f ⊥ := strictMono_iff (β := βᵒᵈ) @[simp] theorem strictMono_map_iff {f : α → β} : StrictMono (WithBot.map f) ↔ StrictMono f := strictMono_iff.trans <| by simp [StrictMono, bot_lt_coe] alias ⟨_, _root_.StrictMono.withBot_map⟩ := strictMono_map_iff lemma map_le_iff (f : α → β) (mono_iff : ∀ {a b}, f a ≤ f b ↔ a ≤ b) : x.map f ≤ y.map f ↔ x ≤ y := by cases x <;> cases y <;> simp [mono_iff] theorem le_coe_unbotD (x : WithBot α) (b : α) : x ≤ x.unbotD b := by cases x <;> simp @[simp] theorem lt_coe_bot [OrderBot α] : x < (⊥ : α) ↔ x = ⊥ := by cases x <;> simp lemma eq_bot_iff_forall_lt : x = ⊥ ↔ ∀ b : α, x < b := by cases x <;> simp; simpa using ⟨_, lt_irrefl _⟩ lemma eq_bot_iff_forall_le [NoBotOrder α] : x = ⊥ ↔ ∀ b : α, x ≤ b := by refine ⟨by simp +contextual, fun h ↦ (x.eq_bot_iff_forall_ne).2 fun y => ?_⟩ rintro rfl exact not_isBot y fun z => coe_le_coe.1 (h z) lemma forall_coe_le_iff_le [NoBotOrder α] : (∀ a : α, a ≤ x → a ≤ y) ↔ x ≤ y := by obtain _ | a := x · simpa [WithBot.none_eq_bot, eq_bot_iff_forall_le] using fun a ha ↦ (not_isBot _ ha).elim · exact ⟨fun h ↦ h _ le_rfl, fun hay b ↦ hay.trans'⟩ lemma forall_le_coe_iff_le [NoBotOrder α] : (∀ a : α, y ≤ a → x ≤ a) ↔ x ≤ y := by obtain _ | y := y · simp [WithBot.none_eq_bot, eq_bot_iff_forall_le] · exact ⟨fun h ↦ h _ le_rfl, fun hmn a ham ↦ hmn.trans ham⟩ end Preorder section PartialOrder variable [PartialOrder α] [NoBotOrder α] {x y : WithBot α} lemma eq_of_forall_coe_le_iff (h : ∀ a : α, a ≤ x ↔ a ≤ y) : x = y := le_antisymm (forall_coe_le_iff_le.mp fun a ↦ (h a).1) (forall_coe_le_iff_le.mp fun a ↦ (h a).2) lemma eq_of_forall_le_coe_iff (h : ∀ a : α, x ≤ a ↔ y ≤ a) : x = y := le_antisymm (forall_le_coe_iff_le.mp fun a ↦ (h a).2) (forall_le_coe_iff_le.mp fun a ↦ (h a).1) end PartialOrder instance semilatticeSup [SemilatticeSup α] : SemilatticeSup (WithBot α) where sup -- note this is `Option.merge`, but with the right defeq when unfolding | ⊥, ⊥ => ⊥ | (a : α), ⊥ => a | ⊥, (b : α) => b | (a : α), (b : α) => ↑(a ⊔ b) le_sup_left x y := by cases x <;> cases y <;> simp le_sup_right x y := by cases x <;> cases y <;> simp sup_le x y z := by cases x <;> cases y <;> cases z <;> simp; simpa using sup_le theorem coe_sup [SemilatticeSup α] (a b : α) : ((a ⊔ b : α) : WithBot α) = (a : WithBot α) ⊔ b := rfl instance semilatticeInf [SemilatticeInf α] : SemilatticeInf (WithBot α) where inf := .map₂ (· ⊓ ·) inf_le_left x y := by cases x <;> cases y <;> simp inf_le_right x y := by cases x <;> cases y <;> simp le_inf x y z := by cases x <;> cases y <;> cases z <;> simp; simpa using le_inf theorem coe_inf [SemilatticeInf α] (a b : α) : ((a ⊓ b : α) : WithBot α) = (a : WithBot α) ⊓ b := rfl instance lattice [Lattice α] : Lattice (WithBot α) := { WithBot.semilatticeSup, WithBot.semilatticeInf with } instance distribLattice [DistribLattice α] : DistribLattice (WithBot α) where le_sup_inf x y z := by cases x <;> cases y <;> cases z <;> simp [← coe_inf, ← coe_sup] simpa [← coe_inf, ← coe_sup] using le_sup_inf instance decidableEq [DecidableEq α] : DecidableEq (WithBot α) := inferInstanceAs <| DecidableEq (Option α) instance decidableLE [LE α] [DecidableLE α] : DecidableLE (WithBot α) | ⊥, _ => isTrue <| by simp | (a : α), ⊥ => isFalse <| by simp | (a : α), (b : α) => decidable_of_iff' _ coe_le_coe instance decidableLT [LT α] [DecidableLT α] : DecidableLT (WithBot α) | _, ⊥ => isFalse <| by simp | ⊥, (a : α) => isTrue <| by simp | (a : α), (b : α) => decidable_of_iff' _ coe_lt_coe instance isTotal_le [LE α] [IsTotal α (· ≤ ·)] : IsTotal (WithBot α) (· ≤ ·) where total x y := by cases x <;> cases y <;> simp; simpa using IsTotal.total .. section LinearOrder variable [LinearOrder α] {x y : WithBot α} instance linearOrder : LinearOrder (WithBot α) := Lattice.toLinearOrder _ @[simp, norm_cast] lemma coe_min (a b : α) : ↑(min a b) = min (a : WithBot α) b := rfl @[simp, norm_cast] lemma coe_max (a b : α) : ↑(max a b) = max (a : WithBot α) b := rfl variable [DenselyOrdered α] [NoMinOrder α] lemma le_of_forall_lt_iff_le : (∀ z : α, x < z → y ≤ z) ↔ y ≤ x := by cases x <;> cases y <;> simp [exists_lt, forall_gt_imp_ge_iff_le_of_dense] lemma ge_of_forall_gt_iff_ge : (∀ z : α, z < x → z ≤ y) ↔ x ≤ y := by cases x <;> cases y <;> simp [exists_lt, forall_lt_imp_le_iff_le_of_dense] end LinearOrder instance instWellFoundedLT [LT α] [WellFoundedLT α] : WellFoundedLT (WithBot α) where wf := .intro fun | ⊥ => ⟨_, by simp⟩ | (a : α) => (wellFounded_lt.1 a).rec fun _ _ ih ↦ .intro _ fun | ⊥, _ => ⟨_, by simp⟩ | (b : α), hlt => ih _ (coe_lt_coe.1 hlt) instance _root_.WithBot.instWellFoundedGT [LT α] [WellFoundedGT α] : WellFoundedGT (WithBot α) where wf := have acc_some (a : α) : Acc ((· > ·) : WithBot α → WithBot α → Prop) a := (wellFounded_gt.1 a).rec fun _ _ ih => .intro _ fun | (b : α), hlt => ih _ (coe_lt_coe.1 hlt) .intro fun | (a : α) => acc_some a | ⊥ => .intro _ fun | (b : α), _ => acc_some b lemma denselyOrdered_iff [LT α] [NoMinOrder α] : DenselyOrdered (WithBot α) ↔ DenselyOrdered α := by constructor <;> intro h <;> constructor · intro a b hab obtain ⟨c, hc⟩ := exists_between (WithBot.coe_lt_coe.mpr hab) induction c with | bot => simp at hc | coe c => exact ⟨c, by simpa using hc⟩ · simpa [WithBot.exists, WithBot.forall, exists_lt] using DenselyOrdered.dense instance denselyOrdered [LT α] [DenselyOrdered α] [NoMinOrder α] : DenselyOrdered (WithBot α) := denselyOrdered_iff.mpr inferInstance theorem lt_iff_exists_coe_btwn [Preorder α] [DenselyOrdered α] [NoMinOrder α] {a b : WithBot α} : a < b ↔ ∃ x : α, a < ↑x ∧ ↑x < b := ⟨fun h => let ⟨_, hy⟩ := exists_between h let ⟨x, hx⟩ := lt_iff_exists_coe.1 hy.1 ⟨x, hx.1 ▸ hy⟩, fun ⟨_, hx⟩ => lt_trans hx.1 hx.2⟩ instance noTopOrder [LE α] [NoTopOrder α] [Nonempty α] : NoTopOrder (WithBot α) where exists_not_le := fun | ⊥ => ‹Nonempty α›.elim fun a ↦ ⟨a, by simp⟩ | (a : α) => let ⟨b, hba⟩ := exists_not_le a; ⟨b, mod_cast hba⟩ instance noMaxOrder [LT α] [NoMaxOrder α] [Nonempty α] : NoMaxOrder (WithBot α) where exists_gt := fun | ⊥ => ‹Nonempty α›.elim fun a ↦ ⟨a, by simp⟩ | (a : α) => let ⟨b, hba⟩ := exists_gt a; ⟨b, mod_cast hba⟩ end WithBot namespace WithTop variable {a b : α} instance nontrivial [Nonempty α] : Nontrivial (WithTop α) := Option.nontrivial instance [IsEmpty α] : Unique (WithTop α) := Option.instUniqueOfIsEmpty open Function theorem coe_injective : Injective ((↑) : α → WithTop α) := Option.some_injective _ @[norm_cast] theorem coe_inj : (a : WithTop α) = b ↔ a = b := Option.some_inj protected theorem «forall» {p : WithTop α → Prop} : (∀ x, p x) ↔ p ⊤ ∧ ∀ x : α, p x := Option.forall protected theorem «exists» {p : WithTop α → Prop} : (∃ x, p x) ↔ p ⊤ ∨ ∃ x : α, p x := Option.exists theorem none_eq_top : (none : WithTop α) = (⊤ : WithTop α) := rfl theorem some_eq_coe (a : α) : (Option.some a : WithTop α) = (↑a : WithTop α) := rfl @[simp] theorem top_ne_coe : ⊤ ≠ (a : WithTop α) := nofun @[simp] theorem coe_ne_top : (a : WithTop α) ≠ ⊤ := nofun /-- `WithTop.toDual` is the equivalence sending `⊤` to `⊥` and any `a : α` to `toDual a : αᵒᵈ`. See `WithTop.toDualBotEquiv` for the related order-iso. -/ protected def toDual : WithTop α ≃ WithBot αᵒᵈ := Equiv.refl _ /-- `WithTop.ofDual` is the equivalence sending `⊤` to `⊥` and any `a : αᵒᵈ` to `ofDual a : α`. See `WithTop.toDualBotEquiv` for the related order-iso. -/ protected def ofDual : WithTop αᵒᵈ ≃ WithBot α := Equiv.refl _ /-- `WithBot.toDual` is the equivalence sending `⊥` to `⊤` and any `a : α` to `toDual a : αᵒᵈ`. See `WithBot.toDual_top_equiv` for the related order-iso. -/ protected def _root_.WithBot.toDual : WithBot α ≃ WithTop αᵒᵈ := Equiv.refl _ /-- `WithBot.ofDual` is the equivalence sending `⊥` to `⊤` and any `a : αᵒᵈ` to `ofDual a : α`. See `WithBot.ofDual_top_equiv` for the related order-iso. -/ protected def _root_.WithBot.ofDual : WithBot αᵒᵈ ≃ WithTop α := Equiv.refl _ @[simp] theorem toDual_symm_apply (a : WithBot αᵒᵈ) : WithTop.toDual.symm a = WithBot.ofDual a := rfl @[simp] theorem ofDual_symm_apply (a : WithBot α) : WithTop.ofDual.symm a = WithBot.toDual a := rfl @[simp] theorem toDual_apply_top : WithTop.toDual (⊤ : WithTop α) = ⊥ := rfl @[simp] theorem ofDual_apply_top : WithTop.ofDual (⊤ : WithTop α) = ⊥ := rfl open OrderDual @[simp] theorem toDual_apply_coe (a : α) : WithTop.toDual (a : WithTop α) = toDual a := rfl @[simp] theorem ofDual_apply_coe (a : αᵒᵈ) : WithTop.ofDual (a : WithTop αᵒᵈ) = ofDual a := rfl /-- Specialization of `Option.getD` to values in `WithTop α` that respects API boundaries. -/ def untopD (d : α) (x : WithTop α) : α := recTopCoe d id x @[simp] theorem untopD_top {α} (d : α) : untopD d ⊤ = d := rfl @[simp] theorem untopD_coe {α} (d x : α) : untopD d x = x := rfl @[simp, norm_cast] theorem coe_eq_coe : (a : WithTop α) = b ↔ a = b := Option.some_inj theorem untopD_eq_iff {d y : α} {x : WithTop α} : untopD d x = y ↔ x = y ∨ x = ⊤ ∧ y = d := WithBot.unbotD_eq_iff @[simp] theorem untopD_eq_self_iff {d : α} {x : WithTop α} : untopD d x = d ↔ x = d ∨ x = ⊤ := WithBot.unbotD_eq_self_iff theorem untopD_eq_untopD_iff {d : α} {x y : WithTop α} : untopD d x = untopD d y ↔ x = y ∨ x = d ∧ y = ⊤ ∨ x = ⊤ ∧ y = d := WithBot.unbotD_eq_unbotD_iff /-- Lift a map `f : α → β` to `WithTop α → WithTop β`. Implemented using `Option.map`. -/ def map (f : α → β) : WithTop α → WithTop β := Option.map f @[simp] theorem map_top (f : α → β) : map f ⊤ = ⊤ := rfl @[simp] theorem map_coe (f : α → β) (a : α) : map f a = f a := rfl @[simp] lemma map_eq_top_iff {f : α → β} {a : WithTop α} : map f a = ⊤ ↔ a = ⊤ := Option.map_eq_none_iff theorem map_eq_some_iff {f : α → β} {y : β} {v : WithTop α} : WithTop.map f v = .some y ↔ ∃ x, v = .some x ∧ f x = y := Option.map_eq_some_iff theorem some_eq_map_iff {f : α → β} {y : β} {v : WithTop α} : .some y = WithTop.map f v ↔ ∃ x, v = .some x ∧ f x = y := by cases v <;> simp [eq_comm] theorem map_id : map (id : α → α) = id := Option.map_id @[simp] theorem map_map (h : β → γ) (g : α → β) (a : WithTop α) : map h (map g a) = map (h ∘ g) a := Option.map_map h g a theorem comp_map (h : β → γ) (g : α → β) (x : WithTop α) : x.map (h ∘ g) = (x.map g).map h := (map_map ..).symm @[simp] theorem map_comp_map (f : α → β) (g : β → γ) : WithTop.map g ∘ WithTop.map f = WithTop.map (g ∘ f) := Option.map_comp_map f g theorem map_comm {f₁ : α → β} {f₂ : α → γ} {g₁ : β → δ} {g₂ : γ → δ} (h : g₁ ∘ f₁ = g₂ ∘ f₂) (a : α) : map g₁ (map f₁ a) = map g₂ (map f₂ a) := Option.map_comm h _ theorem map_injective {f : α → β} (Hf : Injective f) : Injective (WithTop.map f) := Option.map_injective Hf /-- The image of a binary function `f : α → β → γ` as a function `WithTop α → WithTop β → WithTop γ`. Mathematically this should be thought of as the image of the corresponding function `α × β → γ`. -/ def map₂ : (α → β → γ) → WithTop α → WithTop β → WithTop γ := Option.map₂ lemma map₂_coe_coe (f : α → β → γ) (a : α) (b : β) : map₂ f a b = f a b := rfl @[simp] lemma map₂_top_left (f : α → β → γ) (b) : map₂ f ⊤ b = ⊤ := rfl @[simp] lemma map₂_top_right (f : α → β → γ) (a) : map₂ f a ⊤ = ⊤ := by cases a <;> rfl @[simp] lemma map₂_coe_left (f : α → β → γ) (a : α) (b) : map₂ f a b = b.map fun b ↦ f a b := rfl @[simp] lemma map₂_coe_right (f : α → β → γ) (a) (b : β) : map₂ f a b = a.map (f · b) := by cases a <;> rfl @[simp] lemma map₂_eq_top_iff {f : α → β → γ} {a : WithTop α} {b : WithTop β} : map₂ f a b = ⊤ ↔ a = ⊤ ∨ b = ⊤ := Option.map₂_eq_none_iff theorem map_toDual (f : αᵒᵈ → βᵒᵈ) (a : WithBot α) : map f (WithBot.toDual a) = a.map (toDual ∘ f) := rfl theorem map_ofDual (f : α → β) (a : WithBot αᵒᵈ) : map f (WithBot.ofDual a) = a.map (ofDual ∘ f) := rfl theorem toDual_map (f : α → β) (a : WithTop α) : WithTop.toDual (map f a) = WithBot.map (toDual ∘ f ∘ ofDual) (WithTop.toDual a) := rfl theorem ofDual_map (f : αᵒᵈ → βᵒᵈ) (a : WithTop αᵒᵈ) : WithTop.ofDual (map f a) = WithBot.map (ofDual ∘ f ∘ toDual) (WithTop.ofDual a) := rfl lemma ne_top_iff_exists {x : WithTop α} : x ≠ ⊤ ↔ ∃ a : α, ↑a = x := Option.ne_none_iff_exists lemma eq_top_iff_forall_ne {x : WithTop α} : x = ⊤ ↔ ∀ a : α, ↑a ≠ x := Option.eq_none_iff_forall_some_ne theorem forall_ne_top {p : WithTop α → Prop} : (∀ x, x ≠ ⊤ → p x) ↔ ∀ x : α, p x := by simp [ne_top_iff_exists] theorem exists_ne_top {p : WithTop α → Prop} : (∃ x ≠ ⊤, p x) ↔ ∃ x : α, p x := by simp [ne_top_iff_exists] /-- Deconstruct a `x : WithTop α` to the underlying value in `α`, given a proof that `x ≠ ⊤`. -/ def untop : ∀ x : WithTop α, x ≠ ⊤ → α | (x : α), _ => x @[simp] lemma coe_untop : ∀ (x : WithTop α) hx, x.untop hx = x | (x : α), _ => rfl @[simp] theorem untop_coe (x : α) (h : (x : WithTop α) ≠ ⊤ := coe_ne_top) : (x : WithTop α).untop h = x := rfl instance canLift : CanLift (WithTop α) α (↑) fun r => r ≠ ⊤ where prf x h := ⟨x.untop h, coe_untop _ _⟩ instance instBot [Bot α] : Bot (WithTop α) where bot := (⊥ : α) @[simp, norm_cast] lemma coe_bot [Bot α] : ((⊥ : α) : WithTop α) = ⊥ := rfl @[simp, norm_cast] lemma coe_eq_bot [Bot α] {a : α} : (a : WithTop α) = ⊥ ↔ a = ⊥ := coe_eq_coe @[simp, norm_cast] lemma bot_eq_coe [Bot α] {a : α} : (⊥ : WithTop α) = a ↔ ⊥ = a := coe_eq_coe theorem untop_eq_iff {a : WithTop α} {b : α} (h : a ≠ ⊤) : a.untop h = b ↔ a = b := WithBot.unbot_eq_iff (α := αᵒᵈ) h theorem eq_untop_iff {a : α} {b : WithTop α} (h : b ≠ ⊤) : a = b.untop h ↔ a = b := WithBot.eq_unbot_iff (α := αᵒᵈ) h /-- The equivalence between the non-top elements of `WithTop α` and `α`. -/ @[simps] def _root_.Equiv.withTopSubtypeNe : {y : WithTop α // y ≠ ⊤} ≃ α where toFun := fun ⟨x,h⟩ => WithTop.untop x h invFun x := ⟨x, WithTop.coe_ne_top⟩ left_inv _ := by simp right_inv _:= by simp /-- Function that sends an element of `WithTop α` to `α`, with an arbitrary default value for `⊤`. -/ noncomputable abbrev untopA [Nonempty α] : WithTop α → α := untopD (Classical.arbitrary α) lemma untopA_eq_untop [Nonempty α] {a : WithTop α} (ha : a ≠ ⊤) : untopA a = untop a ha := by cases a with | top => contradiction | coe a => simp end WithTop namespace Equiv /-- A universe-polymorphic version of `EquivFunctor.mapEquiv WithTop e`. -/ @[simps apply] def withTopCongr (e : α ≃ β) : WithTop α ≃ WithTop β where toFun := WithTop.map e invFun := WithTop.map e.symm left_inv x := by cases x <;> simp right_inv x := by cases x <;> simp attribute [grind =] withTopCongr_apply @[simp] theorem withTopCongr_refl : withTopCongr (Equiv.refl α) = Equiv.refl _ := Equiv.ext <| congr_fun WithBot.map_id @[simp, grind =] theorem withTopCongr_symm (e : α ≃ β) : withTopCongr e.symm = (withTopCongr e).symm := rfl @[simp] theorem withTopCongr_trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : withTopCongr (e₁.trans e₂) = (withTopCongr e₁).trans (withTopCongr e₂) := by ext x simp end Equiv namespace WithTop variable {a b : α} section LE variable [LE α] {x y : WithTop α} /-- The order on `WithTop α`, defined by `x ≤ ⊤` and `a ≤ b → ↑a ≤ ↑b`. Equivalently, `x ≤ y` can be defined as `∀ b : α, y = ↑b → ∃ a : α, x = ↑a ∧ a ≤ b`, see `le_iff_forall`. The definition as an inductive predicate is preferred since it cannot be accidentally unfolded too far. -/ instance (priority := 10) instLE : LE (WithTop α) where le a b := WithBot.LE (α := αᵒᵈ) b a lemma le_def : x ≤ y ↔ y = ⊤ ∨ ∃ a b : α, a ≤ b ∧ x = a ∧ y = b := WithBot.le_def.trans <| or_congr_right <| exists_swap.trans <| exists₂_congr fun _ _ ↦ and_congr_right' and_comm lemma le_iff_forall : x ≤ y ↔ ∀ b : α, y = ↑b → ∃ a : α, x = ↑a ∧ a ≤ b := by cases x <;> cases y <;> simp [le_def] @[simp, norm_cast] lemma coe_le_coe : (a : WithTop α) ≤ b ↔ a ≤ b := by simp [le_def] lemma not_top_le_coe (a : α) : ¬ ⊤ ≤ (a : WithTop α) := by simp [le_def] instance orderTop : OrderTop (WithTop α) where le_top := by simp [le_def] instance orderBot [OrderBot α] : OrderBot (WithTop α) where bot_le x := by cases x <;> simp [le_def] instance boundedOrder [OrderBot α] : BoundedOrder (WithTop α) := { WithTop.orderTop, WithTop.orderBot with } /-- There is a general version `top_le_iff`, but this lemma does not require a `PartialOrder`. -/ @[simp] protected theorem top_le_iff : ∀ {a : WithTop α}, ⊤ ≤ a ↔ a = ⊤ | (a : α) => by simp [not_top_le_coe _] | ⊤ => by simp theorem le_coe : ∀ {o : Option α}, a ∈ o → (@LE.le (WithTop α) _ o b ↔ a ≤ b) | _, rfl => coe_le_coe theorem le_coe_iff : x ≤ b ↔ ∃ a : α, x = a ∧ a ≤ b := by simp [le_iff_forall] theorem coe_le_iff : ↑a ≤ x ↔ ∀ b : α, x = ↑b → a ≤ b := by simp [le_iff_forall] protected theorem _root_.IsMin.withTop (h : IsMin a) : IsMin (a : WithTop α) := fun x ↦ by cases x <;> simp; simpa using @h _ lemma untop_le_iff (hx : x ≠ ⊤) : untop x hx ≤ b ↔ x ≤ b := by lift x to α using id hx; simp lemma le_untop_iff (hy : y ≠ ⊤) : a ≤ untop y hy ↔ a ≤ y := by lift y to α using id hy; simp lemma untopD_le_iff (hy : y ≠ ⊤) : y.untopD a ≤ b ↔ y ≤ b := by lift y to α using id hy; simp lemma le_untopD_iff (hy : y = ⊤ → a ≤ b) : a ≤ y.untopD b ↔ a ≤ y := by cases y <;> simp [hy] lemma untopA_le_iff [Nonempty α] (hy : y ≠ ⊤) : y.untopA ≤ b ↔ y ≤ b := untopD_le_iff hy lemma le_untopA_iff [Nonempty α] (hy : y ≠ ⊤) : a ≤ y.untopA ↔ a ≤ y := by lift y to α using id hy; simp lemma untop_mono (hx : x ≠ ⊤) (hy : y ≠ ⊤) (h : x ≤ y) : x.untop hx ≤ y.untop hy := by lift x to α using id hx lift y to α using id hy simp only [untop_coe] exact mod_cast h lemma untopD_mono (hy : y ≠ ⊤) (h : x ≤ y) : x.untopD a ≤ y.untopD a := by lift y to α using hy cases x with | top => simp at h | coe a => simp only [WithTop.untopD_coe]; exact mod_cast h lemma untopA_mono [Nonempty α] (hy : y ≠ ⊤) (h : x ≤ y) : x.untopA ≤ y.untopA := untopD_mono hy h end LE section LT variable [LT α] {x y : WithTop α} /-- The order on `WithTop α`, defined by `↑a < ⊤` and `a < b → ↑a < ↑b`. Equivalently, `x < y` can be defined as `∃ a : α, x = ↑a ∧ ∀ b : α, y = ↑b → a < b`, see `le_if_forall`. The definition as an inductive predicate is preferred since it cannot be accidentally unfolded too far. -/ instance (priority := 10) instLT : LT (WithTop α) where lt a b := WithBot.LT (α := αᵒᵈ) b a lemma lt_def : x < y ↔ (∃ a : α, x = ↑a) ∧ y = ⊤ ∨ ∃ a b : α, a < b ∧ x = ↑a ∧ y = ↑b := WithBot.lt_def.trans <| or_congr and_comm <| exists_swap.trans <| exists₂_congr fun _ _ ↦ and_congr_right' and_comm lemma lt_iff_exists : x < y ↔ ∃ a : α, x = ↑a ∧ ∀ b : α, y = ↑b → a < b := by cases x <;> cases y <;> simp [lt_def] @[simp, norm_cast] lemma coe_lt_coe : (a : WithTop α) < b ↔ a < b := by simp [lt_def] @[simp] lemma coe_lt_top (a : α) : (a : WithTop α) < ⊤ := by simp [lt_def] @[simp] protected lemma not_top_lt (a : WithTop α) : ¬⊤ < a := by simp [lt_def] lemma lt_iff_exists_coe : x < y ↔ ∃ a : α, x = a ∧ a < y := by cases x <;> simp lemma coe_lt_iff : a < y ↔ ∀ b : α, y = b → a < b := by simp [lt_iff_exists] /-- A version of `lt_top_iff_ne_top` for `WithTop` that only requires `LT α`, not `PartialOrder α`. -/ protected lemma lt_top_iff_ne_top : x < ⊤ ↔ x ≠ ⊤ := by cases x <;> simp @[simp] lemma lt_untop_iff (hy : y ≠ ⊤) : a < y.untop hy ↔ a < y := by lift y to α using id hy; simp @[simp] lemma untop_lt_iff (hx : x ≠ ⊤) : x.untop hx < b ↔ x < b := by lift x to α using id hx; simp lemma lt_untopD_iff (hy : y = ⊤ → a < b) : a < y.untopD b ↔ a < y := by cases y <;> simp [hy] lemma untopD_lt_iff (hx : x ≠ ⊤) : x.untopD a < b ↔ x < b := by lift x to α using id hx; simp lemma lt_untopA_iff [Nonempty α] (hy : y ≠ ⊤) : a < y.untopA ↔ a < y := by lift y to α using id hy; simp lemma untopA_lt_iff [Nonempty α] (hx : x ≠ ⊤) : x.untopA < b ↔ x < b := untopD_lt_iff hx end LT instance preorder [Preorder α] : Preorder (WithTop α) where lt_iff_le_not_ge x y := by cases x <;> cases y <;> simp [lt_iff_le_not_ge] le_refl x := by cases x <;> simp [le_def] le_trans x y z := by cases x <;> cases y <;> cases z <;> simp [le_def]; simpa using le_trans instance partialOrder [PartialOrder α] : PartialOrder (WithTop α) where le_antisymm x y := by cases x <;> cases y <;> simp [le_def]; simpa using le_antisymm section Preorder variable [Preorder α] [Preorder β] {x y : WithTop α} theorem coe_strictMono : StrictMono (fun a : α => (a : WithTop α)) := fun _ _ => coe_lt_coe.2 theorem coe_mono : Monotone (fun a : α => (a : WithTop α)) := fun _ _ => coe_le_coe.2 theorem monotone_iff {f : WithTop α → β} : Monotone f ↔ Monotone (fun (a : α) => f a) ∧ ∀ x : α, f x ≤ f ⊤ := ⟨fun h => ⟨h.comp WithTop.coe_mono, fun _ => h le_top⟩, fun h => WithTop.forall.2 ⟨WithTop.forall.2 ⟨fun _ => le_rfl, fun _ h => (not_top_le_coe _ h).elim⟩, fun x => WithTop.forall.2 ⟨fun _ => h.2 x, fun _ hle => h.1 (coe_le_coe.1 hle)⟩⟩⟩ @[simp] theorem monotone_map_iff {f : α → β} : Monotone (WithTop.map f) ↔ Monotone f := monotone_iff.trans <| by simp [Monotone] alias ⟨_, _root_.Monotone.withTop_map⟩ := monotone_map_iff theorem strictMono_iff {f : WithTop α → β} : StrictMono f ↔ StrictMono (fun (a : α) => f a) ∧ ∀ x : α, f x < f ⊤ := ⟨fun h => ⟨h.comp WithTop.coe_strictMono, fun _ => h (coe_lt_top _)⟩, fun h => WithTop.forall.2 ⟨WithTop.forall.2 ⟨flip absurd (lt_irrefl _), fun _ h => (not_top_lt h).elim⟩, fun x => WithTop.forall.2 ⟨fun _ => h.2 x, fun _ hle => h.1 (coe_lt_coe.1 hle)⟩⟩⟩ theorem strictAnti_iff {f : WithTop α → β} : StrictAnti f ↔ StrictAnti (fun a ↦ f a : α → β) ∧ ∀ x : α, f ⊤ < f x := strictMono_iff (β := βᵒᵈ) @[simp] theorem strictMono_map_iff {f : α → β} : StrictMono (WithTop.map f) ↔ StrictMono f := strictMono_iff.trans <| by simp [StrictMono, coe_lt_top] alias ⟨_, _root_.StrictMono.withTop_map⟩ := strictMono_map_iff theorem map_le_iff (f : α → β) (mono_iff : ∀ {a b}, f a ≤ f b ↔ a ≤ b) : x.map f ≤ y.map f ↔ x ≤ y := by cases x <;> cases y <;> simp [mono_iff] theorem coe_untopD_le (y : WithTop α) (a : α) : y.untopD a ≤ y := by cases y <;> simp @[simp] theorem coe_top_lt [OrderTop α] : (⊤ : α) < x ↔ x = ⊤ := by cases x <;> simp lemma eq_top_iff_forall_gt : y = ⊤ ↔ ∀ a : α, a < y := by cases y <;> simp; simpa using ⟨_, lt_irrefl _⟩ lemma eq_top_iff_forall_ge [NoTopOrder α] : y = ⊤ ↔ ∀ a : α, a ≤ y := WithBot.eq_bot_iff_forall_le (α := αᵒᵈ) lemma forall_coe_le_iff_le [NoTopOrder α] : (∀ a : α, a ≤ x → a ≤ y) ↔ x ≤ y := WithBot.forall_le_coe_iff_le (α := αᵒᵈ) lemma forall_le_coe_iff_le [NoTopOrder α] : (∀ a : α, y ≤ a → x ≤ a) ↔ x ≤ y := WithBot.forall_coe_le_iff_le (α := αᵒᵈ) end Preorder section PartialOrder variable [PartialOrder α] {x y : WithTop α} lemma untopD_le (hy : y ≤ b) : y.untopD a ≤ b := by rwa [untopD_le_iff] exact ne_top_of_le_ne_top (by simp) hy lemma untopA_le [Nonempty α] (hy : y ≤ b) : y.untopA ≤ b := untopD_le hy variable [NoTopOrder α] lemma eq_of_forall_le_coe_iff (h : ∀ a : α, x ≤ a ↔ y ≤ a) : x = y := WithBot.eq_of_forall_coe_le_iff (α := αᵒᵈ) h lemma eq_of_forall_coe_le_iff (h : ∀ a : α, a ≤ x ↔ a ≤ y) : x = y := WithBot.eq_of_forall_le_coe_iff (α := αᵒᵈ) h end PartialOrder instance semilatticeInf [SemilatticeInf α] : SemilatticeInf (WithTop α) where inf -- note this is `Option.merge`, but with the right defeq when unfolding | ⊤, ⊤ => ⊤ | (a : α), ⊤ => a | ⊤, (b : α) => b | (a : α), (b : α) => ↑(a ⊓ b) inf_le_left x y := by cases x <;> cases y <;> simp inf_le_right x y := by cases x <;> cases y <;> simp le_inf x y z := by cases x <;> cases y <;> cases z <;> simp; simpa using le_inf theorem coe_inf [SemilatticeInf α] (a b : α) : ((a ⊓ b : α) : WithTop α) = (a : WithTop α) ⊓ b := rfl instance semilatticeSup [SemilatticeSup α] : SemilatticeSup (WithTop α) where sup := .map₂ (· ⊔ ·) le_sup_left x y := by cases x <;> cases y <;> simp le_sup_right x y := by cases x <;> cases y <;> simp sup_le x y z := by cases x <;> cases y <;> cases z <;> simp; simpa using sup_le theorem coe_sup [SemilatticeSup α] (a b : α) : ((a ⊔ b : α) : WithTop α) = (a : WithTop α) ⊔ b := rfl instance lattice [Lattice α] : Lattice (WithTop α) := { WithTop.semilatticeSup, WithTop.semilatticeInf with } instance distribLattice [DistribLattice α] : DistribLattice (WithTop α) where le_sup_inf x y z := by cases x <;> cases y <;> cases z <;> simp [← coe_inf, ← coe_sup] simpa [← coe_inf, ← coe_sup] using le_sup_inf instance decidableEq [DecidableEq α] : DecidableEq (WithTop α) := inferInstanceAs <| DecidableEq (Option α) instance decidableLE [LE α] [DecidableLE α] : DecidableLE (WithTop α) | _, ⊤ => isTrue <| by simp | ⊤, (a : α) => isFalse <| by simp | (a : α), (b : α) => decidable_of_iff' _ coe_le_coe instance decidableLT [LT α] [DecidableLT α] : DecidableLT (WithTop α) | ⊤, _ => isFalse <| by simp | (a : α), ⊤ => isTrue <| by simp | (a : α), (b : α) => decidable_of_iff' _ coe_lt_coe instance isTotal_le [LE α] [IsTotal α (· ≤ ·)] : IsTotal (WithTop α) (· ≤ ·) where total x y := by cases x <;> cases y <;> simp; simpa using IsTotal.total .. section LinearOrder variable [LinearOrder α] {x y : WithTop α} instance linearOrder [LinearOrder α] : LinearOrder (WithTop α) := Lattice.toLinearOrder _ @[simp, norm_cast] lemma coe_min (a b : α) : ↑(min a b) = min (a : WithTop α) b := rfl @[simp, norm_cast] lemma coe_max (a b : α) : ↑(max a b) = max (a : WithTop α) b := rfl variable [DenselyOrdered α] [NoMaxOrder α] lemma le_of_forall_lt_iff_le : (∀ b : α, x < b → y ≤ b) ↔ y ≤ x := by cases x <;> cases y <;> simp [exists_gt, forall_gt_imp_ge_iff_le_of_dense] lemma ge_of_forall_gt_iff_ge : (∀ a : α, a < x → a ≤ y) ↔ x ≤ y := by cases x <;> cases y <;> simp [exists_gt, forall_lt_imp_le_iff_le_of_dense] end LinearOrder instance instWellFoundedLT [LT α] [WellFoundedLT α] : WellFoundedLT (WithTop α) := inferInstanceAs <| WellFoundedLT (WithBot αᵒᵈ)ᵒᵈ instance instWellFoundedGT [LT α] [WellFoundedGT α] : WellFoundedGT (WithTop α) := inferInstanceAs <| WellFoundedGT (WithBot αᵒᵈ)ᵒᵈ instance trichotomous.lt [Preorder α] [IsTrichotomous α (· < ·)] : IsTrichotomous (WithTop α) (· < ·) where trichotomous x y := by cases x <;> cases y <;> simp [trichotomous] instance IsWellOrder.lt [Preorder α] [IsWellOrder α (· < ·)] : IsWellOrder (WithTop α) (· < ·) where instance trichotomous.gt [Preorder α] [IsTrichotomous α (· > ·)] : IsTrichotomous (WithTop α) (· > ·) := have : IsTrichotomous α (· < ·) := .swap _; .swap _ instance IsWellOrder.gt [Preorder α] [IsWellOrder α (· > ·)] : IsWellOrder (WithTop α) (· > ·) where instance _root_.WithBot.trichotomous.lt [Preorder α] [h : IsTrichotomous α (· < ·)] : IsTrichotomous (WithBot α) (· < ·) where trichotomous x y := by cases x <;> cases y <;> simp [trichotomous] instance _root_.WithBot.isWellOrder.lt [Preorder α] [IsWellOrder α (· < ·)] : IsWellOrder (WithBot α) (· < ·) where instance _root_.WithBot.trichotomous.gt [Preorder α] [h : IsTrichotomous α (· > ·)] : IsTrichotomous (WithBot α) (· > ·) where trichotomous x y := by cases x <;> cases y <;> simp; simpa using trichotomous_of (· > ·) .. instance _root_.WithBot.isWellOrder.gt [Preorder α] [h : IsWellOrder α (· > ·)] : IsWellOrder (WithBot α) (· > ·) where trichotomous x y := by cases x <;> cases y <;> simp; simpa using trichotomous_of (· > ·) .. lemma denselyOrdered_iff [LT α] [NoMaxOrder α] : DenselyOrdered (WithTop α) ↔ DenselyOrdered α := by constructor <;> intro h <;> constructor · intro a b hab obtain ⟨c, hc⟩ := exists_between (coe_lt_coe.mpr hab) induction c with | top => simp at hc | coe c => exact ⟨c, by simpa using hc⟩ · simpa [WithTop.exists, WithTop.forall, exists_gt] using DenselyOrdered.dense instance [LT α] [DenselyOrdered α] [NoMaxOrder α] : DenselyOrdered (WithTop α) := denselyOrdered_iff.mpr inferInstance theorem lt_iff_exists_coe_btwn [Preorder α] [DenselyOrdered α] [NoMaxOrder α] {a b : WithTop α} : a < b ↔ ∃ x : α, a < ↑x ∧ ↑x < b := ⟨fun h => let ⟨_, hy⟩ := exists_between h let ⟨x, hx⟩ := lt_iff_exists_coe.1 hy.2 ⟨x, hx.1 ▸ hy⟩, fun ⟨_, hx⟩ => lt_trans hx.1 hx.2⟩ instance noBotOrder [LE α] [NoBotOrder α] [Nonempty α] : NoBotOrder (WithTop α) where exists_not_ge := fun | ⊤ => ‹Nonempty α›.elim fun a ↦ ⟨a, by simp⟩ | (a : α) => let ⟨b, hba⟩ := exists_not_ge a; ⟨b, mod_cast hba⟩ instance noMinOrder [LT α] [NoMinOrder α] [Nonempty α] : NoMinOrder (WithTop α) where exists_lt := fun | ⊤ => ‹Nonempty α›.elim fun a ↦ ⟨a, by simp⟩ | (a : α) => let ⟨b, hab⟩ := exists_lt a; ⟨b, mod_cast hab⟩ end WithTop section WithBotWithTop lemma WithBot.eq_top_iff_forall_ge [Preorder α] [Nonempty α] [NoTopOrder α] {x : WithBot (WithTop α)} : x = ⊤ ↔ ∀ a : α, a ≤ x := by refine ⟨by simp_all, fun H ↦ ?_⟩ induction x · simp at H · simpa [WithTop.eq_top_iff_forall_ge] using H end WithBotWithTop /-! ### `(WithBot α)ᵒᵈ ≃ WithTop αᵒᵈ`, `(WithTop α)ᵒᵈ ≃ WithBot αᵒᵈ` -/ open OrderDual namespace WithBot @[simp] lemma toDual_symm_apply (a : WithTop αᵒᵈ) : WithBot.toDual.symm a = WithTop.ofDual a := rfl @[simp] lemma ofDual_symm_apply (a : WithTop α) : WithBot.ofDual.symm a = WithTop.toDual a := rfl @[simp] lemma toDual_apply_bot : WithBot.toDual (⊥ : WithBot α) = ⊤ := rfl @[simp] lemma ofDual_apply_bot : WithBot.ofDual (⊥ : WithBot α) = ⊤ := rfl @[simp] lemma toDual_apply_coe (a : α) : WithBot.toDual (a : WithBot α) = toDual a := rfl @[simp] lemma ofDual_apply_coe (a : αᵒᵈ) : WithBot.ofDual (a : WithBot αᵒᵈ) = ofDual a := rfl lemma map_toDual (f : αᵒᵈ → βᵒᵈ) (a : WithTop α) : WithBot.map f (WithTop.toDual a) = a.map (toDual ∘ f) := rfl lemma map_ofDual (f : α → β) (a : WithTop αᵒᵈ) : WithBot.map f (WithTop.ofDual a) = a.map (ofDual ∘ f) := rfl lemma toDual_map (f : α → β) (a : WithBot α) : WithBot.toDual (WithBot.map f a) = map (toDual ∘ f ∘ ofDual) (WithBot.toDual a) := rfl lemma ofDual_map (f : αᵒᵈ → βᵒᵈ) (a : WithBot αᵒᵈ) : WithBot.ofDual (WithBot.map f a) = map (ofDual ∘ f ∘ toDual) (WithBot.ofDual a) := rfl end WithBot section LE variable [LE α] lemma WithBot.toDual_le_iff {x : WithBot α} {y : WithTop αᵒᵈ} : x.toDual ≤ y ↔ WithTop.ofDual y ≤ x := by cases x <;> cases y <;> simp [toDual_le] lemma WithBot.le_toDual_iff {x : WithTop αᵒᵈ} {y : WithBot α} : x ≤ WithBot.toDual y ↔ y ≤ WithTop.ofDual x := by cases x <;> cases y <;> simp [le_toDual] @[simp] lemma WithBot.toDual_le_toDual_iff {x y : WithBot α} : x.toDual ≤ y.toDual ↔ y ≤ x := by cases x <;> cases y <;> simp lemma WithBot.ofDual_le_iff {x : WithBot αᵒᵈ} {y : WithTop α} : WithBot.ofDual x ≤ y ↔ y.toDual ≤ x := by cases x <;> cases y <;> simp [toDual_le] lemma WithBot.le_ofDual_iff {x : WithTop α} {y : WithBot αᵒᵈ} : x ≤ WithBot.ofDual y ↔ y ≤ x.toDual := by cases x <;> cases y <;> simp [le_toDual] @[simp] lemma WithBot.ofDual_le_ofDual_iff {x y : WithBot αᵒᵈ} : WithBot.ofDual x ≤ WithBot.ofDual y ↔ y ≤ x := by cases x <;> cases y <;> simp lemma WithTop.toDual_le_iff {x : WithTop α} {y : WithBot αᵒᵈ} : x.toDual ≤ y ↔ WithBot.ofDual y ≤ x := by cases x <;> cases y <;> simp [toDual_le] lemma WithTop.le_toDual_iff {x : WithBot αᵒᵈ} {y : WithTop α} : x ≤ WithTop.toDual y ↔ y ≤ WithBot.ofDual x := by cases x <;> cases y <;> simp [le_toDual] @[simp] lemma WithTop.toDual_le_toDual_iff {x y : WithTop α} : x.toDual ≤ y.toDual ↔ y ≤ x := by cases x <;> cases y <;> simp [le_toDual] lemma WithTop.ofDual_le_iff {x : WithTop αᵒᵈ} {y : WithBot α} : WithTop.ofDual x ≤ y ↔ y.toDual ≤ x := by cases x <;> cases y <;> simp [toDual_le] lemma WithTop.le_ofDual_iff {x : WithBot α} {y : WithTop αᵒᵈ} : x ≤ WithTop.ofDual y ↔ y ≤ x.toDual := by cases x <;> cases y <;> simp [le_toDual] @[simp] lemma WithTop.ofDual_le_ofDual_iff {x y : WithTop αᵒᵈ} : WithTop.ofDual x ≤ WithTop.ofDual y ↔ y ≤ x := by cases x <;> cases y <;> simp end LE section LT variable [LT α] lemma WithBot.toDual_lt_iff {x : WithBot α} {y : WithTop αᵒᵈ} : x.toDual < y ↔ WithTop.ofDual y < x := by cases x <;> cases y <;> simp [toDual_lt] lemma WithBot.lt_toDual_iff {x : WithTop αᵒᵈ} {y : WithBot α} : x < y.toDual ↔ y < WithTop.ofDual x := by cases x <;> cases y <;> simp [lt_toDual] @[simp] lemma WithBot.toDual_lt_toDual_iff {x y : WithBot α} : x.toDual < y.toDual ↔ y < x := by cases x <;> cases y <;> simp lemma WithBot.ofDual_lt_iff {x : WithBot αᵒᵈ} {y : WithTop α} : WithBot.ofDual x < y ↔ y.toDual < x := by cases x <;> cases y <;> simp [toDual_lt] lemma WithBot.lt_ofDual_iff {x : WithTop α} {y : WithBot αᵒᵈ} : x < WithBot.ofDual y ↔ y < x.toDual := by cases x <;> cases y <;> simp [lt_toDual] @[simp] lemma WithBot.ofDual_lt_ofDual_iff {x y : WithBot αᵒᵈ} : WithBot.ofDual x < WithBot.ofDual y ↔ y < x := by cases x <;> cases y <;> simp lemma WithTop.toDual_lt_iff {x : WithTop α} {y : WithBot αᵒᵈ} : WithTop.toDual x < y ↔ WithBot.ofDual y < x := by cases x <;> cases y <;> simp [toDual_lt] lemma WithTop.lt_toDual_iff {x : WithBot αᵒᵈ} {y : WithTop α} : x < WithTop.toDual y ↔ y < WithBot.ofDual x := by cases x <;> cases y <;> simp [lt_toDual] @[simp] lemma WithTop.toDual_lt_toDual_iff {x y : WithTop α} : WithTop.toDual x < WithTop.toDual y ↔ y < x := by cases x <;> cases y <;> simp lemma WithTop.ofDual_lt_iff {x : WithTop αᵒᵈ} {y : WithBot α} : WithTop.ofDual x < y ↔ WithBot.toDual y < x := by cases x <;> cases y <;> simp [toDual_lt] lemma WithTop.lt_ofDual_iff {x : WithBot α} {y : WithTop αᵒᵈ} : x < WithTop.ofDual y ↔ y < WithBot.toDual x := by cases x <;> cases y <;> simp [lt_toDual] @[simp] lemma WithTop.ofDual_lt_ofDual_iff {x y : WithTop αᵒᵈ} : WithTop.ofDual x < WithTop.ofDual y ↔ y < x := by cases x <;> cases y <;> simp end LT
.lake/packages/mathlib/Mathlib/Order/WellQuasiOrder.lean
import Mathlib.Data.Fintype.Card import Mathlib.Data.Set.Finite.Basic import Mathlib.Order.Antichain import Mathlib.Order.OrderIsoNat /-! # Well quasi-orders A well quasi-order (WQO) is a relation such that any infinite sequence contains an infinite subsequence of related elements. For a preorder, this is equivalent to having a well-founded order with no infinite antichains. ## Main definitions * `WellQuasiOrdered`: a predicate for WQO unbundled relations * `WellQuasiOrderedLE`: a typeclass for a bundled WQO `≤` relation ## Tags wqo, pwo, well quasi-order, partial well order, dickson order -/ variable {α β : Type*} {r : α → α → Prop} {s : β → β → Prop} /-- A well quasi-order or WQO is a relation such that any infinite sequence contains an infinite monotonic subsequence, or equivalently, two elements `f m` and `f n` with `m < n` and `r (f m) (f n)`. For a preorder, this is equivalent to having a well-founded order with no infinite antichains. Despite the nomenclature, we don't require the relation to be preordered. Moreover, a well quasi-order will not in general be a well-order. -/ def WellQuasiOrdered (r : α → α → Prop) : Prop := ∀ f : ℕ → α, ∃ m n : ℕ, m < n ∧ r (f m) (f n) theorem wellQuasiOrdered_of_isEmpty [IsEmpty α] (r : α → α → Prop) : WellQuasiOrdered r := fun f ↦ isEmptyElim (f 0) theorem IsAntichain.finite_of_wellQuasiOrdered {s : Set α} (hs : IsAntichain r s) (hr : WellQuasiOrdered r) : s.Finite := by refine Set.not_infinite.1 fun hi => ?_ obtain ⟨m, n, hmn, h⟩ := hr fun n => hi.natEmbedding _ n exact hmn.ne ((hi.natEmbedding _).injective <| Subtype.val_injective <| hs.eq (hi.natEmbedding _ m).2 (hi.natEmbedding _ n).2 h) theorem Finite.wellQuasiOrdered (r : α → α → Prop) [Finite α] [IsRefl α r] : WellQuasiOrdered r := by intro f obtain ⟨m, n, h, hf⟩ := Set.finite_univ.exists_lt_map_eq_of_forall_mem (f := f) fun _ ↦ Set.mem_univ _ exact ⟨m, n, h, hf ▸ refl _⟩ theorem WellQuasiOrdered.exists_monotone_subseq [IsPreorder α r] (h : WellQuasiOrdered r) (f : ℕ → α) : ∃ g : ℕ ↪o ℕ, ∀ m n, m ≤ n → r (f (g m)) (f (g n)) := by obtain ⟨g, h1 | h2⟩ := exists_increasing_or_nonincreasing_subseq r f · refine ⟨g, fun m n hle => ?_⟩ obtain hlt | rfl := hle.lt_or_eq exacts [h1 m n hlt, refl_of r _] · obtain ⟨m, n, hlt, hle⟩ := h (f ∘ g) cases h2 m n hlt hle theorem wellQuasiOrdered_iff_exists_monotone_subseq [IsPreorder α r] : WellQuasiOrdered r ↔ ∀ f : ℕ → α, ∃ g : ℕ ↪o ℕ, ∀ m n : ℕ, m ≤ n → r (f (g m)) (f (g n)) := by constructor <;> intro h f · exact h.exists_monotone_subseq f · obtain ⟨g, gmon⟩ := h f exact ⟨_, _, g.strictMono Nat.zero_lt_one, gmon _ _ (Nat.zero_le 1)⟩ theorem WellQuasiOrdered.prod [IsPreorder α r] (hr : WellQuasiOrdered r) (hs : WellQuasiOrdered s) : WellQuasiOrdered fun a b : α × β ↦ r a.1 b.1 ∧ s a.2 b.2 := by intro f obtain ⟨g, h₁⟩ := hr.exists_monotone_subseq (Prod.fst ∘ f) obtain ⟨m, n, h, hf⟩ := hs (Prod.snd ∘ f ∘ g) exact ⟨g m, g n, g.strictMono h, h₁ _ _ h.le, hf⟩ theorem RelIso.wellQuasiOrdered_iff {α β} {r : α → α → Prop} {s : β → β → Prop} (f : r ≃r s) : WellQuasiOrdered r ↔ WellQuasiOrdered s := by apply (Equiv.arrowCongr (.refl ℕ) f).forall_congr congr! with g a b simp [f.map_rel_iff] /-- A typeclass for an order with a well-quasi-ordered `≤` relation. Note that this is unlike `WellFoundedLT`, which instead takes a `<` relation. -/ @[mk_iff wellQuasiOrderedLE_def] class WellQuasiOrderedLE (α : Type*) [LE α] where wqo : @WellQuasiOrdered α (· ≤ ·) theorem wellQuasiOrdered_le [LE α] [h : WellQuasiOrderedLE α] : @WellQuasiOrdered α (· ≤ ·) := h.wqo section Preorder variable [Preorder α] -- This was previously a global instance, -- but it doesn't appear to be used and has been implicated in slow typeclass resolutions. lemma Finite.to_wellQuasiOrderedLE [Finite α] : WellQuasiOrderedLE α where wqo := Finite.wellQuasiOrdered _ instance (priority := 100) WellQuasiOrderedLE.to_wellFoundedLT [WellQuasiOrderedLE α] : WellFoundedLT α := by rw [WellFoundedLT, isWellFounded_iff, RelEmbedding.wellFounded_iff_isEmpty] refine ⟨fun f ↦ ?_⟩ obtain ⟨a, b, h, hf⟩ := wellQuasiOrdered_le f exact (f.map_rel_iff.2 h).not_ge hf theorem WellQuasiOrdered.wellFounded {α : Type*} {r : α → α → Prop} [IsPreorder α r] (h : WellQuasiOrdered r) : WellFounded fun a b ↦ r a b ∧ ¬ r b a := by let _ : Preorder α := { le := r le_refl := refl_of r le_trans := fun _ _ _ => trans_of r } have : WellQuasiOrderedLE α := ⟨h⟩ exact wellFounded_lt theorem WellQuasiOrderedLE.finite_of_isAntichain [WellQuasiOrderedLE α] {s : Set α} (h : IsAntichain (· ≤ ·) s) : s.Finite := h.finite_of_wellQuasiOrdered wellQuasiOrdered_le /-- A preorder is well quasi-ordered iff it's well-founded and has no infinite antichains. -/ theorem wellQuasiOrderedLE_iff : WellQuasiOrderedLE α ↔ WellFoundedLT α ∧ ∀ s : Set α, IsAntichain (· ≤ ·) s → s.Finite := by refine ⟨fun h ↦ ⟨h.to_wellFoundedLT, fun s ↦ h.finite_of_isAntichain⟩, fun ⟨hwf, hc⟩ ↦ ⟨fun f ↦ ?_⟩⟩ obtain ⟨g, h1 | h2⟩ := exists_increasing_or_nonincreasing_subseq (· > ·) f · exfalso apply RelEmbedding.not_wellFounded _ hwf.wf exact (RelEmbedding.ofMonotone _ h1).swap · contrapose! hc refine ⟨Set.range (f ∘ g), ?_, ?_⟩ · rintro _ ⟨m, rfl⟩ _ ⟨n, rfl⟩ _ hf obtain h | rfl | h := lt_trichotomy m n · exact hc _ _ (g.strictMono h) hf · contradiction · exact h2 _ _ h (lt_of_le_not_ge hf (hc _ _ (g.strictMono h))) · refine Set.infinite_range_of_injective fun m n (hf : f (g m) = f (g n)) ↦ ?_ obtain h | rfl | h := lt_trichotomy m n <;> (first | rfl | cases (hf ▸ hc _ _ (g.strictMono h)) le_rfl) instance [WellQuasiOrderedLE α] [Preorder β] [WellQuasiOrderedLE β] : WellQuasiOrderedLE (α × β) := ⟨wellQuasiOrdered_le.prod wellQuasiOrdered_le⟩ end Preorder section LinearOrder variable [LinearOrder α] /-- A linear WQO is the same thing as a well-order. -/ theorem wellQuasiOrderedLE_iff_wellFoundedLT : WellQuasiOrderedLE α ↔ WellFoundedLT α := by rw [wellQuasiOrderedLE_iff, and_iff_left_iff_imp] exact fun _ s hs ↦ hs.subsingleton.finite end LinearOrder
.lake/packages/mathlib/Mathlib/Order/KrullDimension.lean
import Mathlib.Algebra.Order.Group.Int import Mathlib.Algebra.Order.SuccPred.WithBot import Mathlib.Data.ENat.Lattice import Mathlib.Order.Atoms import Mathlib.Order.RelSeries import Mathlib.Tactic.FinCases /-! # Krull dimension of a preordered set and height of an element If `α` is a preordered set, then `krullDim α : WithBot ℕ∞` is defined to be `sup {n | a₀ < a₁ < ... < aₙ}`. In case that `α` is empty, then its Krull dimension is defined to be negative infinity; if the length of all series `a₀ < a₁ < ... < aₙ` is unbounded, then its Krull dimension is defined to be positive infinity. For `a : α`, its height (in `ℕ∞`) is defined to be `sup {n | a₀ < a₁ < ... < aₙ ≤ a}`, while its coheight is defined to be `sup {n | a ≤ a₀ < a₁ < ... < aₙ}` . ## Main results * The Krull dimension is the same as that of the dual order (`krullDim_orderDual`). * The Krull dimension is the supremum of the heights of the elements (`krullDim_eq_iSup_height`), or their coheights (`krullDim_eq_iSup_coheight`), or their sums of height and coheight (`krullDim_eq_iSup_height_add_coheight_of_nonempty`) * The height in the dual order equals the coheight, and vice versa. * The height is monotone (`height_mono`), and strictly monotone if finite (`height_strictMono`). * The coheight is antitone (`coheight_anti`), and strictly antitone if finite (`coheight_strictAnti`). * The height is the supremum of the successor of the height of all smaller elements (`height_eq_iSup_lt_height`). * The elements of height zero are the minimal elements (`height_eq_zero`), and the elements of height `n` are minimal among those of height `≥ n` (`height_eq_coe_iff_minimal_le_height`). * Concrete calculations for the height, coheight and Krull dimension in `ℕ`, `ℤ`, `WithTop`, `WithBot` and `ℕ∞`. ## Design notes Krull dimensions are defined to take value in `WithBot ℕ∞` so that `(-∞) + (+∞)` is also negative infinity. This is because we want Krull dimensions to be additive with respect to product of varieties so that `-∞` being the Krull dimension of empty variety is equal to sum of `-∞` and the Krull dimension of any other varieties. We could generalize the notion of Krull dimension to an arbitrary binary relation; many results in this file would generalize as well. But we don't think it would be useful, so we only define Krull dimension of a preorder. -/ assert_not_exists Field namespace Order section definitions /-- The **Krull dimension** of a preorder `α` is the supremum of the rightmost index of all relation series of `α` ordered by `<`. If there is no series `a₀ < a₁ < ... < aₙ` in `α`, then its Krull dimension is defined to be negative infinity; if the length of all series `a₀ < a₁ < ... < aₙ` is unbounded, its Krull dimension is defined to be positive infinity. -/ noncomputable def krullDim (α : Type*) [Preorder α] : WithBot ℕ∞ := ⨆ (p : LTSeries α), p.length /-- The **height** of an element `a` in a preorder `α` is the supremum of the rightmost index of all relation series of `α` ordered by `<` and ending below or at `a`. In other words, it is the largest `n` such that there's a series `a₀ < a₁ < ... < aₙ = a` (or `∞` if there is no largest `n`). -/ noncomputable def height {α : Type*} [Preorder α] (a : α) : ℕ∞ := ⨆ (p : LTSeries α) (_ : p.last ≤ a), p.length /-- The **coheight** of an element `a` in a preorder `α` is the supremum of the rightmost index of all relation series of `α` ordered by `<` and beginning with `a`. In other words, it is the largest `n` such that there's a series `a = a₀ < a₁ < ... < aₙ` (or `∞` if there is no largest `n`). The definition of `coheight` is via the `height` in the dual order, in order to easily transfer theorems between `height` and `coheight`. See `coheight_eq` for the definition with a series ordered by `<` and beginning with `a`. -/ noncomputable def coheight {α : Type*} [Preorder α] (a : α) : ℕ∞ := height (α := αᵒᵈ) a end definitions /-! ## Height -/ section height variable {α β : Type*} variable [Preorder α] [Preorder β] @[simp] lemma height_toDual (x : α) : height (OrderDual.toDual x) = coheight x := rfl @[simp] lemma height_ofDual (x : αᵒᵈ) : height (OrderDual.ofDual x) = coheight x := rfl @[simp] lemma coheight_toDual (x : α) : coheight (OrderDual.toDual x) = height x := rfl @[simp] lemma coheight_ofDual (x : αᵒᵈ) : coheight (OrderDual.ofDual x) = height x := rfl /-- The **coheight** of an element `a` in a preorder `α` is the supremum of the rightmost index of all relation series of `α` ordered by `<` and beginning with `a`. This is not the definition of `coheight`. The definition of `coheight` is via the `height` in the dual order, in order to easily transfer theorems between `height` and `coheight`. -/ lemma coheight_eq (a : α) : coheight a = ⨆ (p : LTSeries α) (_ : a ≤ p.head), (p.length : ℕ∞) := by apply Equiv.iSup_congr ⟨RelSeries.reverse, RelSeries.reverse, fun _ ↦ RelSeries.reverse_reverse _, fun _ ↦ RelSeries.reverse_reverse _⟩ congr! 1 lemma height_le_iff {a : α} {n : ℕ∞} : height a ≤ n ↔ ∀ ⦃p : LTSeries α⦄, p.last ≤ a → p.length ≤ n := by rw [height, iSup₂_le_iff] lemma coheight_le_iff {a : α} {n : ℕ∞} : coheight a ≤ n ↔ ∀ ⦃p : LTSeries α⦄, a ≤ p.head → p.length ≤ n := by rw [coheight_eq, iSup₂_le_iff] lemma height_le {a : α} {n : ℕ∞} (h : ∀ (p : LTSeries α), p.last = a → p.length ≤ n) : height a ≤ n := by apply height_le_iff.mpr intro p hlast wlog hlenpos : p.length ≠ 0 · simp_all -- We replace the last element in the series with `a` let p' := p.eraseLast.snoc a (lt_of_lt_of_le (p.eraseLast_last_rel_last (by simp_all)) hlast) rw [show p.length = p'.length by simp [p']; cutsat] apply h simp [p'] /-- Variant of `height_le_iff` ranging only over those series that end exactly on `a`. -/ lemma height_le_iff' {a : α} {n : ℕ∞} : height a ≤ n ↔ ∀ ⦃p : LTSeries α⦄, p.last = a → p.length ≤ n := by constructor · rw [height_le_iff] exact fun h p hlast => h (le_of_eq hlast) · exact height_le /-- Alternative definition of height, with the supremum ranging only over those series that end at `a`. -/ lemma height_eq_iSup_last_eq (a : α) : height a = ⨆ (p : LTSeries α) (_ : p.last = a), ↑(p.length) := by apply eq_of_forall_ge_iff intro n rw [height_le_iff', iSup₂_le_iff] /-- Alternative definition of coheight, with the supremum only ranging over those series that begin at `a`. -/ lemma coheight_eq_iSup_head_eq (a : α) : coheight a = ⨆ (p : LTSeries α) (_ : p.head = a), ↑(p.length) := by change height (α := αᵒᵈ) a = ⨆ (p : LTSeries α) (_ : p.head = a), ↑(p.length) rw [height_eq_iSup_last_eq] apply Equiv.iSup_congr ⟨RelSeries.reverse, RelSeries.reverse, fun _ ↦ RelSeries.reverse_reverse _, fun _ ↦ RelSeries.reverse_reverse _⟩ simp /-- Variant of `coheight_le_iff` ranging only over those series that begin exactly on `a`. -/ lemma coheight_le_iff' {a : α} {n : ℕ∞} : coheight a ≤ n ↔ ∀ ⦃p : LTSeries α⦄, p.head = a → p.length ≤ n := by rw [coheight_eq_iSup_head_eq, iSup₂_le_iff] lemma coheight_le {a : α} {n : ℕ∞} (h : ∀ (p : LTSeries α), p.head = a → p.length ≤ n) : coheight a ≤ n := coheight_le_iff'.mpr h lemma length_le_height {p : LTSeries α} {x : α} (hlast : p.last ≤ x) : p.length ≤ height x := by by_cases hlen0 : p.length ≠ 0 · let p' := p.eraseLast.snoc x (by apply lt_of_lt_of_le · apply p.step ⟨p.length - 1, by cutsat⟩ · convert hlast simp only [Fin.succ_mk, RelSeries.last, Fin.last] congr; cutsat) suffices p'.length ≤ height x by simp [p'] at this convert this norm_cast cutsat refine le_iSup₂_of_le p' ?_ le_rfl simp [p'] · simp_all lemma length_le_coheight {x : α} {p : LTSeries α} (hhead : x ≤ p.head) : p.length ≤ coheight x := length_le_height (α := αᵒᵈ) (p := p.reverse) (by simpa) /-- The height of the last element in a series is larger or equal to the length of the series. -/ lemma length_le_height_last {p : LTSeries α} : p.length ≤ height p.last := length_le_height le_rfl /-- The coheight of the first element in a series is larger or equal to the length of the series. -/ lemma length_le_coheight_head {p : LTSeries α} : p.length ≤ coheight p.head := length_le_coheight le_rfl /-- The height of an element in a series is larger or equal to its index in the series. -/ lemma index_le_height (p : LTSeries α) (i : Fin (p.length + 1)) : i ≤ height (p i) := length_le_height_last (p := p.take i) /-- The coheight of an element in a series is larger or equal to its reverse index in the series. -/ lemma rev_index_le_coheight (p : LTSeries α) (i : Fin (p.length + 1)) : i.rev ≤ coheight (p i) := by simpa using index_le_height (α := αᵒᵈ) p.reverse i.rev /-- In a maximally long series, i.e one as long as the height of the last element, the height of each element is its index in the series. -/ lemma height_eq_index_of_length_eq_height_last {p : LTSeries α} (h : p.length = height p.last) (i : Fin (p.length + 1)) : height (p i) = i := by refine le_antisymm (height_le ?_) (index_le_height p i) intro p' hp' have hp'' := length_le_height_last (p := p'.smash (p.drop i) (by simpa)) simp [← h] at hp''; clear h norm_cast at * cutsat /-- In a maximally long series, i.e one as long as the coheight of the first element, the coheight of each element is its reverse index in the series. -/ lemma coheight_eq_index_of_length_eq_head_coheight {p : LTSeries α} (h : p.length = coheight p.head) (i : Fin (p.length + 1)) : coheight (p i) = i.rev := by simpa using height_eq_index_of_length_eq_height_last (α := αᵒᵈ) (p := p.reverse) (by simpa) i.rev @[gcongr] lemma height_mono : Monotone (α := α) height := fun _ _ hab ↦ biSup_mono (fun _ hla => hla.trans hab) @[gcongr] lemma coheight_anti : Antitone (α := α) coheight := (height_mono (α := αᵒᵈ)).dual_left private lemma height_add_const (a : α) (n : ℕ∞) : height a + n = ⨆ (p : LTSeries α) (_ : p.last = a), p.length + n := by have hne : Nonempty { p : LTSeries α // p.last = a } := ⟨RelSeries.singleton _ a, rfl⟩ rw [height_eq_iSup_last_eq, iSup_subtype', iSup_subtype', ENat.iSup_add] /- For elements of finite height, `height` is strictly monotone. -/ @[gcongr] lemma height_strictMono {x y : α} (hxy : x < y) (hfin : height x < ⊤) : height x < height y := by rw [← ENat.add_one_le_iff hfin.ne, height_add_const, iSup₂_le_iff] intro p hlast have := length_le_height_last (p := p.snoc y (by simp [*])) simpa using this lemma height_add_one_le {a b : α} (hab : a < b) : height a + 1 ≤ height b := by cases hfin : height a with | top => have : ⊤ ≤ height b := by rw [← hfin] gcongr simp [this] | coe n => apply Order.add_one_le_of_lt rw [← hfin] gcongr simp [hfin] /- For elements of finite height, `coheight` is strictly antitone. -/ @[gcongr] lemma coheight_strictAnti {x y : α} (hyx : y < x) (hfin : coheight x < ⊤) : coheight x < coheight y := height_strictMono (α := αᵒᵈ) hyx hfin lemma coheight_add_one_le {a b : α} (hab : b < a) : coheight a + 1 ≤ coheight b := by cases hfin : coheight a with | top => have : ⊤ ≤ coheight b := by rw [← hfin] gcongr simp [this] | coe n => apply Order.add_one_le_of_lt rw [← hfin] gcongr simp [hfin] lemma height_le_height_apply_of_strictMono (f : α → β) (hf : StrictMono f) (x : α) : height x ≤ height (f x) := by simp only [height_eq_iSup_last_eq] apply iSup₂_le intro p hlast apply le_iSup₂_of_le (p.map f hf) (by simp [hlast]) (by simp) lemma coheight_le_coheight_apply_of_strictMono (f : α → β) (hf : StrictMono f) (x : α) : coheight x ≤ coheight (f x) := by apply height_le_height_apply_of_strictMono (α := αᵒᵈ) exact fun _ _ h ↦ hf h @[simp] lemma height_orderIso (f : α ≃o β) (x : α) : height (f x) = height x := by apply le_antisymm · simpa using height_le_height_apply_of_strictMono _ f.symm.strictMono (f x) · exact height_le_height_apply_of_strictMono _ f.strictMono x lemma coheight_orderIso (f : α ≃o β) (x : α) : coheight (f x) = coheight x := height_orderIso (α := αᵒᵈ) f.dual x private lemma exists_eq_iSup_of_iSup_eq_coe {α : Type*} [Nonempty α] {f : α → ℕ∞} {n : ℕ} (h : (⨆ x, f x) = n) : ∃ x, f x = n := by obtain ⟨x, hx⟩ := ENat.sSup_mem_of_nonempty_of_lt_top (h ▸ ENat.coe_lt_top _) use x simpa [hx] using h /-- There exist a series ending in a element for any length up to the element’s height. -/ lemma exists_series_of_le_height (a : α) {n : ℕ} (h : n ≤ height a) : ∃ p : LTSeries α, p.last = a ∧ p.length = n := by have hne : Nonempty { p : LTSeries α // p.last = a } := ⟨RelSeries.singleton _ a, rfl⟩ cases ha : height a with | top => clear h rw [height_eq_iSup_last_eq, iSup_subtype', ENat.iSup_coe_eq_top, bddAbove_def] at ha contrapose! ha use n rintro m ⟨⟨p, rfl⟩, hp⟩ simp only at hp by_contra! hnm apply ha (p.drop ⟨m-n, by cutsat⟩) (by simp) (by simp; cutsat) | coe m => rw [ha, Nat.cast_le] at h rw [height_eq_iSup_last_eq, iSup_subtype'] at ha obtain ⟨⟨p, hlast⟩, hlen⟩ := exists_eq_iSup_of_iSup_eq_coe ha simp only [Nat.cast_inj] at hlen use p.drop ⟨m-n, by cutsat⟩ constructor · simp [hlast] · simp [hlen]; cutsat lemma exists_series_of_le_coheight (a : α) {n : ℕ} (h : n ≤ coheight a) : ∃ p : LTSeries α, p.head = a ∧ p.length = n := by obtain ⟨p, hp, hl⟩ := exists_series_of_le_height (α := αᵒᵈ) a h exact ⟨p.reverse, by simpa, by simpa⟩ /-- For an element of finite height there exists a series ending in that element of that height. -/ lemma exists_series_of_height_eq_coe (a : α) {n : ℕ} (h : height a = n) : ∃ p : LTSeries α, p.last = a ∧ p.length = n := exists_series_of_le_height a (le_of_eq h.symm) lemma exists_series_of_coheight_eq_coe (a : α) {n : ℕ} (h : coheight a = n) : ∃ p : LTSeries α, p.head = a ∧ p.length = n := exists_series_of_le_coheight a (le_of_eq h.symm) /-- Another characterization of height, based on the supremum of the heights of elements below. -/ lemma height_eq_iSup_lt_height (x : α) : height x = ⨆ y < x, height y + 1 := by apply le_antisymm · apply height_le intro p hp cases hlen : p.length with | zero => simp | succ n => apply le_iSup_of_le p.eraseLast.last apply le_iSup_of_le (by rw [← hp]; exact p.eraseLast_last_rel_last (by cutsat)) rw [height_add_const] apply le_iSup₂_of_le p.eraseLast (by rfl) (by simp [hlen]) · apply iSup₂_le; intro y hyx rw [height_add_const] apply iSup₂_le; intro p hp apply le_iSup₂_of_le (p.snoc x (hp ▸ hyx)) (by simp) (by simp) /-- Another characterization of coheight, based on the supremum of the coheights of elements above. -/ lemma coheight_eq_iSup_gt_coheight (x : α) : coheight x = ⨆ y > x, coheight y + 1 := height_eq_iSup_lt_height (α := αᵒᵈ) x lemma height_le_coe_iff {x : α} {n : ℕ} : height x ≤ n ↔ ∀ y < x, height y < n := by conv_lhs => rw [height_eq_iSup_lt_height, iSup₂_le_iff] congr! 2 with y _ cases height y · simp · norm_cast lemma coheight_le_coe_iff {x : α} {n : ℕ} : coheight x ≤ n ↔ ∀ y > x, coheight y < n := height_le_coe_iff (α := αᵒᵈ) /-- The height of an element is infinite iff there exist series of arbitrary length ending in that element. -/ lemma height_eq_top_iff {x : α} : height x = ⊤ ↔ ∀ n, ∃ p : LTSeries α, p.last = x ∧ p.length = n where mp h n := by apply exists_series_of_le_height x (n := n) simp [h] mpr h := by rw [height_eq_iSup_last_eq, iSup_subtype', ENat.iSup_coe_eq_top, bddAbove_def] push_neg intro n obtain ⟨p, hlast, hp⟩ := h (n + 1) exact ⟨p.length, ⟨⟨⟨p, hlast⟩, by simp [hp]⟩, by simp [hp]⟩⟩ /-- The coheight of an element is infinite iff there exist series of arbitrary length ending in that element. -/ lemma coheight_eq_top_iff {x : α} : coheight x = ⊤ ↔ ∀ n, ∃ p : LTSeries α, p.head = x ∧ p.length = n := by convert height_eq_top_iff (α := αᵒᵈ) (x := x) using 2 with n constructor <;> (intro ⟨p, hp, hl⟩; use p.reverse; constructor <;> simpa) /-- The elements of height zero are the minimal elements. -/ @[simp] lemma height_eq_zero {x : α} : height x = 0 ↔ IsMin x := by simpa [isMin_iff_forall_not_lt] using height_le_coe_iff (x := x) (n := 0) protected alias ⟨_, IsMin.height_eq_zero⟩ := height_eq_zero /-- The elements of coheight zero are the maximal elements. -/ @[simp] lemma coheight_eq_zero {x : α} : coheight x = 0 ↔ IsMax x := height_eq_zero (α := αᵒᵈ) protected alias ⟨_, IsMax.coheight_eq_zero⟩ := coheight_eq_zero lemma height_ne_zero {x : α} : height x ≠ 0 ↔ ¬ IsMin x := height_eq_zero.not @[simp] lemma height_pos {x : α} : 0 < height x ↔ ¬ IsMin x := by simp [pos_iff_ne_zero] lemma coheight_ne_zero {x : α} : coheight x ≠ 0 ↔ ¬ IsMax x := coheight_eq_zero.not @[simp] lemma coheight_pos {x : α} : 0 < coheight x ↔ ¬ IsMax x := by simp [pos_iff_ne_zero] @[simp] lemma height_bot (α : Type*) [Preorder α] [OrderBot α] : height (⊥ : α) = 0 := by simp @[simp] lemma coheight_top (α : Type*) [Preorder α] [OrderTop α] : coheight (⊤ : α) = 0 := by simp lemma coe_lt_height_iff {x : α} {n : ℕ} (hfin : height x < ⊤) : n < height x ↔ ∃ y < x, height y = n where mp h := by obtain ⟨m, hx : height x = m⟩ := Option.ne_none_iff_exists'.mp hfin.ne_top rw [hx] at h; norm_cast at h obtain ⟨p, hp, hlen⟩ := exists_series_of_height_eq_coe x hx use p ⟨n, by omega⟩ constructor · rw [← hp] apply LTSeries.strictMono simp [Fin.last]; omega · exact height_eq_index_of_length_eq_height_last (by simp [hlen, hp, hx]) ⟨n, by omega⟩ mpr := fun ⟨y, hyx, hy⟩ => hy ▸ height_strictMono hyx (lt_of_le_of_lt (height_mono hyx.le) hfin) lemma coe_lt_coheight_iff {x : α} {n : ℕ} (hfin : coheight x < ⊤) : n < coheight x ↔ ∃ y > x, coheight y = n := coe_lt_height_iff (α := αᵒᵈ) hfin lemma height_eq_coe_add_one_iff {x : α} {n : ℕ} : height x = n + 1 ↔ height x < ⊤ ∧ (∃ y < x, height y = n) ∧ (∀ y < x, height y ≤ n) := by wlog hfin : height x < ⊤ · simp_all exact ne_of_beq_false rfl simp only [hfin, true_and] trans n < height x ∧ height x ≤ n + 1 · rw [le_antisymm_iff, and_comm] simp [ENat.add_one_le_iff] · congr! 1 · exact coe_lt_height_iff hfin · simpa [hfin, ENat.lt_add_one_iff] using height_le_coe_iff (x := x) (n := n + 1) lemma coheight_eq_coe_add_one_iff {x : α} {n : ℕ} : coheight x = n + 1 ↔ coheight x < ⊤ ∧ (∃ y > x, coheight y = n) ∧ (∀ y > x, coheight y ≤ n) := height_eq_coe_add_one_iff (α := αᵒᵈ) lemma height_eq_coe_iff {x : α} {n : ℕ} : height x = n ↔ height x < ⊤ ∧ (n = 0 ∨ ∃ y < x, height y = n - 1) ∧ (∀ y < x, height y < n) := by wlog hfin : height x < ⊤ · simp_all simp only [hfin, true_and] cases n case zero => simp [isMin_iff_forall_not_lt] case succ n => simp only [Nat.cast_add, Nat.cast_one, add_eq_zero, one_ne_zero, and_false, false_or] rw [height_eq_coe_add_one_iff] simp only [hfin, true_and] congr! 3 rename_i y _ cases height y <;> simp; norm_cast; cutsat lemma coheight_eq_coe_iff {x : α} {n : ℕ} : coheight x = n ↔ coheight x < ⊤ ∧ (n = 0 ∨ ∃ y > x, coheight y = n - 1) ∧ (∀ y > x, coheight y < n) := height_eq_coe_iff (α := αᵒᵈ) /-- The elements of finite height `n` are the minimal elements among those of height `≥ n`. -/ lemma height_eq_coe_iff_minimal_le_height {a : α} {n : ℕ} : height a = n ↔ Minimal (fun y => n ≤ height y) a := by by_cases! hfin : height a < ⊤ · cases hn : n with | zero => simp | succ => simp [minimal_iff_forall_lt, height_eq_coe_add_one_iff, ENat.add_one_le_iff, coe_lt_height_iff, *] · suffices ∃ x < a, ↑n ≤ height x by simp_all [minimal_iff_forall_lt] simp only [top_le_iff, height_eq_top_iff] at hfin obtain ⟨p, rfl, hp⟩ := hfin (n + 1) use p.eraseLast.last, p.eraseLast_last_rel_last (by cutsat) simpa [hp] using length_le_height_last (p := p.eraseLast) /-- The elements of finite coheight `n` are the maximal elements among those of coheight `≥ n`. -/ lemma coheight_eq_coe_iff_maximal_le_coheight {a : α} {n : ℕ} : coheight a = n ↔ Maximal (fun y => n ≤ coheight y) a := height_eq_coe_iff_minimal_le_height (α := αᵒᵈ) lemma one_lt_height_iff {x : α} : 1 < Order.height x ↔ ∃ y z, z < y ∧ y < x := by rw [← ENat.add_one_le_iff ENat.one_ne_top, one_add_one_eq_two] refine ⟨fun h ↦ ?_, ?_⟩ · obtain ⟨p, hp, hlen⟩ := Order.exists_series_of_le_height x (n := 2) h refine ⟨p 1, p 0, p.rel_of_lt ?_, hp ▸ p.rel_of_lt ?_⟩ <;> simp [Fin.lt_def, hlen] · rintro ⟨y, z, hzy, hyx⟩ let p : LTSeries α := RelSeries.fromListIsChain [z, y, x] (List.cons_ne_nil z [y, x]) (List.IsChain.cons_cons hzy <| List.isChain_pair.mpr hyx) have : p.last = x := by simp [p, ← RelSeries.getLast_toList] exact Order.length_le_height this.le end height /-! ## Krull dimension -/ section krullDim variable {α β : Type*} variable [Preorder α] [Preorder β] lemma LTSeries.length_le_krullDim (p : LTSeries α) : p.length ≤ krullDim α := le_sSup ⟨_, rfl⟩ @[simp] lemma krullDim_eq_bot_iff : krullDim α = ⊥ ↔ IsEmpty α := by rw [eq_bot_iff, krullDim, iSup_le_iff] simp only [le_bot_iff, WithBot.natCast_ne_bot, isEmpty_iff] exact ⟨fun H x ↦ H ⟨0, fun _ ↦ x, by simp⟩, (· <| · 1)⟩ lemma krullDim_nonneg_iff : 0 ≤ krullDim α ↔ Nonempty α := by rw [← not_iff_not, not_le, not_nonempty_iff, ← krullDim_eq_bot_iff, ← WithBot.lt_coe_bot, bot_eq_zero, WithBot.coe_zero] lemma krullDim_eq_bot [IsEmpty α] : krullDim α = ⊥ := krullDim_eq_bot_iff.mpr ‹_› lemma krullDim_nonneg [Nonempty α] : 0 ≤ krullDim α := krullDim_nonneg_iff.mpr ‹_› theorem krullDim_ne_bot_iff : krullDim α ≠ ⊥ ↔ Nonempty α := by rw [ne_eq, krullDim_eq_bot_iff, not_isEmpty_iff] theorem bot_lt_krullDim_iff : ⊥ < krullDim α ↔ Nonempty α := by rw [bot_lt_iff_ne_bot, krullDim_ne_bot_iff] theorem bot_lt_krullDim [Nonempty α] : ⊥ < krullDim α := bot_lt_krullDim_iff.mpr ‹_› lemma krullDim_nonpos_iff_forall_isMax : krullDim α ≤ 0 ↔ ∀ x : α, IsMax x := by simp only [krullDim, iSup_le_iff, isMax_iff_forall_not_lt] refine ⟨fun H x y h ↦ (H ⟨1, ![x, y], fun i ↦ by obtain rfl := Subsingleton.elim i 0; simpa⟩).not_gt (by simp), ?_⟩ · rintro H ⟨_ | n, l, h⟩ · simp · cases H (l 0) (l 1) (h 0) lemma krullDim_nonpos_iff_forall_isMin : krullDim α ≤ 0 ↔ ∀ x : α, IsMin x := by simp only [krullDim_nonpos_iff_forall_isMax, IsMax, IsMin] exact forall_swap lemma krullDim_le_one_iff : krullDim α ≤ 1 ↔ ∀ x : α, IsMin x ∨ IsMax x := by rw [← not_iff_not] simp_rw [isMax_iff_forall_not_lt, isMin_iff_forall_not_lt, krullDim, iSup_le_iff] push_neg constructor · rintro ⟨⟨_ | _ | n, l, hl⟩, hl'⟩ iterate 2 · cases hl'.not_ge (by simp) exact ⟨l 1, ⟨l 0, hl 0⟩, l 2, hl 1⟩ · rintro ⟨x, ⟨y, hxy⟩, z, hzx⟩ exact ⟨⟨2, ![y, x, z], fun i ↦ by fin_cases i <;> simpa⟩, by simp⟩ lemma krullDim_le_one_iff_forall_isMax {α : Type*} [PartialOrder α] [OrderBot α] : krullDim α ≤ 1 ↔ ∀ x : α, x ≠ ⊥ → IsMax x := by simp [krullDim_le_one_iff, ← or_iff_not_imp_left] lemma krullDim_le_one_iff_forall_isMin {α : Type*} [PartialOrder α] [OrderTop α] : krullDim α ≤ 1 ↔ ∀ x : α, x ≠ ⊤ → IsMin x := by simp [krullDim_le_one_iff, ← or_iff_not_imp_right] lemma krullDim_pos_iff : 0 < krullDim α ↔ ∃ x y : α, x < y := by rw [← not_iff_not] push_neg simp_rw [← isMax_iff_forall_not_lt, ← krullDim_nonpos_iff_forall_isMax] lemma one_le_krullDim_iff : 1 ≤ krullDim α ↔ ∃ x y : α, x < y := by rw [← krullDim_pos_iff, ← Nat.cast_zero, ← WithBot.add_one_le_iff, Nat.cast_zero, zero_add] lemma krullDim_nonpos_of_subsingleton [Subsingleton α] : krullDim α ≤ 0 := by rw [krullDim_nonpos_iff_forall_isMax] exact fun x y h ↦ (Subsingleton.elim x y).ge lemma krullDim_eq_zero [Nonempty α] [Subsingleton α] : krullDim α = 0 := le_antisymm krullDim_nonpos_of_subsingleton krullDim_nonneg lemma krullDim_eq_zero_of_unique [Unique α] : krullDim α = 0 := le_antisymm krullDim_nonpos_of_subsingleton krullDim_nonneg section PartialOrder variable {α : Type*} [PartialOrder α] lemma krullDim_eq_zero_iff_of_orderBot [OrderBot α] : krullDim α = 0 ↔ Subsingleton α := ⟨fun H ↦ subsingleton_of_forall_eq ⊥ fun _ ↦ le_bot_iff.mp (krullDim_nonpos_iff_forall_isMax.mp H.le ⊥ bot_le), fun _ ↦ Order.krullDim_eq_zero⟩ lemma krullDim_pos_iff_of_orderBot [OrderBot α] : 0 < krullDim α ↔ Nontrivial α := by rw [← not_subsingleton_iff_nontrivial, ← Order.krullDim_eq_zero_iff_of_orderBot, ← ne_eq, ← lt_or_lt_iff_ne, or_iff_right] simp [Order.krullDim_nonneg] lemma krullDim_eq_zero_iff_of_orderTop [OrderTop α] : krullDim α = 0 ↔ Subsingleton α := ⟨fun H ↦ subsingleton_of_forall_eq ⊤ fun _ ↦ top_le_iff.mp (krullDim_nonpos_iff_forall_isMin.mp H.le ⊤ le_top), fun _ ↦ Order.krullDim_eq_zero⟩ lemma krullDim_pos_iff_of_orderTop [OrderTop α] : 0 < krullDim α ↔ Nontrivial α := by rw [← not_subsingleton_iff_nontrivial, ← Order.krullDim_eq_zero_iff_of_orderTop, ← ne_eq, ← lt_or_lt_iff_ne, or_iff_right] simp [Order.krullDim_nonneg] end PartialOrder lemma krullDim_eq_length_of_finiteDimensionalOrder [FiniteDimensionalOrder α] : krullDim α = (LTSeries.longestOf α).length := le_antisymm (iSup_le <| fun _ ↦ WithBot.coe_le_coe.mpr <| WithTop.coe_le_coe.mpr <| RelSeries.length_le_length_longestOf _ _) <| le_iSup (fun (i : LTSeries _) ↦ (i.length : WithBot (WithTop ℕ))) <| LTSeries.longestOf _ lemma krullDim_eq_top [InfiniteDimensionalOrder α] : krullDim α = ⊤ := le_antisymm le_top <| le_iSup_iff.mpr <| fun m hm ↦ match m, hm with | ⊥, hm => False.elim <| by haveI : Inhabited α := ⟨LTSeries.withLength _ 0 0⟩ exact not_le_of_gt (WithBot.bot_lt_coe _ : ⊥ < (0 : WithBot (WithTop ℕ))) <| hm default | some ⊤, _ => le_refl _ | some (some m), hm => by refine (not_lt_of_ge (hm (LTSeries.withLength _ (m + 1))) ?_).elim rw [WithBot.some_eq_coe, ← WithBot.coe_natCast, WithBot.coe_lt_coe, WithTop.some_eq_coe, ← WithTop.coe_natCast, WithTop.coe_lt_coe] simp lemma krullDim_eq_top_iff : krullDim α = ⊤ ↔ InfiniteDimensionalOrder α := by refine ⟨fun h ↦ ?_, fun _ ↦ krullDim_eq_top⟩ cases isEmpty_or_nonempty α · simp [krullDim_eq_bot] at h cases finiteDimensionalOrder_or_infiniteDimensionalOrder α · rw [krullDim_eq_length_of_finiteDimensionalOrder] at h cases h · infer_instance lemma le_krullDim_iff {n : ℕ} : n ≤ krullDim α ↔ ∃ l : LTSeries α, l.length = n := by cases isEmpty_or_nonempty α · simp [krullDim_eq_bot] cases finiteDimensionalOrder_or_infiniteDimensionalOrder α · rw [krullDim_eq_length_of_finiteDimensionalOrder, Nat.cast_le] constructor · exact fun H ↦ ⟨(LTSeries.longestOf α).take ⟨_, Nat.lt_succ.mpr H⟩, rfl⟩ · exact fun ⟨l, hl⟩ ↦ hl ▸ l.longestOf_is_longest · simpa [krullDim_eq_top] using SetRel.InfiniteDimensional.exists_relSeries_with_length n /-- A definition of krullDim for nonempty `α` that avoids `WithBot` -/ lemma krullDim_eq_iSup_length [Nonempty α] : krullDim α = ⨆ (p : LTSeries α), (p.length : ℕ∞) := by unfold krullDim rw [WithBot.coe_iSup (OrderTop.bddAbove _)] rfl lemma krullDim_lt_coe_iff {n : ℕ} : krullDim α < n ↔ ∀ l : LTSeries α, l.length < n := by rw [krullDim, ← WithBot.coe_natCast] rcases n with - | n · rw [ENat.coe_zero, ← bot_eq_zero, WithBot.lt_coe_bot] simp · simp [WithBot.lt_add_one_iff, WithBot.coe_natCast, Nat.lt_succ] lemma krullDim_le_of_strictMono (f : α → β) (hf : StrictMono f) : krullDim α ≤ krullDim β := iSup_le fun p ↦ le_sSup ⟨p.map f hf, rfl⟩ lemma krullDim_le_of_strictComono_and_surj (f : α → β) (hf : ∀ ⦃a b⦄, f a < f b → a < b) (hf' : Function.Surjective f) : krullDim β ≤ krullDim α := iSup_le fun p ↦ le_sSup ⟨p.comap _ hf hf', rfl⟩ lemma krullDim_eq_of_orderIso (f : α ≃o β) : krullDim α = krullDim β := le_antisymm (krullDim_le_of_strictMono _ f.strictMono) <| krullDim_le_of_strictMono _ f.symm.strictMono @[simp] lemma krullDim_orderDual : krullDim αᵒᵈ = krullDim α := le_antisymm (iSup_le fun i ↦ le_sSup ⟨i.reverse, rfl⟩) <| iSup_le fun i ↦ le_sSup ⟨i.reverse, rfl⟩ lemma height_le_krullDim (a : α) : height a ≤ krullDim α := by have : Nonempty α := ⟨a⟩ rw [krullDim_eq_iSup_length] simp only [WithBot.coe_le_coe] exact height_le fun p _ ↦ le_iSup_of_le p le_rfl lemma coheight_le_krullDim (a : α) : coheight a ≤ krullDim α := by simpa using height_le_krullDim (α := αᵒᵈ) a @[simp] lemma _root_.LTSeries.height_last_longestOf [FiniteDimensionalOrder α] : height (LTSeries.longestOf α).last = krullDim α := by refine le_antisymm (height_le_krullDim _) ?_ rw [krullDim_eq_length_of_finiteDimensionalOrder, height] norm_cast exact le_iSup_iff.mpr <| fun _ h ↦ iSup_le_iff.mp (h _) le_rfl /-- The Krull dimension is the supremum of the elements' heights. This version of the lemma assumes that `α` is nonempty. In this case, the coercion from `ℕ∞` to `WithBot ℕ∞` is on the outside of the right-hand side, which is usually more convenient. If `α` were empty, then `krullDim α = ⊥`. See `krullDim_eq_iSup_height` for the more general version, with the coercion under the supremum. -/ lemma krullDim_eq_iSup_height_of_nonempty [Nonempty α] : krullDim α = ↑(⨆ (a : α), height a) := by apply le_antisymm · apply iSup_le intro p suffices p.length ≤ ⨆ (a : α), height a from (WithBot.unbotD_le_iff fun _ => this).mp this apply le_iSup_of_le p.last (length_le_height_last (p := p)) · rw [WithBot.coe_iSup (by bddDefault)] apply iSup_le apply height_le_krullDim /-- The Krull dimension is the supremum of the elements' coheights. This version of the lemma assumes that `α` is nonempty. In this case, the coercion from `ℕ∞` to `WithBot ℕ∞` is on the outside of the right-hand side, which is usually more convenient. If `α` were empty, then `krullDim α = ⊥`. See `krullDim_eq_iSup_coheight` for the more general version, with the coercion under the supremum. -/ lemma krullDim_eq_iSup_coheight_of_nonempty [Nonempty α] : krullDim α = ↑(⨆ (a : α), coheight a) := by simpa using krullDim_eq_iSup_height_of_nonempty (α := αᵒᵈ) /-- The Krull dimension is the supremum of the elements' height plus coheight. -/ lemma krullDim_eq_iSup_height_add_coheight_of_nonempty [Nonempty α] : krullDim α = ↑(⨆ (a : α), height a + coheight a) := by apply le_antisymm · rw [krullDim_eq_iSup_height_of_nonempty, WithBot.coe_le_coe] apply ciSup_mono (by bddDefault) (by simp) · wlog hnottop : krullDim α < ⊤ · simp_all rw [krullDim_eq_iSup_length, WithBot.coe_le_coe] apply iSup_le intro a have : height a < ⊤ := WithBot.coe_lt_coe.mp (lt_of_le_of_lt (height_le_krullDim a) hnottop) have : coheight a < ⊤ := WithBot.coe_lt_coe.mp (lt_of_le_of_lt (coheight_le_krullDim a) hnottop) cases hh : height a with | top => simp_all | coe n => cases hch : coheight a with | top => simp_all | coe m => obtain ⟨p₁, hlast, hlen₁⟩ := exists_series_of_height_eq_coe a hh obtain ⟨p₂, hhead, hlen₂⟩ := exists_series_of_coheight_eq_coe a hch apply le_iSup_of_le ((p₁.smash p₂) (by simp [*])) (by simp [*]) /-- The Krull dimension is the supremum of the elements' heights. If `α` is `Nonempty`, then `krullDim_eq_iSup_height_of_nonempty`, with the coercion from `ℕ∞` to `WithBot ℕ∞` outside the supremum, can be more convenient. -/ lemma krullDim_eq_iSup_height : krullDim α = ⨆ (a : α), ↑(height a) := by cases isEmpty_or_nonempty α with | inl h => rw [krullDim_eq_bot, ciSup_of_empty] | inr h => rw [krullDim_eq_iSup_height_of_nonempty, WithBot.coe_iSup (OrderTop.bddAbove _)] /-- The Krull dimension is the supremum of the elements' coheights. If `α` is `Nonempty`, then `krullDim_eq_iSup_coheight_of_nonempty`, with the coercion from `ℕ∞` to `WithBot ℕ∞` outside the supremum, can be more convenient. -/ lemma krullDim_eq_iSup_coheight : krullDim α = ⨆ (a : α), ↑(coheight a) := by cases isEmpty_or_nonempty α with | inl h => rw [krullDim_eq_bot, ciSup_of_empty] | inr h => rw [krullDim_eq_iSup_coheight_of_nonempty, WithBot.coe_iSup (OrderTop.bddAbove _)] @[simp] -- not as useful as a simp lemma as it looks, due to the coe on the left lemma height_top_eq_krullDim [OrderTop α] : height (⊤ : α) = krullDim α := by rw [krullDim_eq_iSup_length] simp only [WithBot.coe_inj] apply le_antisymm · exact height_le fun p _ ↦ le_iSup_of_le p le_rfl · exact iSup_le fun _ => length_le_height le_top @[simp] -- not as useful as a simp lemma as it looks, due to the coe on the left lemma coheight_bot_eq_krullDim [OrderBot α] : coheight (⊥ : α) = krullDim α := by rw [← krullDim_orderDual] exact height_top_eq_krullDim (α := αᵒᵈ) lemma height_eq_krullDim_Iic (x : α) : (height x : ℕ∞) = krullDim (Set.Iic x) := by rw [← height_top_eq_krullDim, height, height, WithBot.coe_inj] apply le_antisymm · apply iSup_le; intro p; apply iSup_le; intro hp let q := LTSeries.mk p.length (fun i ↦ (⟨p.toFun i, le_trans (p.monotone (Fin.le_last _)) hp⟩ : Set.Iic x)) (fun _ _ h ↦ p.strictMono h) simp only [le_top, iSup_pos, ge_iff_le] exact le_iSup (fun p ↦ (p.length : ℕ∞)) q · apply iSup_le; intro p; apply iSup_le; intro _ have mono : StrictMono (fun (y : Set.Iic x) ↦ y.1) := fun _ _ h ↦ h rw [← LTSeries.map_length p (fun x ↦ x.1) mono, ] refine le_iSup₂ (f := fun p hp ↦ (p.length : ℕ∞)) (p.map (fun x ↦ x.1) mono) ?_ exact (p.toFun (Fin.last p.length)).2 lemma coheight_eq_krullDim_Ici {α : Type*} [Preorder α] (x : α) : (coheight x : ℕ∞) = krullDim (Set.Ici x) := by rw [coheight, ← krullDim_orderDual, Order.krullDim_eq_of_orderIso (OrderIso.refl _)] exact height_eq_krullDim_Iic _ end krullDim section finiteDimensional variable {α : Type*} [Preorder α] lemma finiteDimensionalOrder_iff_krullDim_ne_bot_and_top : FiniteDimensionalOrder α ↔ krullDim α ≠ ⊥ ∧ krullDim α ≠ ⊤ := by by_cases h : Nonempty α · simp [← not_infiniteDimensionalOrder_iff, ← krullDim_eq_top_iff] · constructor · exact (fun h1 ↦ False.elim (h (LTSeries.nonempty_of_finiteDimensionalOrder α))) · exact (fun h1 ↦ False.elim (h1.1 (krullDim_eq_bot_iff.mpr (not_nonempty_iff.mp h)))) lemma krullDim_ne_bot_of_finiteDimensionalOrder [FiniteDimensionalOrder α] : krullDim α ≠ ⊥ := (finiteDimensionalOrder_iff_krullDim_ne_bot_and_top.mp ‹_›).1 lemma krullDim_ne_top_of_finiteDimensionalOrder [FiniteDimensionalOrder α] : krullDim α ≠ ⊤ := (finiteDimensionalOrder_iff_krullDim_ne_bot_and_top.mp ‹_›).2 end finiteDimensional section typeclass /-- Typeclass for orders with krull dimension at most `n`. -/ @[mk_iff] class KrullDimLE (n : ℕ) (α : Type*) [Preorder α] : Prop where krullDim_le : krullDim α ≤ n lemma KrullDimLE.mono {n m : ℕ} (e : n ≤ m) (α : Type*) [Preorder α] [KrullDimLE n α] : KrullDimLE m α := ⟨KrullDimLE.krullDim_le (n := n).trans (Nat.cast_le.mpr e)⟩ instance {α} [Preorder α] [Subsingleton α] : KrullDimLE 0 α := ⟨krullDim_nonpos_of_subsingleton⟩ end typeclass /-! ## Concrete calculations -/ section calculations lemma krullDim_eq_one_iff_of_boundedOrder {α : Type*} [PartialOrder α] [BoundedOrder α] : krullDim α = 1 ↔ IsSimpleOrder α := by rw [le_antisymm_iff, krullDim_le_one_iff, WithBot.one_le_iff_pos, Order.krullDim_pos_iff_of_orderBot, isSimpleOrder_iff] simp only [isMin_iff_eq_bot, isMax_iff_eq_top, and_comm] @[simp] lemma krullDim_of_isSimpleOrder {α : Type*} [PartialOrder α] [BoundedOrder α] [IsSimpleOrder α] : krullDim α = 1 := krullDim_eq_one_iff_of_boundedOrder.mpr ‹_› variable {α : Type*} [Preorder α] /- These two lemmas could possibly be used to simplify the subsequent calculations, especially once the `Set.encard` api is richer. (Commented out to avoid importing modules purely for `proof_wanted`.) proof_wanted height_of_linearOrder {α : Type*} [LinearOrder α] (a : α) : height a = (Set.Iio a).encard proof_wanted coheight_of_linearOrder {α : Type*} [LinearOrder α] (a : α) : coheight a = (Set.Ioi a).encard -/ @[simp] lemma height_nat (n : ℕ) : height n = n := by induction n using Nat.strongRecOn with | ind n ih => apply le_antisymm · apply height_le_coe_iff.mpr simp +contextual only [ih, Nat.cast_lt, implies_true] · exact length_le_height_last (p := LTSeries.range n) @[simp] lemma coheight_of_noMaxOrder [NoMaxOrder α] (a : α) : coheight a = ⊤ := by obtain ⟨f, hstrictmono⟩ := Nat.exists_strictMono ↑(Set.Ioi a) apply coheight_eq_top_iff.mpr intro m use {length := m, toFun := fun i => if i = 0 then a else f i, step := ?step } case h => simp [RelSeries.head] case step => intro ⟨i, hi⟩ by_cases hzero : i = 0 · subst i exact (f 1).prop · suffices f i < f (i + 1) by simp [Fin.ext_iff, hzero, this] apply hstrictmono cutsat @[simp] lemma height_of_noMinOrder [NoMinOrder α] (a : α) : height a = ⊤ := -- Implementation note: Here it's a bit easier to define the coheight variant first coheight_of_noMaxOrder (α := αᵒᵈ) a @[simp] lemma krullDim_of_noMaxOrder [Nonempty α] [NoMaxOrder α] : krullDim α = ⊤ := by simp [krullDim_eq_iSup_coheight, coheight_of_noMaxOrder] @[simp] lemma krullDim_of_noMinOrder [Nonempty α] [NoMinOrder α] : krullDim α = ⊤ := by simp [krullDim_eq_iSup_height, height_of_noMinOrder] lemma coheight_nat (n : ℕ) : coheight n = ⊤ := coheight_of_noMaxOrder .. lemma krullDim_nat : krullDim ℕ = ⊤ := krullDim_of_noMaxOrder .. lemma height_int (n : ℤ) : height n = ⊤ := height_of_noMinOrder .. lemma coheight_int (n : ℤ) : coheight n = ⊤ := coheight_of_noMaxOrder .. lemma krullDim_int : krullDim ℤ = ⊤ := krullDim_of_noMaxOrder .. @[simp] lemma height_coe_withBot (x : α) : height (x : WithBot α) = height x + 1 := by apply le_antisymm · apply height_le intro p hlast wlog hlenpos : p.length ≠ 0 · simp_all -- essentially p' := (p.drop 1).map unbot let p' : LTSeries α := { length := p.length - 1 toFun := fun ⟨i, hi⟩ => (p ⟨i+1, by cutsat⟩).unbot (by apply ne_bot_of_gt (a := p.head) apply p.strictMono exact compare_gt_iff_gt.mp rfl) step := fun i => by simpa [WithBot.unbot_lt_iff] using p.step ⟨i + 1, by cutsat⟩ } have hlast' : p'.last = x := by simp only [p', RelSeries.last, WithBot.unbot_eq_iff, ← hlast, Fin.last] congr omega suffices p'.length ≤ height p'.last by simpa [p', hlast'] using this apply length_le_height_last · rw [height_add_const] apply iSup₂_le intro p hlast let p' := (p.map _ WithBot.coe_strictMono).cons ⊥ (by simp) apply le_iSup₂_of_le p' (by simp [p', hlast]) (by simp [p']) @[simp] lemma coheight_coe_withTop (x : α) : coheight (x : WithTop α) = coheight x + 1 := height_coe_withBot (α := αᵒᵈ) x @[simp] lemma height_coe_withTop (x : α) : height (x : WithTop α) = height x := by apply le_antisymm · apply height_le intro p hlast -- essentially p' := p.map untop let p' : LTSeries α := { length := p.length toFun := fun i => (p i).untop (by apply WithTop.lt_top_iff_ne_top.mp apply lt_of_le_of_lt · exact p.monotone (Fin.le_last _) · rw [RelSeries.last] at hlast simp [hlast]) step := fun i => by simpa [WithTop.untop_lt_iff, WithTop.coe_untop] using p.step i } have hlast' : p'.last = x := by simp only [p', RelSeries.last, WithTop.untop_eq_iff, ← hlast] suffices p'.length ≤ height p'.last by rw [hlast'] at this simpa [p'] using this apply length_le_height_last · apply height_le intro p hlast let p' := p.map _ WithTop.coe_strictMono apply le_iSup₂_of_le p' (by simp [p', hlast]) (by simp [p']) @[simp] lemma coheight_coe_withBot (x : α) : coheight (x : WithBot α) = coheight x := height_coe_withTop (α := αᵒᵈ) x @[simp] lemma krullDim_WithTop [Nonempty α] : krullDim (WithTop α) = krullDim α + 1 := by rw [← height_top_eq_krullDim, krullDim_eq_iSup_height_of_nonempty, height_eq_iSup_lt_height] norm_cast simp_rw [WithTop.lt_top_iff_ne_top] rw [ENat.iSup_add, iSup_subtype'] symm apply Equiv.withTopSubtypeNe.symm.iSup_congr simp @[simp] lemma krullDim_withBot [Nonempty α] : krullDim (WithBot α) = krullDim α + 1 := by conv_lhs => rw [← krullDim_orderDual] conv_rhs => rw [← krullDim_orderDual] exact krullDim_WithTop (α := αᵒᵈ) @[simp] lemma krullDim_enat : krullDim ℕ∞ = ⊤ := by change (krullDim (WithTop ℕ) = ⊤) simp [← WithBot.coe_top, ← WithBot.coe_one, ← WithBot.coe_add] @[simp] lemma height_enat (n : ℕ∞) : height n = n := by cases n with | top => simp only [← WithBot.coe_eq_coe, height_top_eq_krullDim, krullDim_enat, WithBot.coe_top] | coe n => exact (height_coe_withTop _).trans (height_nat _) @[simp] lemma coheight_coe_enat (n : ℕ) : coheight (n : ℕ∞) = ⊤ := by apply (coheight_coe_withTop _).trans simp only [coheight_nat, top_add] end calculations section orderHom variable {α β : Type*} [Preorder α] [PartialOrder β] variable {m : ℕ} (f : α →o β) (h : ∀ (x : β), Order.krullDim (f ⁻¹' {x}) ≤ m) include h in lemma height_le_of_krullDim_preimage_le (x : α) : Order.height x ≤ (m + 1) * Order.height (f x) + m := by generalize h' : Order.height (f x) = n cases n with | top => simp | coe n => induction n using Nat.strong_induction_on generalizing x with | h n ih => refine height_le_iff.mpr fun p hp ↦ le_of_not_gt fun h_len ↦ ?_ let i : Fin (p.length + 1) := ⟨p.length - (m + 1), Nat.sub_lt_succ p.length _⟩ suffices h'' : f (p i) < f x by obtain ⟨n', hn'⟩ : ∃ (n' : ℕ), n' = height (f (p i)) := ENat.ne_top_iff_exists.mp ((height_mono h''.le).trans_lt (h' ▸ ENat.coe_lt_top _)).ne have h_lt : n' < n := ENat.coe_lt_coe.mp (h' ▸ hn' ▸ height_strictMono h'' (hn' ▸ ENat.coe_lt_top _)) have := (length_le_height_last (p := p.take i)).trans <| ih n' h_lt (p i) hn'.symm rw [RelSeries.take_length, ENat.coe_sub, Nat.cast_add, Nat.cast_one, tsub_le_iff_right, add_assoc, add_comm _ (_ + 1), ← add_assoc, ← mul_add_one] at this refine not_lt_of_ge ?_ (h_len.trans_le this) gcongr rwa [← ENat.coe_one, ← ENat.coe_add, ENat.coe_le_coe] refine (f.monotone ((p.monotone (Fin.le_last _)).trans hp)).lt_of_not_ge fun h'' ↦ ?_ let q' : LTSeries α := p.drop i let q : LTSeries (f ⁻¹' {f x}) := ⟨q'.length, fun j ↦ ⟨q' j, le_antisymm (f.monotone (le_trans (b := q'.last) (q'.monotone (Fin.le_last _)) (p.last_drop _ ▸ hp))) (le_trans (b := f q'.head) (p.head_drop _ ▸ h'') (f.monotone (q'.monotone (Fin.zero_le _))))⟩, fun i ↦ q'.step i⟩ have := (LTSeries.length_le_krullDim q).trans (h (f x)) simp only [RelSeries.drop_length, Nat.cast_le, tsub_le_iff_right, q', i, q] at this have : p.length > m := ENat.coe_lt_coe.mp ((le_add_left le_rfl).trans_lt h_len) cutsat include h in lemma coheight_le_of_krullDim_preimage_le (x : α) : Order.coheight x ≤ (m + 1) * Order.coheight (f x) + m := by rw [Order.coheight, Order.coheight] apply height_le_of_krullDim_preimage_le (f := f.dual) exact fun x ↦ le_of_eq_of_le (krullDim_orderDual (α := f ⁻¹' {x})) (h x) include f h in lemma krullDim_le_of_krullDim_preimage_le : Order.krullDim α ≤ (m + 1) * Order.krullDim β + m := by rw [Order.krullDim_eq_iSup_height, Order.krullDim_eq_iSup_height, iSup_le_iff] refine fun x ↦ (WithBot.coe_mono (height_le_of_krullDim_preimage_le f h x)).trans ?_ push_cast gcongr exacts [right_eq_inf.mp rfl, le_iSup_iff.mpr fun b a ↦ a (f x)] /-- Another version when the `OrderHom` is unbundled -/ lemma krullDim_le_of_krullDim_preimage_le' (f : α → β) (h_mono : Monotone f) (h : ∀ (x : β), Order.krullDim (f ⁻¹' {x}) ≤ m) : Order.krullDim α ≤ (m + 1) * Order.krullDim β + m := Order.krullDim_le_of_krullDim_preimage_le ⟨f, h_mono⟩ h end orderHom end Order
.lake/packages/mathlib/Mathlib/Order/Copy.lean
import Mathlib.Order.ConditionallyCompleteLattice.Basic /-! # Tooling to make copies of lattice structures Sometimes it is useful to make a copy of a lattice structure where one replaces the data parts with provably equal definitions that have better definitional properties. -/ open Order universe u variable {α : Type u} /-- A function to create a provable equal copy of a top order with possibly different definitional equalities. -/ def OrderTop.copy {h : LE α} {h' : LE α} (c : @OrderTop α h') (top : α) (eq_top : top = (by infer_instance : Top α).top) (le_eq : ∀ x y : α, (@LE.le α h) x y ↔ x ≤ y) : @OrderTop α h := @OrderTop.mk α h { top := top } fun _ ↦ by simp [eq_top, le_eq] /-- A function to create a provable equal copy of a bottom order with possibly different definitional equalities. -/ def OrderBot.copy {h : LE α} {h' : LE α} (c : @OrderBot α h') (bot : α) (eq_bot : bot = (by infer_instance : Bot α).bot) (le_eq : ∀ x y : α, (@LE.le α h) x y ↔ x ≤ y) : @OrderBot α h := @OrderBot.mk α h { bot := bot } fun _ ↦ by simp [eq_bot, le_eq] /-- A function to create a provable equal copy of a bounded order with possibly different definitional equalities. -/ def BoundedOrder.copy {h : LE α} {h' : LE α} (c : @BoundedOrder α h') (top : α) (eq_top : top = (by infer_instance : Top α).top) (bot : α) (eq_bot : bot = (by infer_instance : Bot α).bot) (le_eq : ∀ x y : α, (@LE.le α h) x y ↔ x ≤ y) : @BoundedOrder α h := @BoundedOrder.mk α h (@OrderTop.mk α h { top := top } (fun _ ↦ by simp [eq_top, le_eq])) (@OrderBot.mk α h { bot := bot } (fun _ ↦ by simp [eq_bot, le_eq])) /-- A function to create a provable equal copy of a lattice with possibly different definitional equalities. -/ def Lattice.copy (c : Lattice α) (le : α → α → Prop) (eq_le : le = (by infer_instance : LE α).le) (sup : α → α → α) (eq_sup : sup = (by infer_instance : Max α).max) (inf : α → α → α) (eq_inf : inf = (by infer_instance : Min α).min) : Lattice α where le := le sup := sup inf := inf lt := fun a b ↦ le a b ∧ ¬ le b a le_refl := by intros; simp [eq_le] le_trans := by intro _ _ _ hab hbc; rw [eq_le] at hab hbc ⊢; exact le_trans hab hbc le_antisymm := by intro _ _ hab hba; simp_rw [eq_le] at hab hba; exact le_antisymm hab hba le_sup_left := by intros; simp [eq_le, eq_sup] le_sup_right := by intros; simp [eq_le, eq_sup] sup_le := by intro _ _ _ hac hbc; simp_rw [eq_le] at hac hbc ⊢; simp [eq_sup, hac, hbc] inf_le_left := by intros; simp [eq_le, eq_inf] inf_le_right := by intros; simp [eq_le, eq_inf] le_inf := by intro _ _ _ hac hbc; simp_rw [eq_le] at hac hbc ⊢; simp [eq_inf, hac, hbc] /-- A function to create a provable equal copy of a distributive lattice with possibly different definitional equalities. -/ def DistribLattice.copy (c : DistribLattice α) (le : α → α → Prop) (eq_le : le = (by infer_instance : LE α).le) (sup : α → α → α) (eq_sup : sup = (by infer_instance : Max α).max) (inf : α → α → α) (eq_inf : inf = (by infer_instance : Min α).min) : DistribLattice α where toLattice := Lattice.copy (@DistribLattice.toLattice α c) le eq_le sup eq_sup inf eq_inf le_sup_inf := by intros; simp [eq_le, eq_sup, eq_inf, le_sup_inf] /-- A function to create a provable equal copy of a generalised heyting algebra with possibly different definitional equalities. -/ def GeneralizedHeytingAlgebra.copy (c : GeneralizedHeytingAlgebra α) (le : α → α → Prop) (eq_le : le = (by infer_instance : LE α).le) (top : α) (eq_top : top = (by infer_instance : Top α).top) (sup : α → α → α) (eq_sup : sup = (by infer_instance : Max α).max) (inf : α → α → α) (eq_inf : inf = (by infer_instance : Min α).min) (himp : α → α → α) (eq_himp : himp = (by infer_instance : HImp α).himp) : GeneralizedHeytingAlgebra α where __ := Lattice.copy (@GeneralizedHeytingAlgebra.toLattice α c) le eq_le sup eq_sup inf eq_inf __ := OrderTop.copy (@GeneralizedHeytingAlgebra.toOrderTop α c) top eq_top (by rw [← eq_le]; exact fun _ _ ↦ .rfl) himp := himp le_himp_iff _ _ _ := by simp [eq_le, eq_himp, eq_inf] /-- A function to create a provable equal copy of a generalised co-Heyting algebra with possibly different definitional equalities. -/ def GeneralizedCoheytingAlgebra.copy (c : GeneralizedCoheytingAlgebra α) (le : α → α → Prop) (eq_le : le = (by infer_instance : LE α).le) (bot : α) (eq_bot : bot = (by infer_instance : Bot α).bot) (sup : α → α → α) (eq_sup : sup = (by infer_instance : Max α).max) (inf : α → α → α) (eq_inf : inf = (by infer_instance : Min α).min) (sdiff : α → α → α) (eq_sdiff : sdiff = (by infer_instance : SDiff α).sdiff) : GeneralizedCoheytingAlgebra α where __ := Lattice.copy (@GeneralizedCoheytingAlgebra.toLattice α c) le eq_le sup eq_sup inf eq_inf __ := OrderBot.copy (@GeneralizedCoheytingAlgebra.toOrderBot α c) bot eq_bot (by rw [← eq_le]; exact fun _ _ ↦ .rfl) sdiff := sdiff sdiff_le_iff := by simp [eq_le, eq_sdiff, eq_sup] /-- A function to create a provable equal copy of a heyting algebra with possibly different definitional equalities. -/ def HeytingAlgebra.copy (c : HeytingAlgebra α) (le : α → α → Prop) (eq_le : le = (by infer_instance : LE α).le) (top : α) (eq_top : top = (by infer_instance : Top α).top) (bot : α) (eq_bot : bot = (by infer_instance : Bot α).bot) (sup : α → α → α) (eq_sup : sup = (by infer_instance : Max α).max) (inf : α → α → α) (eq_inf : inf = (by infer_instance : Min α).min) (himp : α → α → α) (eq_himp : himp = (by infer_instance : HImp α).himp) (compl : α → α) (eq_compl : compl = (by infer_instance : HasCompl α).compl) : HeytingAlgebra α where toGeneralizedHeytingAlgebra := GeneralizedHeytingAlgebra.copy (@HeytingAlgebra.toGeneralizedHeytingAlgebra α c) le eq_le top eq_top sup eq_sup inf eq_inf himp eq_himp __ := OrderBot.copy (@HeytingAlgebra.toOrderBot α c) bot eq_bot (by rw [← eq_le]; exact fun _ _ ↦ .rfl) compl := compl himp_bot := by simp [eq_le, eq_himp, eq_bot, eq_compl] /-- A function to create a provable equal copy of a co-Heyting algebra with possibly different definitional equalities. -/ def CoheytingAlgebra.copy (c : CoheytingAlgebra α) (le : α → α → Prop) (eq_le : le = (by infer_instance : LE α).le) (top : α) (eq_top : top = (by infer_instance : Top α).top) (bot : α) (eq_bot : bot = (by infer_instance : Bot α).bot) (sup : α → α → α) (eq_sup : sup = (by infer_instance : Max α).max) (inf : α → α → α) (eq_inf : inf = (by infer_instance : Min α).min) (sdiff : α → α → α) (eq_sdiff : sdiff = (by infer_instance : SDiff α).sdiff) (hnot : α → α) (eq_hnot : hnot = (by infer_instance : HNot α).hnot) : CoheytingAlgebra α where toGeneralizedCoheytingAlgebra := GeneralizedCoheytingAlgebra.copy (@CoheytingAlgebra.toGeneralizedCoheytingAlgebra α c) le eq_le bot eq_bot sup eq_sup inf eq_inf sdiff eq_sdiff __ := OrderTop.copy (@CoheytingAlgebra.toOrderTop α c) top eq_top (by rw [← eq_le]; exact fun _ _ ↦ .rfl) hnot := hnot top_sdiff := by simp [eq_le, eq_sdiff, eq_top, eq_hnot] /-- A function to create a provable equal copy of a bi-Heyting algebra with possibly different definitional equalities. -/ def BiheytingAlgebra.copy (c : BiheytingAlgebra α) (le : α → α → Prop) (eq_le : le = (by infer_instance : LE α).le) (top : α) (eq_top : top = (by infer_instance : Top α).top) (bot : α) (eq_bot : bot = (by infer_instance : Bot α).bot) (sup : α → α → α) (eq_sup : sup = (by infer_instance : Max α).max) (inf : α → α → α) (eq_inf : inf = (by infer_instance : Min α).min) (sdiff : α → α → α) (eq_sdiff : sdiff = (by infer_instance : SDiff α).sdiff) (hnot : α → α) (eq_hnot : hnot = (by infer_instance : HNot α).hnot) (himp : α → α → α) (eq_himp : himp = (by infer_instance : HImp α).himp) (compl : α → α) (eq_compl : compl = (by infer_instance : HasCompl α).compl) : BiheytingAlgebra α where toHeytingAlgebra := HeytingAlgebra.copy (@BiheytingAlgebra.toHeytingAlgebra α c) le eq_le top eq_top bot eq_bot sup eq_sup inf eq_inf himp eq_himp compl eq_compl __ := CoheytingAlgebra.copy (@BiheytingAlgebra.toCoheytingAlgebra α c) le eq_le top eq_top bot eq_bot sup eq_sup inf eq_inf sdiff eq_sdiff hnot eq_hnot /-- A function to create a provable equal copy of a complete lattice with possibly different definitional equalities. -/ def CompleteLattice.copy (c : CompleteLattice α) (le : α → α → Prop) (eq_le : le = (by infer_instance : LE α).le) (top : α) (eq_top : top = (by infer_instance : Top α).top) (bot : α) (eq_bot : bot = (by infer_instance : Bot α).bot) (sup : α → α → α) (eq_sup : sup = (by infer_instance : Max α).max) (inf : α → α → α) (eq_inf : inf = (by infer_instance : Min α).min) (sSup : Set α → α) (eq_sSup : sSup = (by infer_instance : SupSet α).sSup) (sInf : Set α → α) (eq_sInf : sInf = (by infer_instance : InfSet α).sInf) : CompleteLattice α where toLattice := Lattice.copy (@CompleteLattice.toLattice α c) le eq_le sup eq_sup inf eq_inf top := top bot := bot sSup := sSup sInf := sInf le_sSup := by intro _ _ h; simp [eq_le, eq_sSup, le_sSup _ _ h] sSup_le := by intro _ _ h; simpa [eq_le, eq_sSup] using h sInf_le := by intro _ _ h; simp [eq_le, eq_sInf, sInf_le _ _ h] le_sInf := by intro _ _ h; simpa [eq_le, eq_sInf] using h le_top := by intros; simp [eq_le, eq_top] bot_le := by intros; simp [eq_le, eq_bot] /-- A function to create a provable equal copy of a frame with possibly different definitional equalities. -/ def Frame.copy (c : Frame α) (le : α → α → Prop) (eq_le : le = (by infer_instance : LE α).le) (top : α) (eq_top : top = (by infer_instance : Top α).top) (bot : α) (eq_bot : bot = (by infer_instance : Bot α).bot) (sup : α → α → α) (eq_sup : sup = (by infer_instance : Max α).max) (inf : α → α → α) (eq_inf : inf = (by infer_instance : Min α).min) (himp : α → α → α) (eq_himp : himp = (by infer_instance : HImp α).himp) (compl : α → α) (eq_compl : compl = (by infer_instance : HasCompl α).compl) (sSup : Set α → α) (eq_sSup : sSup = (by infer_instance : SupSet α).sSup) (sInf : Set α → α) (eq_sInf : sInf = (by infer_instance : InfSet α).sInf) : Frame α where toCompleteLattice := CompleteLattice.copy (@Frame.toCompleteLattice α c) le eq_le top eq_top bot eq_bot sup eq_sup inf eq_inf sSup eq_sSup sInf eq_sInf __ := HeytingAlgebra.copy (@Frame.toHeytingAlgebra α c) le eq_le top eq_top bot eq_bot sup eq_sup inf eq_inf himp eq_himp compl eq_compl /-- A function to create a provable equal copy of a coframe with possibly different definitional equalities. -/ def Coframe.copy (c : Coframe α) (le : α → α → Prop) (eq_le : le = (by infer_instance : LE α).le) (top : α) (eq_top : top = (by infer_instance : Top α).top) (bot : α) (eq_bot : bot = (by infer_instance : Bot α).bot) (sup : α → α → α) (eq_sup : sup = (by infer_instance : Max α).max) (inf : α → α → α) (eq_inf : inf = (by infer_instance : Min α).min) (sdiff : α → α → α) (eq_sdiff : sdiff = (by infer_instance : SDiff α).sdiff) (hnot : α → α) (eq_hnot : hnot = (by infer_instance : HNot α).hnot) (sSup : Set α → α) (eq_sSup : sSup = (by infer_instance : SupSet α).sSup) (sInf : Set α → α) (eq_sInf : sInf = (by infer_instance : InfSet α).sInf) : Coframe α where toCompleteLattice := CompleteLattice.copy (@Coframe.toCompleteLattice α c) le eq_le top eq_top bot eq_bot sup eq_sup inf eq_inf sSup eq_sSup sInf eq_sInf __ := CoheytingAlgebra.copy (@Coframe.toCoheytingAlgebra α c) le eq_le top eq_top bot eq_bot sup eq_sup inf eq_inf sdiff eq_sdiff hnot eq_hnot /-- A function to create a provable equal copy of a complete distributive lattice with possibly different definitional equalities. -/ def CompleteDistribLattice.copy (c : CompleteDistribLattice α) (le : α → α → Prop) (eq_le : le = (by infer_instance : LE α).le) (top : α) (eq_top : top = (by infer_instance : Top α).top) (bot : α) (eq_bot : bot = (by infer_instance : Bot α).bot) (sup : α → α → α) (eq_sup : sup = (by infer_instance : Max α).max) (inf : α → α → α) (eq_inf : inf = (by infer_instance : Min α).min) (sdiff : α → α → α) (eq_sdiff : sdiff = (by infer_instance : SDiff α).sdiff) (hnot : α → α) (eq_hnot : hnot = (by infer_instance : HNot α).hnot) (himp : α → α → α) (eq_himp : himp = (by infer_instance : HImp α).himp) (compl : α → α) (eq_compl : compl = (by infer_instance : HasCompl α).compl) (sSup : Set α → α) (eq_sSup : sSup = (by infer_instance : SupSet α).sSup) (sInf : Set α → α) (eq_sInf : sInf = (by infer_instance : InfSet α).sInf) : CompleteDistribLattice α where toFrame := Frame.copy (@CompleteDistribLattice.toFrame α c) le eq_le top eq_top bot eq_bot sup eq_sup inf eq_inf himp eq_himp compl eq_compl sSup eq_sSup sInf eq_sInf __ := Coframe.copy (@CompleteDistribLattice.toCoframe α c) le eq_le top eq_top bot eq_bot sup eq_sup inf eq_inf sdiff eq_sdiff hnot eq_hnot sSup eq_sSup sInf eq_sInf /-- A function to create a provable equal copy of a conditionally complete lattice with possibly different definitional equalities. -/ def ConditionallyCompleteLattice.copy (c : ConditionallyCompleteLattice α) (le : α → α → Prop) (eq_le : le = (by infer_instance : LE α).le) (sup : α → α → α) (eq_sup : sup = (by infer_instance : Max α).max) (inf : α → α → α) (eq_inf : inf = (by infer_instance : Min α).min) (sSup : Set α → α) (eq_sSup : sSup = (by infer_instance : SupSet α).sSup) (sInf : Set α → α) (eq_sInf : sInf = (by infer_instance : InfSet α).sInf) : ConditionallyCompleteLattice α where toLattice := Lattice.copy (@ConditionallyCompleteLattice.toLattice α c) le eq_le sup eq_sup inf eq_inf sSup := sSup sInf := sInf le_csSup := by intro _ _ hb h; subst_vars; exact le_csSup _ _ hb h csSup_le := by intro _ _ hb h; subst_vars; exact csSup_le _ _ hb h csInf_le := by intro _ _ hb h; subst_vars; exact csInf_le _ _ hb h le_csInf := by intro _ _ hb h; subst_vars; exact le_csInf _ _ hb h
.lake/packages/mathlib/Mathlib/Order/PFilter.lean
import Mathlib.Order.Ideal /-! # Order filters ## 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. - `Order.PFilter P`: The type of nonempty, downward directed, upward closed subsets of `P`. This is dual to `Order.Ideal`, so it simply wraps `Order.Ideal Pᵒᵈ`. - `Order.IsPFilter P`: a predicate for when a `Set P` is a filter. Note the relation between `Order/Filter` and `Order/PFilter`: for any type `α`, `Filter α` represents the same mathematical object as `PFilter (Set α)`. ## References - <https://en.wikipedia.org/wiki/Filter_(mathematics)> ## Tags pfilter, filter, ideal, dual -/ open OrderDual namespace Order /-- A filter on a preorder `P` is a subset of `P` that is - nonempty - downward directed - upward closed. -/ structure PFilter (P : Type*) [Preorder P] where dual : Ideal Pᵒᵈ variable {P : Type*} /-- A predicate for when a subset of `P` is a filter. -/ def IsPFilter [Preorder P] (F : Set P) : Prop := IsIdeal (OrderDual.ofDual ⁻¹' F) theorem IsPFilter.of_def [Preorder P] {F : Set P} (nonempty : F.Nonempty) (directed : DirectedOn (· ≥ ·) F) (mem_of_le : ∀ {x y : P}, x ≤ y → x ∈ F → y ∈ F) : IsPFilter F := ⟨fun _ _ _ _ => mem_of_le ‹_› ‹_›, nonempty, directed⟩ /-- Create an element of type `Order.PFilter` from a set satisfying the predicate `Order.IsPFilter`. -/ def IsPFilter.toPFilter [Preorder P] {F : Set P} (h : IsPFilter F) : PFilter P := ⟨h.toIdeal⟩ namespace PFilter section Preorder variable [Preorder P] {x y : P} (F s t : PFilter P) instance [Inhabited P] : Inhabited (PFilter P) := ⟨⟨default⟩⟩ /-- A filter on `P` is a subset of `P`. -/ instance : SetLike (PFilter P) P where coe F := toDual ⁻¹' F.dual.carrier coe_injective' := fun ⟨_⟩ ⟨_⟩ h => congr_arg mk <| Ideal.ext h theorem isPFilter : IsPFilter (F : Set P) := F.dual.isIdeal protected theorem nonempty : (F : Set P).Nonempty := F.dual.nonempty theorem directed : DirectedOn (· ≥ ·) (F : Set P) := F.dual.directed theorem mem_of_le {F : PFilter P} : x ≤ y → x ∈ F → y ∈ F := fun h => F.dual.lower h /-- Two filters are equal when their underlying sets are equal. -/ @[ext] theorem ext (h : (s : Set P) = t) : s = t := SetLike.ext' h @[trans] theorem mem_of_mem_of_le {F G : PFilter P} (hx : x ∈ F) (hle : F ≤ G) : x ∈ G := hle hx /-- The smallest filter containing a given element. -/ def principal (p : P) : PFilter P := ⟨Ideal.principal (toDual p)⟩ @[simp] theorem mem_mk (x : P) (I : Ideal Pᵒᵈ) : x ∈ (⟨I⟩ : PFilter P) ↔ toDual x ∈ I := Iff.rfl @[simp] theorem principal_le_iff {F : PFilter P} : principal x ≤ F ↔ x ∈ F := Ideal.principal_le_iff (x := toDual x) @[simp] theorem mem_principal : x ∈ principal y ↔ y ≤ x := Iff.rfl theorem principal_le_principal_iff {p q : P} : principal q ≤ principal p ↔ p ≤ q := by simp -- defeq abuse theorem antitone_principal : Antitone (principal : P → PFilter P) := fun _ _ => principal_le_principal_iff.2 end Preorder section OrderTop variable [Preorder P] [OrderTop P] {F : PFilter P} /-- A specific witness of `pfilter.nonempty` when `P` has a top element. -/ @[simp] theorem top_mem : ⊤ ∈ F := Ideal.bot_mem _ /-- There is a bottom filter when `P` has a top element. -/ instance : OrderBot (PFilter P) where bot := ⟨⊥⟩ bot_le F := (bot_le : ⊥ ≤ F.dual) end OrderTop /-- There is a top filter when `P` has a bottom element. -/ instance {P} [Preorder P] [OrderBot P] : OrderTop (PFilter P) where top := ⟨⊤⟩ le_top F := (le_top : F.dual ≤ ⊤) section SemilatticeInf variable [SemilatticeInf P] {x y : P} {F : PFilter P} /-- A specific witness of `pfilter.directed` when `P` has meets. -/ theorem inf_mem (hx : x ∈ F) (hy : y ∈ F) : x ⊓ y ∈ F := Ideal.sup_mem hx hy @[simp] theorem inf_mem_iff : x ⊓ y ∈ F ↔ x ∈ F ∧ y ∈ F := Ideal.sup_mem_iff end SemilatticeInf section CompleteSemilatticeInf variable [CompleteSemilatticeInf P] theorem sInf_gc : GaloisConnection (fun x => toDual (principal x)) fun F => sInf (ofDual F : PFilter P) := fun x F => by simp only [le_sInf_iff, SetLike.mem_coe, toDual_le, SetLike.le_def, mem_principal] /-- If a poset `P` admits arbitrary `Inf`s, then `principal` and `Inf` form a Galois coinsertion. -/ def infGi : GaloisCoinsertion (fun x => toDual (principal x)) fun F => sInf (ofDual F : PFilter P) := sInf_gc.toGaloisCoinsertion fun _ => sInf_le <| mem_principal.2 le_rfl end CompleteSemilatticeInf end PFilter end Order
.lake/packages/mathlib/Mathlib/Order/CompletePartialOrder.lean
import Mathlib.Order.OmegaCompletePartialOrder /-! # Complete Partial Orders This file considers complete partial orders (sometimes called directedly complete partial orders). These are partial orders for which every directed set has a least upper bound. ## Main declarations - `CompletePartialOrder`: Typeclass for (directly) complete partial orders. ## Main statements - `CompletePartialOrder.toOmegaCompletePartialOrder`: A complete partial order is an ω-complete partial order. - `CompleteLattice.toCompletePartialOrder`: A complete lattice is a complete partial order. ## References - [B. A. Davey and H. A. Priestley, Introduction to lattices and order][davey_priestley] ## Tags complete partial order, directedly complete partial order -/ variable {ι : Sort*} {α β : Type*} section CompletePartialOrder /-- Complete partial orders are partial orders where every directed set has a least upper bound. -/ class CompletePartialOrder (α : Type*) extends PartialOrder α, SupSet α where /-- For each directed set `d`, `sSup d` is the least upper bound of `d`. -/ lubOfDirected : ∀ d, DirectedOn (· ≤ ·) d → IsLUB d (sSup d) variable [CompletePartialOrder α] [Preorder β] {f : ι → α} {d : Set α} {a : α} protected lemma DirectedOn.isLUB_sSup : DirectedOn (· ≤ ·) d → IsLUB d (sSup d) := CompletePartialOrder.lubOfDirected _ protected lemma DirectedOn.le_sSup (hd : DirectedOn (· ≤ ·) d) (ha : a ∈ d) : a ≤ sSup d := hd.isLUB_sSup.1 ha protected lemma DirectedOn.sSup_le (hd : DirectedOn (· ≤ ·) d) (ha : ∀ b ∈ d, b ≤ a) : sSup d ≤ a := hd.isLUB_sSup.2 ha protected lemma Directed.le_iSup (hf : Directed (· ≤ ·) f) (i : ι) : f i ≤ ⨆ j, f j := hf.directedOn_range.le_sSup <| Set.mem_range_self _ protected lemma Directed.iSup_le (hf : Directed (· ≤ ·) f) (ha : ∀ i, f i ≤ a) : ⨆ i, f i ≤ a := hf.directedOn_range.sSup_le <| Set.forall_mem_range.2 ha --TODO: We could mimic more `sSup`/`iSup` lemmas /-- Scott-continuity takes on a simpler form in complete partial orders. -/ lemma CompletePartialOrder.scottContinuous {f : α → β} : ScottContinuous f ↔ ∀ ⦃d : Set α⦄, d.Nonempty → DirectedOn (· ≤ ·) d → IsLUB (f '' d) (f (sSup d)) := by refine ⟨fun h d hd₁ hd₂ ↦ h hd₁ hd₂ hd₂.isLUB_sSup, fun h d hne hd a hda ↦ ?_⟩ rw [hda.unique hd.isLUB_sSup] exact h hne hd open OmegaCompletePartialOrder /-- A complete partial order is an ω-complete partial order. -/ instance CompletePartialOrder.toOmegaCompletePartialOrder : OmegaCompletePartialOrder α where ωSup c := ⨆ n, c n le_ωSup c := c.directed.le_iSup ωSup_le c _ := c.directed.iSup_le end CompletePartialOrder /-- A complete lattice is a complete partial order. -/ instance CompleteLattice.toCompletePartialOrder [CompleteLattice α] : CompletePartialOrder α where sSup := sSup lubOfDirected _ _ := isLUB_sSup _
.lake/packages/mathlib/Mathlib/Order/OrderIsoNat.lean
import Mathlib.Data.Nat.Lattice import Mathlib.Logic.Denumerable import Mathlib.Logic.Function.Iterate import Mathlib.Order.Hom.Basic import Mathlib.Data.Set.Subsingleton /-! # Relation embeddings from the naturals This file allows translation from monotone functions `ℕ → α` to order embeddings `ℕ ↪ α` and defines the limit value of an eventually-constant sequence. ## Main declarations * `natLT`/`natGT`: Make an order embedding `Nat ↪ α` from an increasing/decreasing function `Nat → α`. * `monotonicSequenceLimit`: The limit of an eventually-constant monotone sequence `Nat →o α`. * `monotonicSequenceLimitIndex`: The index of the first occurrence of `monotonicSequenceLimit` in the sequence. -/ variable {α : Type*} namespace RelEmbedding variable {r : α → α → Prop} [IsStrictOrder α r] /-- If `f` is a strictly `r`-increasing sequence, then this returns `f` as an order embedding. -/ def natLT (f : ℕ → α) (H : ∀ n : ℕ, r (f n) (f (n + 1))) : ((· < ·) : ℕ → ℕ → Prop) ↪r r := ofMonotone f <| Nat.rel_of_forall_rel_succ_of_lt r H @[simp] theorem coe_natLT {f : ℕ → α} {H : ∀ n : ℕ, r (f n) (f (n + 1))} : ⇑(natLT f H) = f := rfl /-- If `f` is a strictly `r`-decreasing sequence, then this returns `f` as an order embedding. -/ def natGT (f : ℕ → α) (H : ∀ n : ℕ, r (f (n + 1)) (f n)) : ((· > ·) : ℕ → ℕ → Prop) ↪r r := haveI := IsStrictOrder.swap r RelEmbedding.swap (natLT f H) @[simp] theorem coe_natGT {f : ℕ → α} {H : ∀ n : ℕ, r (f (n + 1)) (f n)} : ⇑(natGT f H) = f := rfl @[deprecated (since := "2025-08-08")] alias exists_not_acc_lt_of_not_acc := exists_not_acc_lt_of_not_acc /-- A value is accessible iff it isn't contained in any infinite decreasing sequence. -/ theorem acc_iff_isEmpty_subtype_mem_range {x} : Acc r x ↔ IsEmpty { f : ((· > ·) : ℕ → ℕ → Prop) ↪r r // x ∈ Set.range f } where mp acc := .mk fun ⟨f, k, hk⟩ ↦ not_acc_iff_exists_descending_chain.mpr ⟨(f <| k + ·), hk, fun _n ↦ f.map_rel_iff.2 (Nat.lt_succ_self _)⟩ acc mpr h := of_not_not fun nacc ↦ have ⟨f, hf⟩ := not_acc_iff_exists_descending_chain.mp nacc h.elim ⟨natGT f hf.2, 0, hf.1⟩ theorem not_acc (f : ((· > ·) : ℕ → ℕ → Prop) ↪r r) (k : ℕ) : ¬Acc r (f k) := by rw [acc_iff_isEmpty_subtype_mem_range, not_isEmpty_iff] exact ⟨⟨f, k, rfl⟩⟩ /-- A strict order relation is well-founded iff it doesn't have any infinite descending chain. See `wellFounded_iff_isEmpty_descending_chain` for a version which works on any relation. -/ theorem wellFounded_iff_isEmpty : WellFounded r ↔ IsEmpty (((· > ·) : ℕ → ℕ → Prop) ↪r r) where mp := fun ⟨h⟩ ↦ ⟨fun f ↦ f.not_acc 0 (h _)⟩ mpr _ := ⟨fun _x ↦ acc_iff_isEmpty_subtype_mem_range.2 inferInstance⟩ theorem not_wellFounded (f : ((· > ·) : ℕ → ℕ → Prop) ↪r r) : ¬WellFounded r := by rw [wellFounded_iff_isEmpty, not_isEmpty_iff] exact ⟨f⟩ @[deprecated (since := "2025-08-10")] alias acc_iff_no_decreasing_seq := acc_iff_isEmpty_subtype_mem_range @[deprecated (since := "2025-08-10")] alias not_acc_of_decreasing_seq := not_acc @[deprecated (since := "2025-08-10")] alias wellFounded_iff_no_descending_seq := wellFounded_iff_isEmpty @[deprecated (since := "2025-08-10")] alias not_wellFounded_of_decreasing_seq := not_wellFounded end RelEmbedding theorem not_strictAnti_of_wellFoundedLT [Preorder α] [WellFoundedLT α] (f : ℕ → α) : ¬ StrictAnti f := fun hf ↦ (RelEmbedding.natGT f (fun n ↦ hf (by simp))).not_wellFounded wellFounded_lt theorem not_strictMono_of_wellFoundedGT [Preorder α] [WellFoundedGT α] (f : ℕ → α) : ¬ StrictMono f := not_strictAnti_of_wellFoundedLT (α := αᵒᵈ) f namespace Nat variable (s : Set ℕ) [Infinite s] /-- An order embedding from `ℕ` to itself with a specified range -/ def orderEmbeddingOfSet [DecidablePred (· ∈ s)] : ℕ ↪o ℕ := (RelEmbedding.orderEmbeddingOfLTEmbedding (RelEmbedding.natLT (Nat.Subtype.ofNat s) fun _ => Nat.Subtype.lt_succ_self _)).trans (OrderEmbedding.subtype s) /-- `Nat.Subtype.ofNat` as an order isomorphism between `ℕ` and an infinite subset. See also `Nat.nth` for a version where the subset may be finite. -/ noncomputable def Subtype.orderIsoOfNat : ℕ ≃o s := by classical exact RelIso.ofSurjective (RelEmbedding.orderEmbeddingOfLTEmbedding (RelEmbedding.natLT (Nat.Subtype.ofNat s) fun n => Nat.Subtype.lt_succ_self _)) Nat.Subtype.ofNat_surjective variable {s} @[simp] theorem coe_orderEmbeddingOfSet [DecidablePred (· ∈ s)] : ⇑(orderEmbeddingOfSet s) = (↑) ∘ Subtype.ofNat s := rfl theorem orderEmbeddingOfSet_apply [DecidablePred (· ∈ s)] {n : ℕ} : orderEmbeddingOfSet s n = Subtype.ofNat s n := rfl @[simp] theorem Subtype.orderIsoOfNat_apply [dP : DecidablePred (· ∈ s)] {n : ℕ} : Subtype.orderIsoOfNat s n = Subtype.ofNat s n := by simp [orderIsoOfNat]; congr! variable (s) theorem orderEmbeddingOfSet_range [DecidablePred (· ∈ s)] : Set.range (Nat.orderEmbeddingOfSet s) = s := Subtype.coe_comp_ofNat_range theorem exists_subseq_of_forall_mem_union {s t : Set α} (e : ℕ → α) (he : ∀ n, e n ∈ s ∪ t) : ∃ g : ℕ ↪o ℕ, (∀ n, e (g n) ∈ s) ∨ ∀ n, e (g n) ∈ t := by classical have : Infinite (e ⁻¹' s) ∨ Infinite (e ⁻¹' t) := by simp only [Set.infinite_coe_iff, ← Set.infinite_union, ← Set.preimage_union, Set.eq_univ_of_forall fun n => Set.mem_preimage.2 (he n), Set.infinite_univ] cases this exacts [⟨Nat.orderEmbeddingOfSet (e ⁻¹' s), Or.inl fun n => (Nat.Subtype.ofNat (e ⁻¹' s) _).2⟩, ⟨Nat.orderEmbeddingOfSet (e ⁻¹' t), Or.inr fun n => (Nat.Subtype.ofNat (e ⁻¹' t) _).2⟩] end Nat theorem exists_increasing_or_nonincreasing_subseq' (r : α → α → Prop) (f : ℕ → α) : ∃ g : ℕ ↪o ℕ, (∀ n : ℕ, r (f (g n)) (f (g (n + 1)))) ∨ ∀ m n : ℕ, m < n → ¬r (f (g m)) (f (g n)) := by classical let bad : Set ℕ := { m | ∀ n, m < n → ¬r (f m) (f n) } by_cases hbad : Infinite bad · refine ⟨Nat.orderEmbeddingOfSet bad, Or.intro_right _ fun m n mn => ?_⟩ have h := @Set.mem_range_self _ _ ↑(Nat.orderEmbeddingOfSet bad) m rw [Nat.orderEmbeddingOfSet_range bad] at h exact h _ ((OrderEmbedding.lt_iff_lt _).2 mn) · rw [Set.infinite_coe_iff, Set.Infinite, not_not] at hbad obtain ⟨m, hm⟩ : ∃ m, ∀ n, m ≤ n → n ∉ bad := by by_cases he : hbad.toFinset.Nonempty · refine ⟨(hbad.toFinset.max' he).succ, fun n hn nbad => Nat.not_succ_le_self _ (hn.trans (hbad.toFinset.le_max' n (hbad.mem_toFinset.2 nbad)))⟩ · exact ⟨0, fun n _ nbad => he ⟨n, hbad.mem_toFinset.2 nbad⟩⟩ have h : ∀ n : ℕ, ∃ n' : ℕ, n < n' ∧ r (f (n + m)) (f (n' + m)) := by intro n have h := hm _ (Nat.le_add_left m n) simp only [bad, exists_prop, not_not, Set.mem_setOf_eq, not_forall] at h obtain ⟨n', hn1, hn2⟩ := h refine ⟨n + n' - n - m, by cutsat, ?_⟩ convert hn2 omega let g' : ℕ → ℕ := @Nat.rec (fun _ => ℕ) m fun n gn => Nat.find (h gn) exact ⟨(RelEmbedding.natLT (fun n => g' n + m) fun n => Nat.add_lt_add_right (Nat.find_spec (h (g' n))).1 m).orderEmbeddingOfLTEmbedding, Or.intro_left _ fun n => (Nat.find_spec (h (g' n))).2⟩ /-- This is the infinitary Erdős–Szekeres theorem, and an important lemma in the usual proof of Bolzano-Weierstrass for `ℝ`. -/ theorem exists_increasing_or_nonincreasing_subseq (r : α → α → Prop) [IsTrans α r] (f : ℕ → α) : ∃ g : ℕ ↪o ℕ, (∀ m n : ℕ, m < n → r (f (g m)) (f (g n))) ∨ ∀ m n : ℕ, m < n → ¬r (f (g m)) (f (g n)) := by obtain ⟨g, hr | hnr⟩ := exists_increasing_or_nonincreasing_subseq' r f · refine ⟨g, Or.intro_left _ fun m n mn => ?_⟩ obtain ⟨x, rfl⟩ := Nat.exists_eq_add_of_le (Nat.succ_le_iff.2 mn) induction x with | zero => apply hr | succ x ih => apply IsTrans.trans _ _ _ _ (hr _) exact ih (lt_of_lt_of_le m.lt_succ_self (Nat.le_add_right _ _)) · exact ⟨g, Or.intro_right _ hnr⟩ /-- The **monotone chain condition**: a preorder is co-well-founded iff every increasing sequence contains two non-increasing indices. See `wellFoundedGT_iff_monotone_chain_condition` for a stronger version on partial orders. -/ theorem wellFoundedGT_iff_monotone_chain_condition' [Preorder α] : WellFoundedGT α ↔ ∀ a : ℕ →o α, ∃ n, ∀ m, n ≤ m → ¬a n < a m := by refine ⟨fun h a => ?_, fun h => ?_⟩ · obtain ⟨x, ⟨n, rfl⟩, H⟩ := h.wf.has_min _ (Set.range_nonempty a) exact ⟨n, fun m _ => H _ (Set.mem_range_self _)⟩ · rw [WellFoundedGT, isWellFounded_iff, RelEmbedding.wellFounded_iff_isEmpty] refine ⟨fun a => ?_⟩ obtain ⟨n, hn⟩ := h (a.swap : _ →r _).toOrderHom exact hn n.succ n.lt_succ_self.le ((RelEmbedding.map_rel_iff _).2 n.lt_succ_self) theorem WellFoundedGT.monotone_chain_condition' [Preorder α] [h : WellFoundedGT α] (a : ℕ →o α) : ∃ n, ∀ m, n ≤ m → ¬a n < a m := wellFoundedGT_iff_monotone_chain_condition'.1 h a /-- A stronger version of the **monotone chain** condition for partial orders. See `wellFoundedGT_iff_monotone_chain_condition'` for a version on preorders. -/ theorem wellFoundedGT_iff_monotone_chain_condition [PartialOrder α] : WellFoundedGT α ↔ ∀ a : ℕ →o α, ∃ n, ∀ m, n ≤ m → a n = a m := wellFoundedGT_iff_monotone_chain_condition'.trans <| by congrm ∀ a, ∃ n, ∀ m h, ?_ rw [lt_iff_le_and_ne] simp [a.mono h] theorem WellFoundedGT.monotone_chain_condition [PartialOrder α] [h : WellFoundedGT α] (a : ℕ →o α) : ∃ n, ∀ m, n ≤ m → a n = a m := wellFoundedGT_iff_monotone_chain_condition.1 h a /-- Given an eventually-constant monotone sequence `a₀ ≤ a₁ ≤ a₂ ≤ ...` in a partially-ordered type, `monotonicSequenceLimitIndex a` is the least natural number `n` for which `aₙ` reaches the constant value. For sequences that are not eventually constant, `monotonicSequenceLimitIndex a` is defined, but is a junk value. -/ noncomputable def monotonicSequenceLimitIndex [Preorder α] (a : ℕ →o α) : ℕ := sInf { n | ∀ m, n ≤ m → a n = a m } /-- The constant value of an eventually-constant monotone sequence `a₀ ≤ a₁ ≤ a₂ ≤ ...` in a partially-ordered type. -/ noncomputable def monotonicSequenceLimit [Preorder α] (a : ℕ →o α) := a (monotonicSequenceLimitIndex a) theorem le_monotonicSequenceLimit [PartialOrder α] [WellFoundedGT α] (a : ℕ →o α) (m : ℕ) : a m ≤ monotonicSequenceLimit a := by rcases le_or_gt m (monotonicSequenceLimitIndex a) with hm | hm · exact a.monotone hm · obtain h := WellFoundedGT.monotone_chain_condition a exact (Nat.sInf_mem (s := {n | ∀ m, n ≤ m → a n = a m}) h m hm.le).ge theorem WellFoundedGT.iSup_eq_monotonicSequenceLimit [CompleteLattice α] [WellFoundedGT α] (a : ℕ →o α) : iSup a = monotonicSequenceLimit a := (iSup_le (le_monotonicSequenceLimit a)).antisymm (le_iSup a _) theorem WellFoundedGT.ciSup_eq_monotonicSequenceLimit [ConditionallyCompleteLattice α] [WellFoundedGT α] (a : ℕ →o α) (ha : BddAbove (Set.range a)) : iSup a = monotonicSequenceLimit a := (ciSup_le (le_monotonicSequenceLimit a)).antisymm (le_ciSup ha _) theorem exists_covBy_seq_of_wellFoundedLT_wellFoundedGT (α) [Preorder α] [Nonempty α] [wfl : WellFoundedLT α] [wfg : WellFoundedGT α] : ∃ a : ℕ → α, IsMin (a 0) ∧ ∃ n, IsMax (a n) ∧ ∀ i < n, a i ⋖ a (i + 1) := by choose next hnext using exists_covBy_of_wellFoundedLT (α := α) have hα := Set.nonempty_iff_univ_nonempty.mp ‹_› classical let a : ℕ → α := Nat.rec (wfl.wf.min _ hα) fun _n a ↦ if ha : IsMax a then a else next ha refine ⟨a, isMin_iff_forall_not_lt.mpr fun _ ↦ wfl.wf.not_lt_min _ hα trivial, ?_⟩ have cov n (hn : ¬ IsMax (a n)) : a n ⋖ a (n + 1) := by change a n ⋖ if ha : IsMax (a n) then a n else _ rw [dif_neg hn] exact hnext hn have H : ∃ n, IsMax (a n) := by by_contra! exact (RelEmbedding.natGT a fun n ↦ (cov n (this n)).1).not_wellFounded wfg.wf exact ⟨_, wellFounded_lt.min_mem _ H, fun i h ↦ cov _ fun h' ↦ wellFounded_lt.not_lt_min _ H h' h⟩ theorem exists_covBy_seq_of_wellFoundedLT_wellFoundedGT_of_le {α : Type*} [PartialOrder α] [wfl : WellFoundedLT α] [wfg : WellFoundedGT α] {x y : α} (h : x ≤ y) : ∃ a : ℕ → α, a 0 = x ∧ ∃ n, a n = y ∧ ∀ i < n, a i ⋖ a (i + 1) := by let S := Set.Icc x y let hS : BoundedOrder S := { top := ⟨y, h, le_rfl⟩, le_top x := x.2.2, bot := ⟨x, le_rfl, h⟩, bot_le x := x.2.1 } obtain ⟨a, h₁, n, h₂, e⟩ := exists_covBy_seq_of_wellFoundedLT_wellFoundedGT S simp only [isMin_iff_eq_bot, Subtype.ext_iff, isMax_iff_eq_top] at h₁ h₂ exact ⟨Subtype.val ∘ a, h₁, n, h₂, fun i hi ↦ ⟨(e i hi).1, fun c hc h ↦ (e i hi).2 (c := ⟨c, (a i).2.1.trans hc.le, h.le.trans (a _).2.2⟩) hc h⟩⟩
.lake/packages/mathlib/Mathlib/Order/Bounded.lean
import Mathlib.Order.RelClasses import Mathlib.Order.Interval.Set.Basic /-! # Bounded and unbounded sets We prove miscellaneous lemmas about bounded and unbounded sets. Many of these are just variations on the same ideas, or similar results with a few minor differences. The file is divided into these different general ideas. -/ assert_not_exists RelIso namespace Set variable {α : Type*} {r : α → α → Prop} {s t : Set α} /-! ### Subsets of bounded and unbounded sets -/ theorem Bounded.mono (hst : s ⊆ t) (hs : Bounded r t) : Bounded r s := hs.imp fun _ ha b hb => ha b (hst hb) theorem Unbounded.mono (hst : s ⊆ t) (hs : Unbounded r s) : Unbounded r t := fun a => let ⟨b, hb, hb'⟩ := hs a ⟨b, hst hb, hb'⟩ /-! ### Alternate characterizations of unboundedness on orders -/ theorem unbounded_le_of_forall_exists_lt [Preorder α] (h : ∀ a, ∃ b ∈ s, a < b) : Unbounded (· ≤ ·) s := fun a => let ⟨b, hb, hb'⟩ := h a ⟨b, hb, fun hba => hba.not_gt hb'⟩ theorem unbounded_le_iff [LinearOrder α] : Unbounded (· ≤ ·) s ↔ ∀ a, ∃ b ∈ s, a < b := by simp only [Unbounded, not_le] theorem unbounded_lt_of_forall_exists_le [Preorder α] (h : ∀ a, ∃ b ∈ s, a ≤ b) : Unbounded (· < ·) s := fun a => let ⟨b, hb, hb'⟩ := h a ⟨b, hb, fun hba => hba.not_ge hb'⟩ theorem unbounded_lt_iff [LinearOrder α] : Unbounded (· < ·) s ↔ ∀ a, ∃ b ∈ s, a ≤ b := by simp only [Unbounded, not_lt] theorem unbounded_ge_of_forall_exists_gt [Preorder α] (h : ∀ a, ∃ b ∈ s, b < a) : Unbounded (· ≥ ·) s := @unbounded_le_of_forall_exists_lt αᵒᵈ _ _ h theorem unbounded_ge_iff [LinearOrder α] : Unbounded (· ≥ ·) s ↔ ∀ a, ∃ b ∈ s, b < a := ⟨fun h a => let ⟨b, hb, hba⟩ := h a ⟨b, hb, lt_of_not_ge hba⟩, unbounded_ge_of_forall_exists_gt⟩ theorem unbounded_gt_of_forall_exists_ge [Preorder α] (h : ∀ a, ∃ b ∈ s, b ≤ a) : Unbounded (· > ·) s := fun a => let ⟨b, hb, hb'⟩ := h a ⟨b, hb, fun hba => not_le_of_gt hba hb'⟩ theorem unbounded_gt_iff [LinearOrder α] : Unbounded (· > ·) s ↔ ∀ a, ∃ b ∈ s, b ≤ a := ⟨fun h a => let ⟨b, hb, hba⟩ := h a ⟨b, hb, le_of_not_gt hba⟩, unbounded_gt_of_forall_exists_ge⟩ /-! ### Relation between boundedness by strict and nonstrict orders. -/ /-! #### Less and less or equal -/ theorem Bounded.rel_mono {r' : α → α → Prop} (h : Bounded r s) (hrr' : r ≤ r') : Bounded r' s := let ⟨a, ha⟩ := h ⟨a, fun b hb => hrr' b a (ha b hb)⟩ theorem bounded_le_of_bounded_lt [Preorder α] (h : Bounded (· < ·) s) : Bounded (· ≤ ·) s := h.rel_mono fun _ _ => le_of_lt theorem Unbounded.rel_mono {r' : α → α → Prop} (hr : r' ≤ r) (h : Unbounded r s) : Unbounded r' s := fun a => let ⟨b, hb, hba⟩ := h a ⟨b, hb, fun hba' => hba (hr b a hba')⟩ theorem unbounded_lt_of_unbounded_le [Preorder α] (h : Unbounded (· ≤ ·) s) : Unbounded (· < ·) s := h.rel_mono fun _ _ => le_of_lt theorem bounded_le_iff_bounded_lt [Preorder α] [NoMaxOrder α] : Bounded (· ≤ ·) s ↔ Bounded (· < ·) s := by refine ⟨fun h => ?_, bounded_le_of_bounded_lt⟩ obtain ⟨a, ha⟩ := h obtain ⟨b, hb⟩ := exists_gt a exact ⟨b, fun c hc => lt_of_le_of_lt (ha c hc) hb⟩ theorem unbounded_lt_iff_unbounded_le [Preorder α] [NoMaxOrder α] : Unbounded (· < ·) s ↔ Unbounded (· ≤ ·) s := by simp_rw [← not_bounded_iff, bounded_le_iff_bounded_lt] /-! #### Greater and greater or equal -/ theorem bounded_ge_of_bounded_gt [Preorder α] (h : Bounded (· > ·) s) : Bounded (· ≥ ·) s := let ⟨a, ha⟩ := h ⟨a, fun b hb => le_of_lt (ha b hb)⟩ theorem unbounded_gt_of_unbounded_ge [Preorder α] (h : Unbounded (· ≥ ·) s) : Unbounded (· > ·) s := fun a => let ⟨b, hb, hba⟩ := h a ⟨b, hb, fun hba' => hba (le_of_lt hba')⟩ theorem bounded_ge_iff_bounded_gt [Preorder α] [NoMinOrder α] : Bounded (· ≥ ·) s ↔ Bounded (· > ·) s := @bounded_le_iff_bounded_lt αᵒᵈ _ _ _ theorem unbounded_gt_iff_unbounded_ge [Preorder α] [NoMinOrder α] : Unbounded (· > ·) s ↔ Unbounded (· ≥ ·) s := @unbounded_lt_iff_unbounded_le αᵒᵈ _ _ _ /-! ### The universal set -/ theorem unbounded_le_univ [LE α] [NoTopOrder α] : Unbounded (· ≤ ·) (@Set.univ α) := fun a => let ⟨b, hb⟩ := exists_not_le a ⟨b, ⟨⟩, hb⟩ theorem unbounded_lt_univ [Preorder α] [NoTopOrder α] : Unbounded (· < ·) (@Set.univ α) := unbounded_lt_of_unbounded_le unbounded_le_univ theorem unbounded_ge_univ [LE α] [NoBotOrder α] : Unbounded (· ≥ ·) (@Set.univ α) := fun a => let ⟨b, hb⟩ := exists_not_ge a ⟨b, ⟨⟩, hb⟩ theorem unbounded_gt_univ [Preorder α] [NoBotOrder α] : Unbounded (· > ·) (@Set.univ α) := unbounded_gt_of_unbounded_ge unbounded_ge_univ /-! ### Bounded and unbounded intervals -/ theorem bounded_self (a : α) : Bounded r { b | r b a } := ⟨a, fun _ => id⟩ /-! #### Half-open bounded intervals -/ theorem bounded_lt_Iio [Preorder α] (a : α) : Bounded (· < ·) (Iio a) := bounded_self a theorem bounded_le_Iio [Preorder α] (a : α) : Bounded (· ≤ ·) (Iio a) := bounded_le_of_bounded_lt (bounded_lt_Iio a) theorem bounded_le_Iic [Preorder α] (a : α) : Bounded (· ≤ ·) (Iic a) := bounded_self a theorem bounded_lt_Iic [Preorder α] [NoMaxOrder α] (a : α) : Bounded (· < ·) (Iic a) := by simp only [← bounded_le_iff_bounded_lt, bounded_le_Iic] theorem bounded_gt_Ioi [Preorder α] (a : α) : Bounded (· > ·) (Ioi a) := bounded_self a theorem bounded_ge_Ioi [Preorder α] (a : α) : Bounded (· ≥ ·) (Ioi a) := bounded_ge_of_bounded_gt (bounded_gt_Ioi a) theorem bounded_ge_Ici [Preorder α] (a : α) : Bounded (· ≥ ·) (Ici a) := bounded_self a theorem bounded_gt_Ici [Preorder α] [NoMinOrder α] (a : α) : Bounded (· > ·) (Ici a) := by simp only [← bounded_ge_iff_bounded_gt, bounded_ge_Ici] /-! #### Other bounded intervals -/ theorem bounded_lt_Ioo [Preorder α] (a b : α) : Bounded (· < ·) (Ioo a b) := (bounded_lt_Iio b).mono Set.Ioo_subset_Iio_self theorem bounded_lt_Ico [Preorder α] (a b : α) : Bounded (· < ·) (Ico a b) := (bounded_lt_Iio b).mono Set.Ico_subset_Iio_self theorem bounded_lt_Ioc [Preorder α] [NoMaxOrder α] (a b : α) : Bounded (· < ·) (Ioc a b) := (bounded_lt_Iic b).mono Set.Ioc_subset_Iic_self theorem bounded_lt_Icc [Preorder α] [NoMaxOrder α] (a b : α) : Bounded (· < ·) (Icc a b) := (bounded_lt_Iic b).mono Set.Icc_subset_Iic_self theorem bounded_le_Ioo [Preorder α] (a b : α) : Bounded (· ≤ ·) (Ioo a b) := (bounded_le_Iio b).mono Set.Ioo_subset_Iio_self theorem bounded_le_Ico [Preorder α] (a b : α) : Bounded (· ≤ ·) (Ico a b) := (bounded_le_Iio b).mono Set.Ico_subset_Iio_self theorem bounded_le_Ioc [Preorder α] (a b : α) : Bounded (· ≤ ·) (Ioc a b) := (bounded_le_Iic b).mono Set.Ioc_subset_Iic_self theorem bounded_le_Icc [Preorder α] (a b : α) : Bounded (· ≤ ·) (Icc a b) := (bounded_le_Iic b).mono Set.Icc_subset_Iic_self theorem bounded_gt_Ioo [Preorder α] (a b : α) : Bounded (· > ·) (Ioo a b) := (bounded_gt_Ioi a).mono Set.Ioo_subset_Ioi_self theorem bounded_gt_Ioc [Preorder α] (a b : α) : Bounded (· > ·) (Ioc a b) := (bounded_gt_Ioi a).mono Set.Ioc_subset_Ioi_self theorem bounded_gt_Ico [Preorder α] [NoMinOrder α] (a b : α) : Bounded (· > ·) (Ico a b) := (bounded_gt_Ici a).mono Set.Ico_subset_Ici_self theorem bounded_gt_Icc [Preorder α] [NoMinOrder α] (a b : α) : Bounded (· > ·) (Icc a b) := (bounded_gt_Ici a).mono Set.Icc_subset_Ici_self theorem bounded_ge_Ioo [Preorder α] (a b : α) : Bounded (· ≥ ·) (Ioo a b) := (bounded_ge_Ioi a).mono Set.Ioo_subset_Ioi_self theorem bounded_ge_Ioc [Preorder α] (a b : α) : Bounded (· ≥ ·) (Ioc a b) := (bounded_ge_Ioi a).mono Set.Ioc_subset_Ioi_self theorem bounded_ge_Ico [Preorder α] (a b : α) : Bounded (· ≥ ·) (Ico a b) := (bounded_ge_Ici a).mono Set.Ico_subset_Ici_self theorem bounded_ge_Icc [Preorder α] (a b : α) : Bounded (· ≥ ·) (Icc a b) := (bounded_ge_Ici a).mono Set.Icc_subset_Ici_self /-! #### Unbounded intervals -/ theorem unbounded_le_Ioi [SemilatticeSup α] [NoMaxOrder α] (a : α) : Unbounded (· ≤ ·) (Ioi a) := fun b => let ⟨c, hc⟩ := exists_gt (a ⊔ b) ⟨c, le_sup_left.trans_lt hc, (le_sup_right.trans_lt hc).not_ge⟩ theorem unbounded_le_Ici [SemilatticeSup α] [NoMaxOrder α] (a : α) : Unbounded (· ≤ ·) (Ici a) := (unbounded_le_Ioi a).mono Set.Ioi_subset_Ici_self theorem unbounded_lt_Ioi [SemilatticeSup α] [NoMaxOrder α] (a : α) : Unbounded (· < ·) (Ioi a) := unbounded_lt_of_unbounded_le (unbounded_le_Ioi a) theorem unbounded_lt_Ici [SemilatticeSup α] (a : α) : Unbounded (· < ·) (Ici a) := fun b => ⟨a ⊔ b, le_sup_left, le_sup_right.not_gt⟩ /-! ### Bounded initial segments -/ theorem bounded_inter_not (H : ∀ a b, ∃ m, ∀ c, r c a ∨ r c b → r c m) (a : α) : Bounded r (s ∩ { b | ¬r b a }) ↔ Bounded r s := by refine ⟨?_, Bounded.mono inter_subset_left⟩ rintro ⟨b, hb⟩ obtain ⟨m, hm⟩ := H a b exact ⟨m, fun c hc => hm c (or_iff_not_imp_left.2 fun hca => hb c ⟨hc, hca⟩)⟩ theorem unbounded_inter_not (H : ∀ a b, ∃ m, ∀ c, r c a ∨ r c b → r c m) (a : α) : Unbounded r (s ∩ { b | ¬r b a }) ↔ Unbounded r s := by simp_rw [← not_bounded_iff, bounded_inter_not H] /-! #### Less or equal -/ theorem bounded_le_inter_not_le [SemilatticeSup α] (a : α) : Bounded (· ≤ ·) (s ∩ { b | ¬b ≤ a }) ↔ Bounded (· ≤ ·) s := bounded_inter_not (fun x y => ⟨x ⊔ y, fun _ h => h.elim le_sup_of_le_left le_sup_of_le_right⟩) a theorem unbounded_le_inter_not_le [SemilatticeSup α] (a : α) : Unbounded (· ≤ ·) (s ∩ { b | ¬b ≤ a }) ↔ Unbounded (· ≤ ·) s := by rw [← not_bounded_iff, ← not_bounded_iff, not_iff_not] exact bounded_le_inter_not_le a theorem bounded_le_inter_lt [LinearOrder α] (a : α) : Bounded (· ≤ ·) (s ∩ { b | a < b }) ↔ Bounded (· ≤ ·) s := by simp_rw [← not_le, bounded_le_inter_not_le] theorem unbounded_le_inter_lt [LinearOrder α] (a : α) : Unbounded (· ≤ ·) (s ∩ { b | a < b }) ↔ Unbounded (· ≤ ·) s := by convert @unbounded_le_inter_not_le _ s _ a exact lt_iff_not_ge theorem bounded_le_inter_le [LinearOrder α] (a : α) : Bounded (· ≤ ·) (s ∩ { b | a ≤ b }) ↔ Bounded (· ≤ ·) s := by refine ⟨?_, Bounded.mono Set.inter_subset_left⟩ rw [← @bounded_le_inter_lt _ s _ a] exact Bounded.mono fun x ⟨hx, hx'⟩ => ⟨hx, le_of_lt hx'⟩ theorem unbounded_le_inter_le [LinearOrder α] (a : α) : Unbounded (· ≤ ·) (s ∩ { b | a ≤ b }) ↔ Unbounded (· ≤ ·) s := by rw [← not_bounded_iff, ← not_bounded_iff, not_iff_not] exact bounded_le_inter_le a /-! #### Less than -/ theorem bounded_lt_inter_not_lt [SemilatticeSup α] (a : α) : Bounded (· < ·) (s ∩ { b | ¬b < a }) ↔ Bounded (· < ·) s := bounded_inter_not (fun x y => ⟨x ⊔ y, fun _ h => h.elim lt_sup_of_lt_left lt_sup_of_lt_right⟩) a theorem unbounded_lt_inter_not_lt [SemilatticeSup α] (a : α) : Unbounded (· < ·) (s ∩ { b | ¬b < a }) ↔ Unbounded (· < ·) s := by rw [← not_bounded_iff, ← not_bounded_iff, not_iff_not] exact bounded_lt_inter_not_lt a theorem bounded_lt_inter_le [LinearOrder α] (a : α) : Bounded (· < ·) (s ∩ { b | a ≤ b }) ↔ Bounded (· < ·) s := by convert @bounded_lt_inter_not_lt _ s _ a exact not_lt.symm theorem unbounded_lt_inter_le [LinearOrder α] (a : α) : Unbounded (· < ·) (s ∩ { b | a ≤ b }) ↔ Unbounded (· < ·) s := by convert @unbounded_lt_inter_not_lt _ s _ a exact not_lt.symm theorem bounded_lt_inter_lt [LinearOrder α] [NoMaxOrder α] (a : α) : Bounded (· < ·) (s ∩ { b | a < b }) ↔ Bounded (· < ·) s := by rw [← bounded_le_iff_bounded_lt, ← bounded_le_iff_bounded_lt] exact bounded_le_inter_lt a theorem unbounded_lt_inter_lt [LinearOrder α] [NoMaxOrder α] (a : α) : Unbounded (· < ·) (s ∩ { b | a < b }) ↔ Unbounded (· < ·) s := by rw [← not_bounded_iff, ← not_bounded_iff, not_iff_not] exact bounded_lt_inter_lt a /-! #### Greater or equal -/ theorem bounded_ge_inter_not_ge [SemilatticeInf α] (a : α) : Bounded (· ≥ ·) (s ∩ { b | ¬a ≤ b }) ↔ Bounded (· ≥ ·) s := @bounded_le_inter_not_le αᵒᵈ s _ a theorem unbounded_ge_inter_not_ge [SemilatticeInf α] (a : α) : Unbounded (· ≥ ·) (s ∩ { b | ¬a ≤ b }) ↔ Unbounded (· ≥ ·) s := @unbounded_le_inter_not_le αᵒᵈ s _ a theorem bounded_ge_inter_gt [LinearOrder α] (a : α) : Bounded (· ≥ ·) (s ∩ { b | b < a }) ↔ Bounded (· ≥ ·) s := @bounded_le_inter_lt αᵒᵈ s _ a theorem unbounded_ge_inter_gt [LinearOrder α] (a : α) : Unbounded (· ≥ ·) (s ∩ { b | b < a }) ↔ Unbounded (· ≥ ·) s := @unbounded_le_inter_lt αᵒᵈ s _ a theorem bounded_ge_inter_ge [LinearOrder α] (a : α) : Bounded (· ≥ ·) (s ∩ { b | b ≤ a }) ↔ Bounded (· ≥ ·) s := @bounded_le_inter_le αᵒᵈ s _ a theorem unbounded_ge_iff_unbounded_inter_ge [LinearOrder α] (a : α) : Unbounded (· ≥ ·) (s ∩ { b | b ≤ a }) ↔ Unbounded (· ≥ ·) s := @unbounded_le_inter_le αᵒᵈ s _ a /-! #### Greater than -/ theorem bounded_gt_inter_not_gt [SemilatticeInf α] (a : α) : Bounded (· > ·) (s ∩ { b | ¬a < b }) ↔ Bounded (· > ·) s := @bounded_lt_inter_not_lt αᵒᵈ s _ a theorem unbounded_gt_inter_not_gt [SemilatticeInf α] (a : α) : Unbounded (· > ·) (s ∩ { b | ¬a < b }) ↔ Unbounded (· > ·) s := @unbounded_lt_inter_not_lt αᵒᵈ s _ a theorem bounded_gt_inter_ge [LinearOrder α] (a : α) : Bounded (· > ·) (s ∩ { b | b ≤ a }) ↔ Bounded (· > ·) s := @bounded_lt_inter_le αᵒᵈ s _ a theorem unbounded_inter_ge [LinearOrder α] (a : α) : Unbounded (· > ·) (s ∩ { b | b ≤ a }) ↔ Unbounded (· > ·) s := @unbounded_lt_inter_le αᵒᵈ s _ a theorem bounded_gt_inter_gt [LinearOrder α] [NoMinOrder α] (a : α) : Bounded (· > ·) (s ∩ { b | b < a }) ↔ Bounded (· > ·) s := @bounded_lt_inter_lt αᵒᵈ s _ _ a theorem unbounded_gt_inter_gt [LinearOrder α] [NoMinOrder α] (a : α) : Unbounded (· > ·) (s ∩ { b | b < a }) ↔ Unbounded (· > ·) s := @unbounded_lt_inter_lt αᵒᵈ s _ _ a end Set
.lake/packages/mathlib/Mathlib/Order/TypeTags.lean
import Mathlib.Order.Notation /-! # Order-related type synonyms In this file we define `WithBot`, `WithTop`, `ENat`, and `PNat`. The definitions were moved to this file without any theory so that, e.g., `Data/Countable/Basic` can prove `Countable ENat` without exploding its imports. -/ variable {α : Type*} /-- Attach `⊥` to a type. -/ def WithBot (α : Type*) := Option α namespace WithBot instance [Repr α] : Repr (WithBot α) := ⟨fun o _ => match o with | none => "⊥" | some a => "↑" ++ repr a⟩ /-- The canonical map from `α` into `WithBot α` -/ @[coe, match_pattern] def some : α → WithBot α := Option.some instance coe : Coe α (WithBot α) := ⟨some⟩ instance bot : Bot (WithBot α) := ⟨none⟩ instance inhabited : Inhabited (WithBot α) := ⟨⊥⟩ /-- Recursor for `WithBot` using the preferred forms `⊥` and `↑a`. -/ @[elab_as_elim, induction_eliminator, cases_eliminator] def recBotCoe {C : WithBot α → Sort*} (bot : C ⊥) (coe : ∀ a : α, C a) : ∀ n : WithBot α, C n | ⊥ => bot | (a : α) => coe a @[simp] theorem recBotCoe_bot {C : WithBot α → Sort*} (d : C ⊥) (f : ∀ a : α, C a) : @recBotCoe _ C d f ⊥ = d := rfl @[simp] theorem recBotCoe_coe {C : WithBot α → Sort*} (d : C ⊥) (f : ∀ a : α, C a) (x : α) : @recBotCoe _ C d f ↑x = f x := rfl end WithBot --TODO(Mario): Construct using order dual on `WithBot` /-- Attach `⊤` to a type. -/ def WithTop (α : Type*) := Option α namespace WithTop instance [Repr α] : Repr (WithTop α) := ⟨fun o _ => match o with | none => "⊤" | some a => "↑" ++ repr a⟩ /-- The canonical map from `α` into `WithTop α` -/ @[coe, match_pattern] def some : α → WithTop α := Option.some instance coeTC : CoeTC α (WithTop α) := ⟨some⟩ instance top : Top (WithTop α) := ⟨none⟩ instance inhabited : Inhabited (WithTop α) := ⟨⊤⟩ /-- Recursor for `WithTop` using the preferred forms `⊤` and `↑a`. -/ @[elab_as_elim, induction_eliminator, cases_eliminator] def recTopCoe {C : WithTop α → Sort*} (top : C ⊤) (coe : ∀ a : α, C a) : ∀ n : WithTop α, C n | none => top | Option.some a => coe a @[simp] theorem recTopCoe_top {C : WithTop α → Sort*} (d : C ⊤) (f : ∀ a : α, C a) : @recTopCoe _ C d f ⊤ = d := rfl @[simp] theorem recTopCoe_coe {C : WithTop α → Sort*} (d : C ⊤) (f : ∀ a : α, C a) (x : α) : @recTopCoe _ C d f ↑x = f x := rfl end WithTop
.lake/packages/mathlib/Mathlib/Order/Directed.lean
import Mathlib.Data.Set.Image /-! # Directed indexed families and sets This file defines directed indexed families and directed sets. An indexed family/set is directed iff each pair of elements has a shared upper bound. ## Main declarations * `Directed r f`: Predicate stating that the indexed family `f` is `r`-directed. * `DirectedOn r s`: Predicate stating that the set `s` is `r`-directed. * `IsDirected α r`: Prop-valued mixin stating that `α` is `r`-directed. Follows the style of the unbundled relation classes such as `IsTotal`. ## TODO Define connected orders (the transitive symmetric closure of `≤` is everything) and show that (co)directed orders are connected. ## References * [Gierz et al, *A Compendium of Continuous Lattices*][GierzEtAl1980] -/ open Function universe u v w variable {α : Type u} {β : Type v} {ι : Sort w} (r r' s : α → α → Prop) /-- Local notation for a relation -/ local infixl:50 " ≼ " => r /-- A family of elements of α is directed (with respect to a relation `≼` on α) if there is a member of the family `≼`-above any pair in the family. -/ def Directed (f : ι → α) := ∀ x y, ∃ z, f x ≼ f z ∧ f y ≼ f z /-- A subset of α is directed if there is an element of the set `≼`-above any pair of elements in the set. -/ def DirectedOn (s : Set α) := ∀ x ∈ s, ∀ y ∈ s, ∃ z ∈ s, x ≼ z ∧ y ≼ z variable {r r'} theorem directedOn_iff_directed {s} : @DirectedOn α r s ↔ Directed r (Subtype.val : s → α) := by simp only [DirectedOn, Directed, Subtype.exists, exists_and_left, exists_prop, Subtype.forall] exact forall₂_congr fun x _ => by simp [And.comm, and_assoc] alias ⟨DirectedOn.directed_val, _⟩ := directedOn_iff_directed theorem directedOn_range {f : ι → α} : Directed r f ↔ DirectedOn r (Set.range f) := by simp_rw [Directed, DirectedOn, Set.forall_mem_range, Set.exists_range_iff] protected alias ⟨Directed.directedOn_range, _⟩ := directedOn_range theorem directedOn_image {s : Set β} {f : β → α} : DirectedOn r (f '' s) ↔ DirectedOn (f ⁻¹'o r) s := by simp only [DirectedOn, Set.mem_image, exists_exists_and_eq_and, forall_exists_index, and_imp, forall_apply_eq_imp_iff₂, Order.Preimage] theorem DirectedOn.mono' {s : Set α} (hs : DirectedOn r s) (h : ∀ ⦃a⦄, a ∈ s → ∀ ⦃b⦄, b ∈ s → r a b → r' a b) : DirectedOn r' s := fun _ hx _ hy => let ⟨z, hz, hxz, hyz⟩ := hs _ hx _ hy ⟨z, hz, h hx hz hxz, h hy hz hyz⟩ theorem DirectedOn.mono {s : Set α} (h : DirectedOn r s) (H : ∀ ⦃a b⦄, r a b → r' a b) : DirectedOn r' s := h.mono' fun _ _ _ _ h ↦ H h theorem directed_comp {ι} {f : ι → β} {g : β → α} : Directed r (g ∘ f) ↔ Directed (g ⁻¹'o r) f := Iff.rfl theorem Directed.mono {s : α → α → Prop} {ι} {f : ι → α} (H : ∀ a b, r a b → s a b) (h : Directed r f) : Directed s f := fun a b => let ⟨c, h₁, h₂⟩ := h a b ⟨c, H _ _ h₁, H _ _ h₂⟩ theorem Directed.mono_comp (r : α → α → Prop) {ι} {rb : β → β → Prop} {g : α → β} {f : ι → α} (hg : ∀ ⦃x y⦄, r x y → rb (g x) (g y)) (hf : Directed r f) : Directed rb (g ∘ f) := directed_comp.2 <| hf.mono hg theorem DirectedOn.mono_comp {r : α → α → Prop} {rb : β → β → Prop} {g : α → β} {s : Set α} (hg : ∀ ⦃x y⦄, r x y → rb (g x) (g y)) (hf : DirectedOn r s) : DirectedOn rb (g '' s) := directedOn_image.mpr (hf.mono hg) lemma directedOn_onFun_iff {r : α → α → Prop} {f : β → α} {s : Set β} : DirectedOn (r on f) s ↔ DirectedOn r (f '' s) := by refine ⟨DirectedOn.mono_comp (by simp), fun h x hx y hy ↦ ?_⟩ obtain ⟨_, ⟨z, hz, rfl⟩, hz'⟩ := h (f x) (Set.mem_image_of_mem f hx) (f y) (Set.mem_image_of_mem f hy) grind /-- A set stable by supremum is `≤`-directed. -/ theorem directedOn_of_sup_mem [SemilatticeSup α] {S : Set α} (H : ∀ ⦃i j⦄, i ∈ S → j ∈ S → i ⊔ j ∈ S) : DirectedOn (· ≤ ·) S := fun a ha b hb => ⟨a ⊔ b, H ha hb, le_sup_left, le_sup_right⟩ theorem Directed.extend_bot [Preorder α] [OrderBot α] {e : ι → β} {f : ι → α} (hf : Directed (· ≤ ·) f) (he : Function.Injective e) : Directed (· ≤ ·) (Function.extend e f ⊥) := by intro a b rcases (em (∃ i, e i = a)).symm with (ha | ⟨i, rfl⟩) · use b simp [Function.extend_apply' _ _ _ ha] rcases (em (∃ i, e i = b)).symm with (hb | ⟨j, rfl⟩) · use e i simp [Function.extend_apply' _ _ _ hb] rcases hf i j with ⟨k, hi, hj⟩ use e k simp only [he.extend_apply, *, true_and] /-- A set stable by infimum is `≥`-directed. -/ theorem directedOn_of_inf_mem [SemilatticeInf α] {S : Set α} (H : ∀ ⦃i j⦄, i ∈ S → j ∈ S → i ⊓ j ∈ S) : DirectedOn (· ≥ ·) S := directedOn_of_sup_mem (α := αᵒᵈ) H theorem IsTotal.directed [IsTotal α r] (f : ι → α) : Directed r f := fun i j => Or.casesOn (total_of r (f i) (f j)) (fun h => ⟨j, h, refl _⟩) fun h => ⟨i, refl _, h⟩ /-- `IsDirected α r` states that for any elements `a`, `b` there exists an element `c` such that `r a c` and `r b c`. -/ class IsDirected (α : Type*) (r : α → α → Prop) : Prop where /-- For every pair of elements `a` and `b` there is a `c` such that `r a c` and `r b c` -/ directed (a b : α) : ∃ c, r a c ∧ r b c theorem directed_of (r : α → α → Prop) [IsDirected α r] (a b : α) : ∃ c, r a c ∧ r b c := IsDirected.directed _ _ theorem directed_of₃ (r : α → α → Prop) [IsDirected α r] [IsTrans α r] (a b c : α) : ∃ d, r a d ∧ r b d ∧ r c d := have ⟨e, hae, hbe⟩ := directed_of r a b have ⟨f, hef, hcf⟩ := directed_of r e c ⟨f, Trans.trans hae hef, Trans.trans hbe hef, hcf⟩ theorem directed_id [IsDirected α r] : Directed r id := directed_of r theorem directed_id_iff : Directed r id ↔ IsDirected α r := ⟨fun h => ⟨h⟩, @directed_id _ _⟩ theorem directedOn_univ [IsDirected α r] : DirectedOn r Set.univ := fun a _ b _ => let ⟨c, hc⟩ := directed_of r a b ⟨c, trivial, hc⟩ theorem directedOn_univ_iff : DirectedOn r Set.univ ↔ IsDirected α r := ⟨fun h => ⟨fun a b => let ⟨c, _, hc⟩ := h a trivial b trivial ⟨c, hc⟩⟩, @directedOn_univ _ _⟩ -- see Note [lower instance priority] instance (priority := 100) IsTotal.to_isDirected [IsTotal α r] : IsDirected α r := directed_id_iff.1 <| IsTotal.directed _ theorem isDirected_mono [IsDirected α r] (h : ∀ ⦃a b⦄, r a b → s a b) : IsDirected α s := ⟨fun a b => let ⟨c, ha, hb⟩ := IsDirected.directed a b ⟨c, h ha, h hb⟩⟩ theorem exists_ge_ge [LE α] [IsDirected α (· ≤ ·)] (a b : α) : ∃ c, a ≤ c ∧ b ≤ c := directed_of (· ≤ ·) a b theorem exists_le_le [LE α] [IsDirected α (· ≥ ·)] (a b : α) : ∃ c, c ≤ a ∧ c ≤ b := directed_of (· ≥ ·) a b instance OrderDual.isDirected_ge [LE α] [IsDirected α (· ≤ ·)] : IsDirected αᵒᵈ (· ≥ ·) := by assumption instance OrderDual.isDirected_le [LE α] [IsDirected α (· ≥ ·)] : IsDirected αᵒᵈ (· ≤ ·) := by assumption /-- A monotone function on an upwards-directed type is directed. -/ theorem directed_of_isDirected_le [LE α] [IsDirected α (· ≤ ·)] {f : α → β} {r : β → β → Prop} (H : ∀ ⦃i j⦄, i ≤ j → r (f i) (f j)) : Directed r f := directed_id.mono_comp _ H theorem Monotone.directed_le [Preorder α] [IsDirected α (· ≤ ·)] [Preorder β] {f : α → β} : Monotone f → Directed (· ≤ ·) f := directed_of_isDirected_le theorem Antitone.directed_ge [Preorder α] [IsDirected α (· ≤ ·)] [Preorder β] {f : α → β} (hf : Antitone f) : Directed (· ≥ ·) f := directed_of_isDirected_le hf /-- An antitone function on a downwards-directed type is directed. -/ theorem directed_of_isDirected_ge [LE α] [IsDirected α (· ≥ ·)] {r : β → β → Prop} {f : α → β} (hf : ∀ a₁ a₂, a₁ ≤ a₂ → r (f a₂) (f a₁)) : Directed r f := directed_of_isDirected_le (α := αᵒᵈ) fun _ _ ↦ hf _ _ theorem Monotone.directed_ge [Preorder α] [IsDirected α (· ≥ ·)] [Preorder β] {f : α → β} (hf : Monotone f) : Directed (· ≥ ·) f := directed_of_isDirected_ge hf theorem Antitone.directed_le [Preorder α] [IsDirected α (· ≥ ·)] [Preorder β] {f : α → β} (hf : Antitone f) : Directed (· ≤ ·) f := directed_of_isDirected_ge hf section Reflexive protected theorem DirectedOn.insert (h : Reflexive r) (a : α) {s : Set α} (hd : DirectedOn r s) (ha : ∀ b ∈ s, ∃ c ∈ s, a ≼ c ∧ b ≼ c) : DirectedOn r (insert a s) := by rintro x (rfl | hx) y (rfl | hy) · exact ⟨y, Set.mem_insert _ _, h _, h _⟩ · obtain ⟨w, hws, hwr⟩ := ha y hy exact ⟨w, Set.mem_insert_of_mem _ hws, hwr⟩ · obtain ⟨w, hws, hwr⟩ := ha x hx exact ⟨w, Set.mem_insert_of_mem _ hws, hwr.symm⟩ · obtain ⟨w, hws, hwr⟩ := hd x hx y hy exact ⟨w, Set.mem_insert_of_mem _ hws, hwr⟩ theorem directedOn_singleton (h : Reflexive r) (a : α) : DirectedOn r ({a} : Set α) := fun x hx _ hy => ⟨x, hx, h _, hx.symm ▸ hy.symm ▸ h _⟩ theorem directedOn_pair (h : Reflexive r) {a b : α} (hab : a ≼ b) : DirectedOn r ({a, b} : Set α) := (directedOn_singleton h _).insert h _ fun c hc => ⟨c, hc, hc.symm ▸ hab, h _⟩ theorem directedOn_pair' (h : Reflexive r) {a b : α} (hab : a ≼ b) : DirectedOn r ({b, a} : Set α) := by rw [Set.pair_comm] apply directedOn_pair h hab end Reflexive section Preorder variable [Preorder α] {a : α} protected theorem IsMin.isBot [IsDirected α (· ≥ ·)] (h : IsMin a) : IsBot a := fun b => let ⟨_, hca, hcb⟩ := exists_le_le a b (h hca).trans hcb protected theorem IsMax.isTop [IsDirected α (· ≤ ·)] (h : IsMax a) : IsTop a := h.toDual.isBot lemma DirectedOn.is_bot_of_is_min {s : Set α} (hd : DirectedOn (· ≥ ·) s) {m} (hm : m ∈ s) (hmin : ∀ a ∈ s, a ≤ m → m ≤ a) : ∀ a ∈ s, m ≤ a := fun a as => let ⟨x, xs, xm, xa⟩ := hd m hm a as (hmin x xs xm).trans xa lemma DirectedOn.is_top_of_is_max {s : Set α} (hd : DirectedOn (· ≤ ·) s) {m} (hm : m ∈ s) (hmax : ∀ a ∈ s, m ≤ a → a ≤ m) : ∀ a ∈ s, a ≤ m := @DirectedOn.is_bot_of_is_min αᵒᵈ _ s hd m hm hmax theorem isTop_or_exists_gt [IsDirected α (· ≤ ·)] (a : α) : IsTop a ∨ ∃ b, a < b := (em (IsMax a)).imp IsMax.isTop not_isMax_iff.mp theorem isBot_or_exists_lt [IsDirected α (· ≥ ·)] (a : α) : IsBot a ∨ ∃ b, b < a := @isTop_or_exists_gt αᵒᵈ _ _ a theorem isBot_iff_isMin [IsDirected α (· ≥ ·)] : IsBot a ↔ IsMin a := ⟨IsBot.isMin, IsMin.isBot⟩ theorem isTop_iff_isMax [IsDirected α (· ≤ ·)] : IsTop a ↔ IsMax a := ⟨IsTop.isMax, IsMax.isTop⟩ end Preorder section PartialOrder variable [PartialOrder β] section Nontrivial variable [Nontrivial β] variable (β) in theorem exists_lt_of_directed_ge [IsDirected β (· ≥ ·)] : ∃ a b : β, a < b := by rcases exists_pair_ne β with ⟨a, b, hne⟩ rcases isBot_or_exists_lt a with (ha | ⟨c, hc⟩) exacts [⟨a, b, (ha b).lt_of_ne hne⟩, ⟨_, _, hc⟩] variable (β) in theorem exists_lt_of_directed_le [IsDirected β (· ≤ ·)] : ∃ a b : β, a < b := let ⟨a, b, h⟩ := exists_lt_of_directed_ge βᵒᵈ ⟨b, a, h⟩ protected theorem IsMin.not_isMax [IsDirected β (· ≥ ·)] {b : β} (hb : IsMin b) : ¬ IsMax b := by intro hb' obtain ⟨a, c, hac⟩ := exists_lt_of_directed_ge β have := hb.isBot a obtain rfl := (hb' <| this).antisymm this exact hb'.not_lt hac protected theorem IsMin.not_isMax' [IsDirected β (· ≤ ·)] {b : β} (hb : IsMin b) : ¬ IsMax b := fun hb' ↦ hb'.toDual.not_isMax hb.toDual protected theorem IsMax.not_isMin [IsDirected β (· ≤ ·)] {b : β} (hb : IsMax b) : ¬ IsMin b := fun hb' ↦ hb.toDual.not_isMax hb'.toDual protected theorem IsMax.not_isMin' [IsDirected β (· ≥ ·)] {b : β} (hb : IsMax b) : ¬ IsMin b := fun hb' ↦ hb'.toDual.not_isMin hb.toDual end Nontrivial variable [Preorder α] {f : α → β} {s : Set α} -- TODO: Generalise the following two lemmas to connected orders /-- If `f` is monotone and antitone on a directed order, then `f` is constant. -/ lemma constant_of_monotone_antitone [IsDirected α (· ≤ ·)] (hf : Monotone f) (hf' : Antitone f) (a b : α) : f a = f b := by obtain ⟨c, hac, hbc⟩ := exists_ge_ge a b exact le_antisymm ((hf hac).trans <| hf' hbc) ((hf hbc).trans <| hf' hac) /-- If `f` is monotone and antitone on a directed set `s`, then `f` is constant on `s`. -/ lemma constant_of_monotoneOn_antitoneOn (hf : MonotoneOn f s) (hf' : AntitoneOn f s) (hs : DirectedOn (· ≤ ·) s) : ∀ ⦃a⦄, a ∈ s → ∀ ⦃b⦄, b ∈ s → f a = f b := by rintro a ha b hb obtain ⟨c, hc, hac, hbc⟩ := hs _ ha _ hb exact le_antisymm ((hf ha hc hac).trans <| hf' hb hc hbc) ((hf hb hc hbc).trans <| hf' ha hc hac) end PartialOrder -- see Note [lower instance priority] instance (priority := 100) SemilatticeSup.to_isDirected_le [SemilatticeSup α] : IsDirected α (· ≤ ·) := ⟨fun a b => ⟨a ⊔ b, le_sup_left, le_sup_right⟩⟩ -- see Note [lower instance priority] instance (priority := 100) SemilatticeInf.to_isDirected_ge [SemilatticeInf α] : IsDirected α (· ≥ ·) := ⟨fun a b => ⟨a ⊓ b, inf_le_left, inf_le_right⟩⟩ -- see Note [lower instance priority] instance (priority := 100) OrderTop.to_isDirected_le [LE α] [OrderTop α] : IsDirected α (· ≤ ·) := ⟨fun _ _ => ⟨⊤, le_top _, le_top _⟩⟩ -- see Note [lower instance priority] instance (priority := 100) OrderBot.to_isDirected_ge [LE α] [OrderBot α] : IsDirected α (· ≥ ·) := ⟨fun _ _ => ⟨⊥, bot_le _, bot_le _⟩⟩ namespace DirectedOn section Pi variable {ι : Type*} {α : ι → Type*} {r : (i : ι) → α i → α i → Prop} lemma proj {d : Set (Π i, α i)} (hd : DirectedOn (fun x y => ∀ i, r i (x i) (y i)) d) (i : ι) : DirectedOn (r i) ((fun a => a i) '' d) := DirectedOn.mono_comp (fun _ _ h => h) (mono hd fun ⦃_ _⦄ h ↦ h i) lemma pi {d : (i : ι) → Set (α i)} (hd : ∀ (i : ι), DirectedOn (r i) (d i)) : DirectedOn (fun x y => ∀ i, r i (x i) (y i)) (Set.pi Set.univ d) := by intro a ha b hb choose f hfd haf hbf using fun i => hd i (a i) (ha i trivial) (b i) (hb i trivial) exact ⟨f, fun i _ => hfd i, haf, hbf⟩ end Pi section Prod variable {r₂ : β → β → Prop} /-- Local notation for a relation -/ local infixl:50 " ≼₁ " => r /-- Local notation for a relation -/ local infixl:50 " ≼₂ " => r₂ lemma fst {d : Set (α × β)} (hd : DirectedOn (fun p q ↦ p.1 ≼₁ q.1 ∧ p.2 ≼₂ q.2) d) : DirectedOn (· ≼₁ ·) (Prod.fst '' d) := DirectedOn.mono_comp (fun ⦃_ _⦄ h ↦ h) (mono hd fun ⦃_ _⦄ h ↦ h.1) lemma snd {d : Set (α × β)} (hd : DirectedOn (fun p q ↦ p.1 ≼₁ q.1 ∧ p.2 ≼₂ q.2) d) : DirectedOn (· ≼₂ ·) (Prod.snd '' d) := DirectedOn.mono_comp (fun ⦃_ _⦄ h ↦ h) (mono hd fun ⦃_ _⦄ h ↦ h.2) lemma prod {d₁ : Set α} {d₂ : Set β} (h₁ : DirectedOn (· ≼₁ ·) d₁) (h₂ : DirectedOn (· ≼₂ ·) d₂) : DirectedOn (fun p q ↦ p.1 ≼₁ q.1 ∧ p.2 ≼₂ q.2) (d₁ ×ˢ d₂) := fun _ hpd _ hqd => by obtain ⟨r₁, hdr₁, hpr₁, hqr₁⟩ := h₁ _ hpd.1 _ hqd.1 obtain ⟨r₂, hdr₂, hpr₂, hqr₂⟩ := h₂ _ hpd.2 _ hqd.2 exact ⟨⟨r₁, r₂⟩, ⟨hdr₁, hdr₂⟩, ⟨hpr₁, hpr₂⟩, ⟨hqr₁, hqr₂⟩⟩ end Prod end DirectedOn
.lake/packages/mathlib/Mathlib/Order/ModularLattice.lean
import Mathlib.Data.Set.Monotone import Mathlib.Order.Cover import Mathlib.Order.LatticeIntervals import Mathlib.Order.GaloisConnection.Defs /-! # Modular Lattices This file defines (semi)modular lattices, a kind of lattice useful in algebra. For examples, look to the subobject lattices of abelian groups, submodules, and ideals, or consider any distributive lattice. ## Typeclasses We define (semi)modularity typeclasses as Prop-valued mixins. * `IsWeakUpperModularLattice`: Weakly upper modular lattices. Lattice where `a ⊔ b` covers `a` and `b` if `a` and `b` both cover `a ⊓ b`. * `IsWeakLowerModularLattice`: Weakly lower modular lattices. Lattice where `a` and `b` cover `a ⊓ b` if `a ⊔ b` covers both `a` and `b` * `IsUpperModularLattice`: Upper modular lattices. Lattices where `a ⊔ b` covers `a` if `b` covers `a ⊓ b`. * `IsLowerModularLattice`: Lower modular lattices. Lattices where `a` covers `a ⊓ b` if `a ⊔ b` covers `b`. - `IsModularLattice`: Modular lattices. Lattices where `a ≤ c → (a ⊔ b) ⊓ c = a ⊔ (b ⊓ c)`. We only require an inequality because the other direction holds in all lattices. ## Main Definitions - `infIccOrderIsoIccSup` gives an order isomorphism between the intervals `[a ⊓ b, a]` and `[b, a ⊔ b]`. This corresponds to the diamond (or second) isomorphism theorems of algebra. ## Main Results - `isModularLattice_iff_inf_sup_inf_assoc`: Modularity is equivalent to the `inf_sup_inf_assoc`: `(x ⊓ z) ⊔ (y ⊓ z) = ((x ⊓ z) ⊔ y) ⊓ z` - `DistribLattice.isModularLattice`: Distributive lattices are modular. ## References * [Manfred Stern, *Semimodular lattices. {Theory} and applications*][stern2009] * [Wikipedia, *Modular Lattice*][https://en.wikipedia.org/wiki/Modular_lattice] ## TODO - Relate atoms and coatoms in modular lattices -/ open Set variable {α : Type*} /-- A weakly upper modular lattice is a lattice where `a ⊔ b` covers `a` and `b` if `a` and `b` both cover `a ⊓ b`. -/ class IsWeakUpperModularLattice (α : Type*) [Lattice α] : Prop where /-- `a ⊔ b` covers `a` and `b` if `a` and `b` both cover `a ⊓ b`. -/ covBy_sup_of_inf_covBy_covBy {a b : α} : a ⊓ b ⋖ a → a ⊓ b ⋖ b → a ⋖ a ⊔ b /-- A weakly lower modular lattice is a lattice where `a` and `b` cover `a ⊓ b` if `a ⊔ b` covers both `a` and `b`. -/ class IsWeakLowerModularLattice (α : Type*) [Lattice α] : Prop where /-- `a` and `b` cover `a ⊓ b` if `a ⊔ b` covers both `a` and `b` -/ inf_covBy_of_covBy_covBy_sup {a b : α} : a ⋖ a ⊔ b → b ⋖ a ⊔ b → a ⊓ b ⋖ a /-- An upper modular lattice, aka semimodular lattice, is a lattice where `a ⊔ b` covers `a` and `b` if either `a` or `b` covers `a ⊓ b`. -/ class IsUpperModularLattice (α : Type*) [Lattice α] : Prop where /-- `a ⊔ b` covers `a` and `b` if either `a` or `b` covers `a ⊓ b` -/ covBy_sup_of_inf_covBy {a b : α} : a ⊓ b ⋖ a → b ⋖ a ⊔ b /-- A lower modular lattice is a lattice where `a` and `b` both cover `a ⊓ b` if `a ⊔ b` covers either `a` or `b`. -/ class IsLowerModularLattice (α : Type*) [Lattice α] : Prop where /-- `a` and `b` both cover `a ⊓ b` if `a ⊔ b` covers either `a` or `b` -/ inf_covBy_of_covBy_sup {a b : α} : a ⋖ a ⊔ b → a ⊓ b ⋖ b /-- A modular lattice is one with a limited associativity between `⊓` and `⊔`. -/ class IsModularLattice (α : Type*) [Lattice α] : Prop where /-- Whenever `x ≤ z`, then for any `y`, `(x ⊔ y) ⊓ z ≤ x ⊔ (y ⊓ z)` -/ sup_inf_le_assoc_of_le : ∀ {x : α} (y : α) {z : α}, x ≤ z → (x ⊔ y) ⊓ z ≤ x ⊔ y ⊓ z section WeakUpperModular variable [Lattice α] [IsWeakUpperModularLattice α] {a b : α} theorem covBy_sup_of_inf_covBy_of_inf_covBy_left : a ⊓ b ⋖ a → a ⊓ b ⋖ b → a ⋖ a ⊔ b := IsWeakUpperModularLattice.covBy_sup_of_inf_covBy_covBy theorem covBy_sup_of_inf_covBy_of_inf_covBy_right : a ⊓ b ⋖ a → a ⊓ b ⋖ b → b ⋖ a ⊔ b := by rw [inf_comm, sup_comm] exact fun ha hb => covBy_sup_of_inf_covBy_of_inf_covBy_left hb ha alias CovBy.sup_of_inf_of_inf_left := covBy_sup_of_inf_covBy_of_inf_covBy_left alias CovBy.sup_of_inf_of_inf_right := covBy_sup_of_inf_covBy_of_inf_covBy_right instance : IsWeakLowerModularLattice (OrderDual α) := ⟨fun ha hb => (ha.ofDual.sup_of_inf_of_inf_left hb.ofDual).toDual⟩ end WeakUpperModular section WeakLowerModular variable [Lattice α] [IsWeakLowerModularLattice α] {a b : α} theorem inf_covBy_of_covBy_sup_of_covBy_sup_left : a ⋖ a ⊔ b → b ⋖ a ⊔ b → a ⊓ b ⋖ a := IsWeakLowerModularLattice.inf_covBy_of_covBy_covBy_sup theorem inf_covBy_of_covBy_sup_of_covBy_sup_right : a ⋖ a ⊔ b → b ⋖ a ⊔ b → a ⊓ b ⋖ b := by rw [sup_comm, inf_comm] exact fun ha hb => inf_covBy_of_covBy_sup_of_covBy_sup_left hb ha alias CovBy.inf_of_sup_of_sup_left := inf_covBy_of_covBy_sup_of_covBy_sup_left alias CovBy.inf_of_sup_of_sup_right := inf_covBy_of_covBy_sup_of_covBy_sup_right instance : IsWeakUpperModularLattice (OrderDual α) := ⟨fun ha hb => (ha.ofDual.inf_of_sup_of_sup_left hb.ofDual).toDual⟩ end WeakLowerModular section UpperModular variable [Lattice α] [IsUpperModularLattice α] {a b : α} theorem covBy_sup_of_inf_covBy_left : a ⊓ b ⋖ a → b ⋖ a ⊔ b := IsUpperModularLattice.covBy_sup_of_inf_covBy theorem covBy_sup_of_inf_covBy_right : a ⊓ b ⋖ b → a ⋖ a ⊔ b := by rw [sup_comm, inf_comm] exact covBy_sup_of_inf_covBy_left alias CovBy.sup_of_inf_left := covBy_sup_of_inf_covBy_left alias CovBy.sup_of_inf_right := covBy_sup_of_inf_covBy_right -- See note [lower instance priority] instance (priority := 100) IsUpperModularLattice.to_isWeakUpperModularLattice : IsWeakUpperModularLattice α := ⟨fun _ => CovBy.sup_of_inf_right⟩ instance : IsLowerModularLattice (OrderDual α) := ⟨fun h => h.ofDual.sup_of_inf_left.toDual⟩ end UpperModular section LowerModular variable [Lattice α] [IsLowerModularLattice α] {a b : α} theorem inf_covBy_of_covBy_sup_left : a ⋖ a ⊔ b → a ⊓ b ⋖ b := IsLowerModularLattice.inf_covBy_of_covBy_sup theorem inf_covBy_of_covBy_sup_right : b ⋖ a ⊔ b → a ⊓ b ⋖ a := by rw [inf_comm, sup_comm] exact inf_covBy_of_covBy_sup_left alias CovBy.inf_of_sup_left := inf_covBy_of_covBy_sup_left alias CovBy.inf_of_sup_right := inf_covBy_of_covBy_sup_right -- See note [lower instance priority] instance (priority := 100) IsLowerModularLattice.to_isWeakLowerModularLattice : IsWeakLowerModularLattice α := ⟨fun _ => CovBy.inf_of_sup_right⟩ instance : IsUpperModularLattice (OrderDual α) := ⟨fun h => h.ofDual.inf_of_sup_left.toDual⟩ end LowerModular section IsModularLattice variable [Lattice α] [IsModularLattice α] theorem sup_inf_assoc_of_le {x : α} (y : α) {z : α} (h : x ≤ z) : (x ⊔ y) ⊓ z = x ⊔ y ⊓ z := le_antisymm (IsModularLattice.sup_inf_le_assoc_of_le y h) (le_inf (sup_le_sup_left inf_le_left _) (sup_le h inf_le_right)) theorem IsModularLattice.inf_sup_inf_assoc {x y z : α} : x ⊓ z ⊔ y ⊓ z = (x ⊓ z ⊔ y) ⊓ z := (sup_inf_assoc_of_le y inf_le_right).symm theorem inf_sup_assoc_of_le {x : α} (y : α) {z : α} (h : z ≤ x) : x ⊓ y ⊔ z = x ⊓ (y ⊔ z) := by rw [inf_comm, sup_comm, ← sup_inf_assoc_of_le y h, inf_comm, sup_comm] instance : IsModularLattice αᵒᵈ := ⟨fun y z xz => le_of_eq (by rw [inf_comm, sup_comm, eq_comm, inf_comm, sup_comm] exact @sup_inf_assoc_of_le α _ _ _ y _ xz)⟩ variable {x y z : α} theorem IsModularLattice.sup_inf_sup_assoc : (x ⊔ z) ⊓ (y ⊔ z) = (x ⊔ z) ⊓ y ⊔ z := @IsModularLattice.inf_sup_inf_assoc αᵒᵈ _ _ _ _ _ theorem eq_of_le_of_inf_le_of_le_sup (hxy : x ≤ y) (hinf : y ⊓ z ≤ x) (hsup : y ≤ x ⊔ z) : x = y := by refine hxy.antisymm ?_ rw [← inf_eq_right, sup_inf_assoc_of_le _ hxy] at hsup rwa [← hsup, sup_le_iff, and_iff_right rfl.le, inf_comm] theorem eq_of_le_of_inf_le_of_sup_le (hxy : x ≤ y) (hinf : y ⊓ z ≤ x ⊓ z) (hsup : y ⊔ z ≤ x ⊔ z) : x = y := eq_of_le_of_inf_le_of_le_sup hxy (hinf.trans inf_le_left) (le_sup_left.trans hsup) theorem sup_lt_sup_of_lt_of_inf_le_inf (hxy : x < y) (hinf : y ⊓ z ≤ x ⊓ z) : x ⊔ z < y ⊔ z := lt_of_le_of_ne (sup_le_sup_right (le_of_lt hxy) _) fun hsup => ne_of_lt hxy <| eq_of_le_of_inf_le_of_sup_le (le_of_lt hxy) hinf (le_of_eq hsup.symm) theorem inf_lt_inf_of_lt_of_sup_le_sup (hxy : x < y) (hinf : y ⊔ z ≤ x ⊔ z) : x ⊓ z < y ⊓ z := sup_lt_sup_of_lt_of_inf_le_inf (α := αᵒᵈ) hxy hinf theorem strictMono_inf_prod_sup : StrictMono fun x ↦ (x ⊓ z, x ⊔ z) := fun _x _y hxy ↦ ⟨⟨inf_le_inf_right _ hxy.le, sup_le_sup_right hxy.le _⟩, fun ⟨inf_le, sup_le⟩ ↦ (sup_lt_sup_of_lt_of_inf_le_inf hxy inf_le).not_ge sup_le⟩ /-- A generalization of the theorem that if `N` is a submodule of `M` and `N` and `M / N` are both Artinian, then `M` is Artinian. -/ theorem wellFounded_lt_exact_sequence {β γ : Type*} [Preorder β] [Preorder γ] [h₁ : WellFoundedLT β] [h₂ : WellFoundedLT γ] (K : α) (f₁ : β → α) (f₂ : α → β) (g₁ : γ → α) (g₂ : α → γ) (gci : GaloisCoinsertion f₁ f₂) (gi : GaloisInsertion g₂ g₁) (hf : ∀ a, f₁ (f₂ a) = a ⊓ K) (hg : ∀ a, g₁ (g₂ a) = a ⊔ K) : WellFoundedLT α := StrictMono.wellFoundedLT (f := fun A ↦ (f₂ A, g₂ A)) fun A B hAB ↦ by simp only [Prod.le_def, lt_iff_le_not_ge, ← gci.l_le_l_iff, ← gi.u_le_u_iff, hf, hg] exact strictMono_inf_prod_sup hAB /-- A generalization of the theorem that if `N` is a submodule of `M` and `N` and `M / N` are both Noetherian, then `M` is Noetherian. -/ theorem wellFounded_gt_exact_sequence {β γ : Type*} [Preorder β] [Preorder γ] [WellFoundedGT β] [WellFoundedGT γ] (K : α) (f₁ : β → α) (f₂ : α → β) (g₁ : γ → α) (g₂ : α → γ) (gci : GaloisCoinsertion f₁ f₂) (gi : GaloisInsertion g₂ g₁) (hf : ∀ a, f₁ (f₂ a) = a ⊓ K) (hg : ∀ a, g₁ (g₂ a) = a ⊔ K) : WellFoundedGT α := wellFounded_lt_exact_sequence (α := αᵒᵈ) (β := γᵒᵈ) (γ := βᵒᵈ) K g₁ g₂ f₁ f₂ gi.dual gci.dual hg hf /-- The diamond isomorphism between the intervals `[a ⊓ b, a]` and `[b, a ⊔ b]` -/ @[simps] def infIccOrderIsoIccSup (a b : α) : Set.Icc (a ⊓ b) a ≃o Set.Icc b (a ⊔ b) where toFun x := ⟨x ⊔ b, ⟨le_sup_right, sup_le_sup_right x.prop.2 b⟩⟩ invFun x := ⟨a ⊓ x, ⟨inf_le_inf_left a x.prop.1, inf_le_left⟩⟩ left_inv x := Subtype.ext (by change a ⊓ (↑x ⊔ b) = ↑x rw [sup_comm, ← inf_sup_assoc_of_le _ x.prop.2, sup_eq_right.2 x.prop.1]) right_inv x := Subtype.ext (by change a ⊓ ↑x ⊔ b = ↑x rw [inf_comm, inf_sup_assoc_of_le _ x.prop.1, inf_eq_left.2 x.prop.2]) map_rel_iff' {x y} := by simp only [Subtype.mk_le_mk, Equiv.coe_fn_mk] rw [← Subtype.coe_le_coe] refine ⟨fun h => ?_, fun h => sup_le_sup_right h _⟩ rw [← sup_eq_right.2 x.prop.1, inf_sup_assoc_of_le _ x.prop.2, sup_comm, ← sup_eq_right.2 y.prop.1, inf_sup_assoc_of_le _ y.prop.2, sup_comm b] exact inf_le_inf_left _ h theorem inf_strictMonoOn_Icc_sup {a b : α} : StrictMonoOn (fun c => a ⊓ c) (Icc b (a ⊔ b)) := StrictMono.of_restrict (infIccOrderIsoIccSup a b).symm.strictMono theorem sup_strictMonoOn_Icc_inf {a b : α} : StrictMonoOn (fun c => c ⊔ b) (Icc (a ⊓ b) a) := StrictMono.of_restrict (infIccOrderIsoIccSup a b).strictMono /-- The diamond isomorphism between the intervals `]a ⊓ b, a[` and `}b, a ⊔ b[`. -/ @[simps] def infIooOrderIsoIooSup (a b : α) : Ioo (a ⊓ b) a ≃o Ioo b (a ⊔ b) where toFun c := ⟨c ⊔ b, le_sup_right.trans_lt <| sup_strictMonoOn_Icc_inf (left_mem_Icc.2 inf_le_left) (Ioo_subset_Icc_self c.2) c.2.1, sup_strictMonoOn_Icc_inf (Ioo_subset_Icc_self c.2) (right_mem_Icc.2 inf_le_left) c.2.2⟩ invFun c := ⟨a ⊓ c, inf_strictMonoOn_Icc_sup (left_mem_Icc.2 le_sup_right) (Ioo_subset_Icc_self c.2) c.2.1, inf_le_left.trans_lt' <| inf_strictMonoOn_Icc_sup (Ioo_subset_Icc_self c.2) (right_mem_Icc.2 le_sup_right) c.2.2⟩ left_inv c := Subtype.ext <| by dsimp rw [sup_comm, ← inf_sup_assoc_of_le _ c.prop.2.le, sup_eq_right.2 c.prop.1.le] right_inv c := Subtype.ext <| by dsimp rw [inf_comm, inf_sup_assoc_of_le _ c.prop.1.le, inf_eq_left.2 c.prop.2.le] map_rel_iff' := @fun c d => @OrderIso.le_iff_le _ _ _ _ (infIccOrderIsoIccSup _ _) ⟨c.1, Ioo_subset_Icc_self c.2⟩ ⟨d.1, Ioo_subset_Icc_self d.2⟩ -- See note [lower instance priority] instance (priority := 100) IsModularLattice.to_isLowerModularLattice : IsLowerModularLattice α := ⟨fun {a b} => by simp_rw [covBy_iff_Ioo_eq, sup_comm a, inf_comm a, ← isEmpty_coe_sort, right_lt_sup, inf_lt_left, (infIooOrderIsoIooSup b a).symm.toEquiv.isEmpty_congr] exact id⟩ -- See note [lower instance priority] instance (priority := 100) IsModularLattice.to_isUpperModularLattice : IsUpperModularLattice α := ⟨fun {a b} => by simp_rw [covBy_iff_Ioo_eq, ← isEmpty_coe_sort, right_lt_sup, inf_lt_left, (infIooOrderIsoIooSup a b).toEquiv.isEmpty_congr] exact id⟩ end IsModularLattice namespace IsCompl variable [Lattice α] [BoundedOrder α] [IsModularLattice α] /-- The diamond isomorphism between the intervals `Set.Iic a` and `Set.Ici b`. -/ def IicOrderIsoIci {a b : α} (h : IsCompl a b) : Set.Iic a ≃o Set.Ici b := (OrderIso.setCongr (Set.Iic a) (Set.Icc (a ⊓ b) a) (h.inf_eq_bot.symm ▸ Set.Icc_bot.symm)).trans <| (infIccOrderIsoIccSup a b).trans (OrderIso.setCongr (Set.Icc b (a ⊔ b)) (Set.Ici b) (h.sup_eq_top.symm ▸ Set.Icc_top)) end IsCompl theorem isModularLattice_iff_inf_sup_inf_assoc [Lattice α] : IsModularLattice α ↔ ∀ x y z : α, x ⊓ z ⊔ y ⊓ z = (x ⊓ z ⊔ y) ⊓ z := ⟨fun h => @IsModularLattice.inf_sup_inf_assoc _ _ h, fun h => ⟨fun y z xz => by rw [← inf_eq_left.2 xz, h]⟩⟩ namespace DistribLattice instance (priority := 100) [DistribLattice α] : IsModularLattice α := ⟨fun y z xz => by rw [inf_sup_right, inf_eq_left.2 xz]⟩ end DistribLattice namespace Disjoint variable {a b c : α} theorem disjoint_sup_right_of_disjoint_sup_left [Lattice α] [OrderBot α] [IsModularLattice α] (h : Disjoint a b) (hsup : Disjoint (a ⊔ b) c) : Disjoint a (b ⊔ c) := by rw [disjoint_iff_inf_le, ← h.eq_bot, sup_comm] apply le_inf inf_le_left apply (inf_le_inf_right (c ⊔ b) le_sup_right).trans rw [sup_comm, IsModularLattice.sup_inf_sup_assoc, hsup.eq_bot, bot_sup_eq] theorem disjoint_sup_left_of_disjoint_sup_right [Lattice α] [OrderBot α] [IsModularLattice α] (h : Disjoint b c) (hsup : Disjoint a (b ⊔ c)) : Disjoint (a ⊔ b) c := by rw [disjoint_comm, sup_comm] apply Disjoint.disjoint_sup_right_of_disjoint_sup_left h.symm rwa [sup_comm, disjoint_comm] at hsup theorem isCompl_sup_right_of_isCompl_sup_left [Lattice α] [BoundedOrder α] [IsModularLattice α] (h : Disjoint a b) (hcomp : IsCompl (a ⊔ b) c) : IsCompl a (b ⊔ c) := ⟨h.disjoint_sup_right_of_disjoint_sup_left hcomp.disjoint, codisjoint_assoc.mp hcomp.codisjoint⟩ theorem isCompl_sup_left_of_isCompl_sup_right [Lattice α] [BoundedOrder α] [IsModularLattice α] (h : Disjoint b c) (hcomp : IsCompl a (b ⊔ c)) : IsCompl (a ⊔ b) c := ⟨h.disjoint_sup_left_of_disjoint_sup_right hcomp.disjoint, codisjoint_assoc.mpr hcomp.codisjoint⟩ end Disjoint lemma Set.Iic.isCompl_inf_inf_of_isCompl_of_le [Lattice α] [BoundedOrder α] [IsModularLattice α] {a b c : α} (h₁ : IsCompl b c) (h₂ : b ≤ a) : IsCompl (⟨a ⊓ b, inf_le_left⟩ : Iic a) (⟨a ⊓ c, inf_le_left⟩ : Iic a) := by constructor · simp [disjoint_iff, Subtype.ext_iff, inf_comm a c, inf_assoc a, ← inf_assoc b, h₁.inf_eq_bot] · simp only [Iic.codisjoint_iff, inf_comm a, IsModularLattice.inf_sup_inf_assoc] simp [inf_of_le_left h₂, h₁.sup_eq_top] namespace IsModularLattice variable [Lattice α] [IsModularLattice α] {a b c : α} instance isModularLattice_Iic : IsModularLattice (Set.Iic a) := ⟨@fun x y z xz => (sup_inf_le_assoc_of_le (y : α) xz : (↑x ⊔ ↑y) ⊓ ↑z ≤ ↑x ⊔ ↑y ⊓ ↑z)⟩ instance isModularLattice_Ici : IsModularLattice (Set.Ici a) := ⟨@fun x y z xz => (sup_inf_le_assoc_of_le (y : α) xz : (↑x ⊔ ↑y) ⊓ ↑z ≤ ↑x ⊔ ↑y ⊓ ↑z)⟩ section ComplementedLattice variable [BoundedOrder α] [ComplementedLattice α] theorem exists_inf_eq_and_sup_eq (hb : a ≤ b) (hc : b ≤ c) : ∃ b', b ⊓ b' = a ∧ b ⊔ b' = c := by obtain ⟨d, hdisjoint, hcodisjoint⟩ := exists_isCompl b refine ⟨(d ⊔ a) ⊓ c, ?_, ?_⟩ · simpa [← inf_assoc, ← inf_sup_assoc_of_le _ hb, hdisjoint.eq_bot] using hb.trans hc · simp [← sup_inf_assoc_of_le _ hc, ← sup_assoc, hcodisjoint.eq_top] theorem exists_disjoint_and_sup_eq (h : a ≤ b) : ∃ a', Disjoint a a' ∧ a ⊔ a' = b := by simp_rw [disjoint_iff] apply exists_inf_eq_and_sup_eq (by simp) h theorem exists_inf_eq_and_codisjoint (h : a ≤ b) : ∃ b', b ⊓ b' = a ∧ Codisjoint b b' := by simp_rw [codisjoint_iff] apply exists_inf_eq_and_sup_eq h (by simp) instance complementedLattice_Icc [Fact (a ≤ b)] : ComplementedLattice (Set.Icc a b) where exists_isCompl := fun ⟨x, ha, hb⟩ => by simp_rw [Set.Icc.isCompl_iff] obtain ⟨y, rfl, rfl⟩ := exists_inf_eq_and_sup_eq ha hb exact ⟨⟨y, inf_le_right, le_sup_right⟩, rfl, rfl⟩ instance complementedLattice_Iic : ComplementedLattice (Set.Iic a) where exists_isCompl := fun ⟨x, hx⟩ => by simp_rw [Set.Iic.isCompl_iff] obtain ⟨y, hdisjoint, rfl⟩ := exists_disjoint_and_sup_eq hx exact ⟨⟨y, le_sup_right⟩, hdisjoint, rfl⟩ instance complementedLattice_Ici : ComplementedLattice (Set.Ici a) where exists_isCompl := fun ⟨x, hx⟩ => by simp_rw [Set.Ici.isCompl_iff] obtain ⟨y, rfl, hcodisjoint⟩ := exists_inf_eq_and_codisjoint hx exact ⟨⟨y, inf_le_right⟩, rfl, hcodisjoint⟩ end ComplementedLattice end IsModularLattice
.lake/packages/mathlib/Mathlib/Order/OmegaCompletePartialOrder.lean
import Mathlib.Control.Monad.Basic import Mathlib.Dynamics.FixedPoints.Basic import Mathlib.Order.CompleteLattice.Basic import Mathlib.Order.Iterate import Mathlib.Order.Part import Mathlib.Order.Preorder.Chain import Mathlib.Order.ScottContinuity /-! # Omega Complete Partial Orders An omega-complete partial order is a partial order with a supremum operation on increasing sequences indexed by natural numbers (which we call `ωSup`). In this sense, it is strictly weaker than join complete semi-lattices as only ω-sized totally ordered sets have a supremum. The concept of an omega-complete partial order (ωCPO) is useful for the formalization of the semantics of programming languages. Its notion of supremum helps define the meaning of recursive procedures. ## Main definitions * class `OmegaCompletePartialOrder` * `ite`, `map`, `bind`, `seq` as continuous morphisms ## Instances of `OmegaCompletePartialOrder` * `Part` * every `CompleteLattice` * pi-types * product types * `OrderHom` * `ContinuousHom` (with notation →𝒄) * an instance of `OmegaCompletePartialOrder (α →𝒄 β)` * `ContinuousHom.ofFun` * `ContinuousHom.ofMono` * continuous functions: * `id` * `ite` * `const` * `Part.bind` * `Part.map` * `Part.seq` ## References * [Chain-complete posets and directed sets with applications][markowsky1976] * [Recursive definitions of partial functions and their computations][cadiou1972] * [Semantics of Programming Languages: Structures and Techniques][gunter1992] -/ assert_not_exists IsOrderedMonoid universe u v variable {ι : Sort*} {α β γ δ : Type*} namespace OmegaCompletePartialOrder /-- A chain is a monotone sequence. See the definition on page 114 of [gunter1992]. -/ def Chain (α : Type u) [Preorder α] := ℕ →o α namespace Chain variable [Preorder α] [Preorder β] [Preorder γ] instance : FunLike (Chain α) ℕ α := inferInstanceAs <| FunLike (ℕ →o α) ℕ α instance : OrderHomClass (Chain α) ℕ α := inferInstanceAs <| OrderHomClass (ℕ →o α) ℕ α /-- See note [partially-applied ext lemmas]. -/ @[ext] lemma ext ⦃f g : Chain α⦄ (h : ⇑f = ⇑g) : f = g := DFunLike.ext' h instance [Inhabited α] : Inhabited (Chain α) := ⟨⟨default, fun _ _ _ => le_rfl⟩⟩ instance : Membership α (Chain α) := ⟨fun (c : ℕ →o α) a => ∃ i, a = c i⟩ variable (c c' : Chain α) variable (f : α →o β) variable (g : β →o γ) instance : LE (Chain α) where le x y := ∀ i, ∃ j, x i ≤ y j lemma isChain_range : IsChain (· ≤ ·) (Set.range c) := Monotone.isChain_range (OrderHomClass.mono c) lemma directed : Directed (· ≤ ·) c := directedOn_range.2 c.isChain_range.directedOn /-- `map` function for `Chain` -/ -- Not `@[simps]`: we need `@[simps!]` to see through the type synonym `Chain β = ℕ →o β`, -- but then we'd get the `FunLike` instance for `OrderHom` instead. def map : Chain β := f.comp c @[simp] theorem map_coe : ⇑(map c f) = f ∘ c := rfl variable {f} theorem mem_map (x : α) : x ∈ c → f x ∈ Chain.map c f := fun ⟨i, h⟩ => ⟨i, h.symm ▸ rfl⟩ theorem exists_of_mem_map {b : β} : b ∈ c.map f → ∃ a, a ∈ c ∧ f a = b := fun ⟨i, h⟩ => ⟨c i, ⟨i, rfl⟩, h.symm⟩ @[simp] theorem mem_map_iff {b : β} : b ∈ c.map f ↔ ∃ a, a ∈ c ∧ f a = b := ⟨exists_of_mem_map _, fun h => by rcases h with ⟨w, h, h'⟩ subst b apply mem_map c _ h⟩ @[simp] theorem map_id : c.map OrderHom.id = c := OrderHom.comp_id _ theorem map_comp : (c.map f).map g = c.map (g.comp f) := rfl @[mono] theorem map_le_map {g : α →o β} (h : f ≤ g) : c.map f ≤ c.map g := fun i => by simp only [map_coe, Function.comp_apply]; exists i; apply h /-- `OmegaCompletePartialOrder.Chain.zip` pairs up the elements of two chains that have the same index. -/ -- Not `@[simps]`: we need `@[simps!]` to see through the type synonym `Chain β = ℕ →o β`, -- but then we'd get the `FunLike` instance for `OrderHom` instead. def zip (c₀ : Chain α) (c₁ : Chain β) : Chain (α × β) := OrderHom.prod c₀ c₁ @[simp] theorem zip_coe (c₀ : Chain α) (c₁ : Chain β) (n : ℕ) : c₀.zip c₁ n = (c₀ n, c₁ n) := rfl /-- An example of a `Chain` constructed from an ordered pair. -/ def pair (a b : α) (hab : a ≤ b) : Chain α where toFun | 0 => a | _ => b monotone' _ _ _ := by aesop @[simp] lemma pair_zero (a b : α) (hab) : pair a b hab 0 = a := rfl @[simp] lemma pair_succ (a b : α) (hab) (n : ℕ) : pair a b hab (n + 1) = b := rfl @[simp] lemma range_pair (a b : α) (hab) : Set.range (pair a b hab) = {a, b} := by ext; exact Nat.or_exists_add_one.symm.trans (by aesop) @[simp] lemma pair_zip_pair (a₁ a₂ : α) (b₁ b₂ : β) (ha hb) : (pair a₁ a₂ ha).zip (pair b₁ b₂ hb) = pair (a₁, b₁) (a₂, b₂) (Prod.le_def.2 ⟨ha, hb⟩) := by unfold Chain; ext n : 2; cases n <;> rfl end Chain end OmegaCompletePartialOrder open OmegaCompletePartialOrder Chain /-- An omega-complete partial order is a partial order with a supremum operation on increasing sequences indexed by natural numbers (which we call `ωSup`). In this sense, it is strictly weaker than join complete semi-lattices as only ω-sized totally ordered sets have a supremum. See the definition on page 114 of [gunter1992]. -/ class OmegaCompletePartialOrder (α : Type*) extends PartialOrder α where /-- The supremum of an increasing sequence -/ ωSup : Chain α → α /-- `ωSup` is an upper bound of the increasing sequence -/ le_ωSup : ∀ c : Chain α, ∀ i, c i ≤ ωSup c /-- `ωSup` is a lower bound of the set of upper bounds of the increasing sequence -/ ωSup_le : ∀ (c : Chain α) (x), (∀ i, c i ≤ x) → ωSup c ≤ x namespace OmegaCompletePartialOrder variable [OmegaCompletePartialOrder α] /-- Transfer an `OmegaCompletePartialOrder` on `β` to an `OmegaCompletePartialOrder` on `α` using a strictly monotone function `f : β →o α`, a definition of ωSup and a proof that `f` is continuous with regard to the provided `ωSup` and the ωCPO on `α`. -/ protected abbrev lift [PartialOrder β] (f : β →o α) (ωSup₀ : Chain β → β) (h : ∀ x y, f x ≤ f y → x ≤ y) (h' : ∀ c, f (ωSup₀ c) = ωSup (c.map f)) : OmegaCompletePartialOrder β where ωSup := ωSup₀ ωSup_le c x hx := h _ _ (by rw [h']; apply ωSup_le; intro i; apply f.monotone (hx i)) le_ωSup c i := h _ _ (by rw [h']; apply le_ωSup (c.map f)) theorem le_ωSup_of_le {c : Chain α} {x : α} (i : ℕ) (h : x ≤ c i) : x ≤ ωSup c := le_trans h (le_ωSup c _) theorem ωSup_total {c : Chain α} {x : α} (h : ∀ i, c i ≤ x ∨ x ≤ c i) : ωSup c ≤ x ∨ x ≤ ωSup c := by_cases (fun (this : ∀ i, c i ≤ x) => Or.inl (ωSup_le _ _ this)) (fun (this : ¬∀ i, c i ≤ x) => have : ∃ i, ¬c i ≤ x := by simp only [not_forall] at this ⊢; assumption let ⟨i, hx⟩ := this have : x ≤ c i := (h i).resolve_left hx Or.inr <| le_ωSup_of_le _ this) @[mono] theorem ωSup_le_ωSup_of_le {c₀ c₁ : Chain α} (h : c₀ ≤ c₁) : ωSup c₀ ≤ ωSup c₁ := (ωSup_le _ _) fun i => by obtain ⟨_, h⟩ := h i exact le_trans h (le_ωSup _ _) @[simp] theorem ωSup_le_iff {c : Chain α} {x : α} : ωSup c ≤ x ↔ ∀ i, c i ≤ x := by constructor <;> intros · trans ωSup c · exact le_ωSup _ _ · assumption exact ωSup_le _ _ ‹_› lemma isLUB_range_ωSup (c : Chain α) : IsLUB (Set.range c) (ωSup c) := by constructor · simp only [upperBounds, Set.mem_range, forall_exists_index, forall_apply_eq_imp_iff, Set.mem_setOf_eq] exact fun a ↦ le_ωSup c a · simp only [lowerBounds, upperBounds, Set.mem_range, forall_exists_index, forall_apply_eq_imp_iff, Set.mem_setOf_eq] exact fun ⦃a⦄ a_1 ↦ ωSup_le c a a_1 lemma ωSup_eq_of_isLUB {c : Chain α} {a : α} (h : IsLUB (Set.range c) a) : a = ωSup c := by rw [le_antisymm_iff] simp only [IsLUB, IsLeast, upperBounds, lowerBounds, Set.mem_range, forall_exists_index, forall_apply_eq_imp_iff, Set.mem_setOf_eq] at h constructor · apply h.2 exact fun a ↦ le_ωSup c a · rw [ωSup_le_iff] apply h.1 /-- A subset `p : α → Prop` of the type closed under `ωSup` induces an `OmegaCompletePartialOrder` on the subtype `{a : α // p a}`. -/ def subtype {α : Type*} [OmegaCompletePartialOrder α] (p : α → Prop) (hp : ∀ c : Chain α, (∀ i ∈ c, p i) → p (ωSup c)) : OmegaCompletePartialOrder (Subtype p) := OmegaCompletePartialOrder.lift (OrderHom.Subtype.val p) (fun c => ⟨ωSup _, hp (c.map (OrderHom.Subtype.val p)) fun _ ⟨n, q⟩ => q.symm ▸ (c n).2⟩) (fun _ _ h => h) (fun _ => rfl) section Continuity variable [OmegaCompletePartialOrder β] variable [OmegaCompletePartialOrder γ] variable {f : α → β} {g : β → γ} /-- A function `f` between `ω`-complete partial orders is `ωScottContinuous` if it is Scott continuous over chains. -/ def ωScottContinuous (f : α → β) : Prop := ScottContinuousOn (Set.range fun c : Chain α => Set.range c) f lemma _root_.ScottContinuous.ωScottContinuous (hf : ScottContinuous f) : ωScottContinuous f := hf.scottContinuousOn lemma ωScottContinuous.monotone (h : ωScottContinuous f) : Monotone f := ScottContinuousOn.monotone _ (fun a b hab => by use pair a b hab; exact range_pair a b hab) h lemma ωScottContinuous.isLUB {c : Chain α} (hf : ωScottContinuous f) : IsLUB (Set.range (c.map ⟨f, hf.monotone⟩)) (f (ωSup c)) := by simpa [map_coe, OrderHom.coe_mk, Set.range_comp] using hf (by simp) (Set.range_nonempty _) (isChain_range c).directedOn (isLUB_range_ωSup c) lemma ωScottContinuous.id : ωScottContinuous (id : α → α) := ScottContinuousOn.id lemma ωScottContinuous.map_ωSup (hf : ωScottContinuous f) (c : Chain α) : f (ωSup c) = ωSup (c.map ⟨f, hf.monotone⟩) := ωSup_eq_of_isLUB hf.isLUB /-- `ωScottContinuous f` asserts that `f` is both monotone and distributes over ωSup. -/ lemma ωScottContinuous_iff_monotone_map_ωSup : ωScottContinuous f ↔ ∃ hf : Monotone f, ∀ c : Chain α, f (ωSup c) = ωSup (c.map ⟨f, hf⟩) := by refine ⟨fun hf ↦ ⟨hf.monotone, hf.map_ωSup⟩, ?_⟩ intro hf _ ⟨c, hc⟩ _ _ _ hda convert isLUB_range_ωSup (c.map { toFun := f, monotone' := hf.1 }) · rw [map_coe, OrderHom.coe_mk, ← hc, ← (Set.range_comp f ⇑c)] · rw [← hc] at hda rw [← hf.2 c, ωSup_eq_of_isLUB hda] alias ⟨ωScottContinuous.monotone_map_ωSup, ωScottContinuous.of_monotone_map_ωSup⟩ := ωScottContinuous_iff_monotone_map_ωSup /- A monotone function `f : α →o β` is ωScott continuous if and only if it distributes over ωSup. -/ lemma ωScottContinuous_iff_map_ωSup_of_orderHom {f : α →o β} : ωScottContinuous f ↔ ∀ c : Chain α, f (ωSup c) = ωSup (c.map f) := by rw [ωScottContinuous_iff_monotone_map_ωSup] exact exists_prop_of_true f.monotone' alias ⟨ωScottContinuous.map_ωSup_of_orderHom, ωScottContinuous.of_map_ωSup_of_orderHom⟩ := ωScottContinuous_iff_map_ωSup_of_orderHom lemma ωScottContinuous.comp (hg : ωScottContinuous g) (hf : ωScottContinuous f) : ωScottContinuous (g.comp f) := ωScottContinuous.of_monotone_map_ωSup ⟨hg.monotone.comp hf.monotone, by simp [hf.map_ωSup, hg.map_ωSup, map_comp]⟩ lemma ωScottContinuous.const {x : β} : ωScottContinuous (Function.const α x) := by simp [ωScottContinuous, ScottContinuousOn, Set.range_nonempty] end Continuity end OmegaCompletePartialOrder namespace Part theorem eq_of_chain {c : Chain (Part α)} {a b : α} (ha : some a ∈ c) (hb : some b ∈ c) : a = b := by obtain ⟨i, ha⟩ := ha; replace ha := ha.symm obtain ⟨j, hb⟩ := hb; replace hb := hb.symm rw [eq_some_iff] at ha hb rcases le_total i j with hij | hji · have := c.monotone hij _ ha; apply mem_unique this hb · have := c.monotone hji _ hb; apply Eq.symm; apply mem_unique this ha open Classical in /-- The (noncomputable) `ωSup` definition for the `ω`-CPO structure on `Part α`. -/ protected noncomputable def ωSup (c : Chain (Part α)) : Part α := if h : ∃ a, some a ∈ c then some (Classical.choose h) else none theorem ωSup_eq_some {c : Chain (Part α)} {a : α} (h : some a ∈ c) : Part.ωSup c = some a := have : ∃ a, some a ∈ c := ⟨a, h⟩ have a' : some (Classical.choose this) ∈ c := Classical.choose_spec this calc Part.ωSup c = some (Classical.choose this) := dif_pos this _ = some a := congr_arg _ (eq_of_chain a' h) theorem ωSup_eq_none {c : Chain (Part α)} (h : ¬∃ a, some a ∈ c) : Part.ωSup c = none := dif_neg h theorem mem_chain_of_mem_ωSup {c : Chain (Part α)} {a : α} (h : a ∈ Part.ωSup c) : some a ∈ c := by simp only [Part.ωSup] at h; split_ifs at h with h_1 · have h' := Classical.choose_spec h_1 rw [← eq_some_iff] at h rw [← h] exact h' · rcases h with ⟨⟨⟩⟩ noncomputable instance omegaCompletePartialOrder : OmegaCompletePartialOrder (Part α) where ωSup := Part.ωSup le_ωSup c i := by intro x hx rw [← eq_some_iff] at hx ⊢ rw [ωSup_eq_some] rw [← hx] exact ⟨i, rfl⟩ ωSup_le := by rintro c x hx a ha replace ha := mem_chain_of_mem_ωSup ha obtain ⟨i, ha⟩ := ha apply hx i rw [← ha] apply mem_some section Inst theorem mem_ωSup (x : α) (c : Chain (Part α)) : x ∈ ωSup c ↔ some x ∈ c := by simp only [ωSup, Part.ωSup] constructor · split_ifs with h swap · rintro ⟨⟨⟩⟩ intro h' have hh := Classical.choose_spec h simp only [mem_some_iff] at h' subst x exact hh · intro h have h' : ∃ a : α, some a ∈ c := ⟨_, h⟩ rw [dif_pos h'] have hh := Classical.choose_spec h' rw [eq_of_chain hh h] simp end Inst end Part section Pi variable {β : α → Type*} instance [∀ a, OmegaCompletePartialOrder (β a)] : OmegaCompletePartialOrder (∀ a, β a) where ωSup c a := ωSup (c.map (Pi.evalOrderHom a)) ωSup_le _ _ hf a := ωSup_le _ _ <| by rintro i apply hf le_ωSup _ _ _ := le_ωSup_of_le _ <| le_rfl namespace OmegaCompletePartialOrder variable [∀ x, OmegaCompletePartialOrder <| β x] variable [OmegaCompletePartialOrder γ] variable {f : γ → ∀ x, β x} lemma ωScottContinuous.apply₂ (hf : ωScottContinuous f) (a : α) : ωScottContinuous (f · a) := ωScottContinuous.of_monotone_map_ωSup ⟨fun _ _ h ↦ hf.monotone h a, fun c ↦ congr_fun (hf.map_ωSup c) a⟩ lemma ωScottContinuous.of_apply₂ (hf : ∀ a, ωScottContinuous (f · a)) : ωScottContinuous f := ωScottContinuous.of_monotone_map_ωSup ⟨fun _ _ h a ↦ (hf a).monotone h, fun c ↦ by ext a; apply (hf a).map_ωSup c⟩ lemma ωScottContinuous_iff_apply₂ : ωScottContinuous f ↔ ∀ a, ωScottContinuous (f · a) := ⟨ωScottContinuous.apply₂, ωScottContinuous.of_apply₂⟩ end OmegaCompletePartialOrder end Pi namespace Prod variable [OmegaCompletePartialOrder α] variable [OmegaCompletePartialOrder β] variable [OmegaCompletePartialOrder γ] /-- The supremum of a chain in the product `ω`-CPO. -/ @[simps] protected def ωSupImpl (c : Chain (α × β)) : α × β := (ωSup (c.map OrderHom.fst), ωSup (c.map OrderHom.snd)) @[simps! ωSup_fst ωSup_snd] instance : OmegaCompletePartialOrder (α × β) where ωSup := Prod.ωSupImpl ωSup_le := fun _ _ h => ⟨ωSup_le _ _ fun i => (h i).1, ωSup_le _ _ fun i => (h i).2⟩ le_ωSup c i := ⟨le_ωSup (c.map OrderHom.fst) i, le_ωSup (c.map OrderHom.snd) i⟩ theorem ωSup_zip (c₀ : Chain α) (c₁ : Chain β) : ωSup (c₀.zip c₁) = (ωSup c₀, ωSup c₁) := rfl end Prod namespace CompleteLattice -- see Note [lower instance priority] /-- Any complete lattice has an `ω`-CPO structure where the countable supremum is a special case of arbitrary suprema. -/ instance (priority := 100) [CompleteLattice α] : OmegaCompletePartialOrder α where ωSup c := ⨆ i, c i ωSup_le := fun ⟨c, _⟩ s hs => by simpa only [iSup_le_iff] le_ωSup := fun ⟨c, _⟩ i => le_iSup_of_le i le_rfl variable [OmegaCompletePartialOrder α] [CompleteLattice β] {f g : α → β} -- TODO Prove this result for `ScottContinuousOn` and deduce this as a special case -- https://github.com/leanprover-community/mathlib4/pull/15412 open Chain in lemma ωScottContinuous.prodMk (hf : ωScottContinuous f) (hg : ωScottContinuous g) : ωScottContinuous fun x => (f x, g x) := ScottContinuousOn.prodMk (fun a b hab => by use pair a b hab; exact range_pair a b hab) hf hg lemma ωScottContinuous.iSup {f : ι → α → β} (hf : ∀ i, ωScottContinuous (f i)) : ωScottContinuous (⨆ i, f i) := by refine ωScottContinuous.of_monotone_map_ωSup ⟨Monotone.iSup fun i ↦ (hf i).monotone, fun c ↦ eq_of_forall_ge_iff fun a ↦ ?_⟩ simp +contextual [ωSup_le_iff, (hf _).map_ωSup, @forall_swap ι] lemma ωScottContinuous.sSup {s : Set (α → β)} (hs : ∀ f ∈ s, ωScottContinuous f) : ωScottContinuous (sSup s) := by rw [sSup_eq_iSup]; exact ωScottContinuous.iSup fun f ↦ ωScottContinuous.iSup <| hs f lemma ωScottContinuous.sup (hf : ωScottContinuous f) (hg : ωScottContinuous g) : ωScottContinuous (f ⊔ g) := by rw [← sSup_pair] apply ωScottContinuous.sSup rintro f (rfl | rfl | _) <;> assumption lemma ωScottContinuous.top : ωScottContinuous (⊤ : α → β) := ωScottContinuous.of_monotone_map_ωSup ⟨monotone_const, fun c ↦ eq_of_forall_ge_iff fun a ↦ by simp⟩ lemma ωScottContinuous.bot : ωScottContinuous (⊥ : α → β) := by rw [← sSup_empty]; exact ωScottContinuous.sSup (by simp) end CompleteLattice namespace CompleteLattice variable [OmegaCompletePartialOrder α] [CompleteLinearOrder β] {f g : α → β} -- TODO Prove this result for `ScottContinuousOn` and deduce this as a special case -- Also consider if it holds in greater generality (e.g. finite sets) -- N.B. The Scott Topology coincides with the Upper Topology on a Complete Linear Order -- `Topology.IsScott.scott_eq_upper_of_completeLinearOrder` -- We have that the product topology coincides with the upper topology -- https://github.com/leanprover-community/mathlib4/pull/12133 lemma ωScottContinuous.inf (hf : ωScottContinuous f) (hg : ωScottContinuous g) : ωScottContinuous (f ⊓ g) := by refine ωScottContinuous.of_monotone_map_ωSup ⟨hf.monotone.inf hg.monotone, fun c ↦ eq_of_forall_ge_iff fun a ↦ ?_⟩ simp only [Pi.inf_apply, hf.map_ωSup c, hg.map_ωSup c, inf_le_iff, ωSup_le_iff, Chain.map_coe, Function.comp, OrderHom.coe_mk, ← forall_or_left, ← forall_or_right] exact ⟨fun h _ ↦ h _ _, fun h i j ↦ (h (max j i)).imp (le_trans <| hf.monotone <| c.mono <| le_max_left _ _) (le_trans <| hg.monotone <| c.mono <| le_max_right _ _)⟩ end CompleteLattice namespace OmegaCompletePartialOrder variable [OmegaCompletePartialOrder α] [OmegaCompletePartialOrder β] variable [OmegaCompletePartialOrder γ] [OmegaCompletePartialOrder δ] namespace OrderHom /-- The `ωSup` operator for monotone functions. -/ @[simps] protected def ωSup (c : Chain (α →o β)) : α →o β where toFun a := ωSup (c.map (OrderHom.apply a)) monotone' _ _ h := ωSup_le_ωSup_of_le ((Chain.map_le_map _) fun a => a.monotone h) @[simps! ωSup_coe] instance omegaCompletePartialOrder : OmegaCompletePartialOrder (α →o β) := OmegaCompletePartialOrder.lift OrderHom.coeFnHom OrderHom.ωSup (fun _ _ h => h) fun _ => rfl end OrderHom variable (α β) in /-- A monotone function on `ω`-continuous partial orders is said to be continuous if for every chain `c : chain α`, `f (⊔ i, c i) = ⊔ i, f (c i)`. This is just the bundled version of `OrderHom.continuous`. -/ structure ContinuousHom extends OrderHom α β where /-- The underlying function of a `ContinuousHom` is continuous, i.e. it preserves `ωSup` -/ protected map_ωSup' (c : Chain α) : toFun (ωSup c) = ωSup (c.map toOrderHom) attribute [nolint docBlame] ContinuousHom.toOrderHom @[inherit_doc] infixr:25 " →𝒄 " => ContinuousHom -- Input: \r\MIc instance : FunLike (α →𝒄 β) α β where coe f := f.toFun coe_injective' := by rintro ⟨⟩ ⟨⟩ h; congr; exact DFunLike.ext' h instance : OrderHomClass (α →𝒄 β) α β where map_rel f _ _ h := f.mono h instance : PartialOrder (α →𝒄 β) := (PartialOrder.lift fun f => f.toOrderHom.toFun) <| by rintro ⟨⟨⟩⟩ ⟨⟨⟩⟩ h; congr namespace ContinuousHom protected lemma ωScottContinuous (f : α →𝒄 β) : ωScottContinuous f := ωScottContinuous.of_map_ωSup_of_orderHom f.map_ωSup' -- Not a `simp` lemma because in many cases projection is simpler than a generic coercion theorem toOrderHom_eq_coe (f : α →𝒄 β) : f.1 = f := rfl @[simp] theorem coe_mk (f : α →o β) (hf) : ⇑(mk f hf) = f := rfl @[simp] theorem coe_toOrderHom (f : α →𝒄 β) : ⇑f.1 = f := rfl /-- See Note [custom simps projection]. We specify this explicitly because we don't have a DFunLike instance. -/ def Simps.apply (h : α →𝒄 β) : α → β := h initialize_simps_projections ContinuousHom (toFun → apply) protected theorem congr_fun {f g : α →𝒄 β} (h : f = g) (x : α) : f x = g x := DFunLike.congr_fun h x protected theorem congr_arg (f : α →𝒄 β) {x y : α} (h : x = y) : f x = f y := congr_arg f h protected theorem monotone (f : α →𝒄 β) : Monotone f := f.monotone' @[mono] theorem apply_mono {f g : α →𝒄 β} {x y : α} (h₁ : f ≤ g) (h₂ : x ≤ y) : f x ≤ g y := OrderHom.apply_mono (show (f : α →o β) ≤ g from h₁) h₂ theorem ωSup_bind {β γ : Type v} (c : Chain α) (f : α →o Part β) (g : α →o β → Part γ) : ωSup (c.map (f.partBind g)) = ωSup (c.map f) >>= ωSup (c.map g) := by apply eq_of_forall_ge_iff; intro x simp only [ωSup_le_iff, Part.bind_le] constructor <;> intro h''' · intro b hb apply ωSup_le _ _ _ rintro i y hy simp only [Part.mem_ωSup] at hb rcases hb with ⟨j, hb⟩ replace hb := hb.symm simp only [Part.eq_some_iff, Chain.map_coe, Function.comp_apply] at hy hb replace hb : b ∈ f (c (max i j)) := f.mono (c.mono (le_max_right i j)) _ hb replace hy : y ∈ g (c (max i j)) b := g.mono (c.mono (le_max_left i j)) _ _ hy apply h''' (max i j) simp only [Part.mem_bind_iff, Chain.map_coe, Function.comp_apply, OrderHom.partBind_coe] exact ⟨_, hb, hy⟩ · intro i y hy simp only [Part.mem_bind_iff, Chain.map_coe, Function.comp_apply, OrderHom.partBind_coe] at hy rcases hy with ⟨b, hb₀, hb₁⟩ apply h''' b _ · apply le_ωSup (c.map g) _ _ _ hb₁ · apply le_ωSup (c.map f) i _ hb₀ -- TODO: We should move `ωScottContinuous` to the root namespace lemma ωScottContinuous.bind {β γ} {f : α → Part β} {g : α → β → Part γ} (hf : ωScottContinuous f) (hg : ωScottContinuous g) : ωScottContinuous fun x ↦ f x >>= g x := ωScottContinuous.of_monotone_map_ωSup ⟨hf.monotone.partBind hg.monotone, fun c ↦ by rw [hf.map_ωSup, hg.map_ωSup, ← ωSup_bind]; rfl⟩ lemma ωScottContinuous.map {β γ} {f : β → γ} {g : α → Part β} (hg : ωScottContinuous g) : ωScottContinuous fun x ↦ f <$> g x := by simpa only [map_eq_bind_pure_comp] using ωScottContinuous.bind hg ωScottContinuous.const lemma ωScottContinuous.seq {β γ} {f : α → Part (β → γ)} {g : α → Part β} (hf : ωScottContinuous f) (hg : ωScottContinuous g) : ωScottContinuous fun x ↦ f x <*> g x := by simp only [seq_eq_bind_map] exact ωScottContinuous.bind hf <| ωScottContinuous.of_apply₂ fun _ ↦ ωScottContinuous.map hg theorem continuous (F : α →𝒄 β) (C : Chain α) : F (ωSup C) = ωSup (C.map F) := F.ωScottContinuous.map_ωSup _ /-- Construct a continuous function from a bare function, a continuous function, and a proof that they are equal. -/ @[simps!] def copy (f : α → β) (g : α →𝒄 β) (h : f = g) : α →𝒄 β where toOrderHom := g.1.copy f h map_ωSup' := by rw [OrderHom.copy_eq]; exact g.map_ωSup' /-- The identity as a continuous function. -/ @[simps!] def id : α →𝒄 α := ⟨OrderHom.id, ωScottContinuous.id.map_ωSup⟩ /-- The composition of continuous functions. -/ @[simps!] def comp (f : β →𝒄 γ) (g : α →𝒄 β) : α →𝒄 γ := ⟨.comp f.1 g.1, (f.ωScottContinuous.comp g.ωScottContinuous).map_ωSup⟩ @[ext] protected theorem ext (f g : α →𝒄 β) (h : ∀ x, f x = g x) : f = g := DFunLike.ext f g h protected theorem coe_inj (f g : α →𝒄 β) (h : (f : α → β) = g) : f = g := DFunLike.ext' h @[simp] theorem comp_id (f : β →𝒄 γ) : f.comp id = f := rfl @[simp] theorem id_comp (f : β →𝒄 γ) : id.comp f = f := rfl @[simp] theorem comp_assoc (f : γ →𝒄 δ) (g : β →𝒄 γ) (h : α →𝒄 β) : f.comp (g.comp h) = (f.comp g).comp h := rfl @[simp] theorem coe_apply (a : α) (f : α →𝒄 β) : (f : α →o β) a = f a := rfl /-- `Function.const` is a continuous function. -/ @[simps!] def const (x : β) : α →𝒄 β := ⟨.const _ x, ωScottContinuous.const.map_ωSup⟩ instance [Inhabited β] : Inhabited (α →𝒄 β) := ⟨const default⟩ /-- The map from continuous functions to monotone functions is itself a monotone function. -/ @[simps] def toMono : (α →𝒄 β) →o α →o β where toFun f := f monotone' _ _ h := h /-- When proving that a chain of applications is below a bound `z`, it suffices to consider the functions and values being selected from the same index in the chains. This lemma is more specific than necessary, i.e. `c₀` only needs to be a chain of monotone functions, but it is only used with continuous functions. -/ @[simp] theorem forall_forall_merge (c₀ : Chain (α →𝒄 β)) (c₁ : Chain α) (z : β) : (∀ i j : ℕ, (c₀ i) (c₁ j) ≤ z) ↔ ∀ i : ℕ, (c₀ i) (c₁ i) ≤ z := by constructor <;> introv h · apply h · apply le_trans _ (h (max i j)) trans c₀ i (c₁ (max i j)) · apply (c₀ i).monotone apply c₁.monotone apply le_max_right · apply c₀.monotone apply le_max_left @[simp] theorem forall_forall_merge' (c₀ : Chain (α →𝒄 β)) (c₁ : Chain α) (z : β) : (∀ j i : ℕ, (c₀ i) (c₁ j) ≤ z) ↔ ∀ i : ℕ, (c₀ i) (c₁ i) ≤ z := by rw [forall_swap, forall_forall_merge] /-- The `ωSup` operator for continuous functions, which takes the pointwise countable supremum of the functions in the `ω`-chain. -/ @[simps!] protected def ωSup (c : Chain (α →𝒄 β)) : α →𝒄 β where toOrderHom := ωSup <| c.map toMono map_ωSup' c' := eq_of_forall_ge_iff fun a ↦ by simp [(c _).ωScottContinuous.map_ωSup] @[simps ωSup] instance : OmegaCompletePartialOrder (α →𝒄 β) := OmegaCompletePartialOrder.lift ContinuousHom.toMono ContinuousHom.ωSup (fun _ _ h => h) (fun _ => rfl) namespace Prod /-- The application of continuous functions as a continuous function. -/ @[simps] def apply : (α →𝒄 β) × α →𝒄 β where toFun f := f.1 f.2 monotone' x y h := by dsimp trans y.fst x.snd <;> [apply h.1; apply y.1.monotone h.2] map_ωSup' c := by apply le_antisymm · apply ωSup_le intro i dsimp rw [(c _).fst.continuous] apply ωSup_le intro j apply le_ωSup_of_le (max i j) apply apply_mono · exact monotone_fst (OrderHom.mono _ (le_max_left _ _)) · exact monotone_snd (OrderHom.mono _ (le_max_right _ _)) · apply ωSup_le intro i apply le_ωSup_of_le i dsimp apply OrderHom.mono _ apply le_ωSup_of_le i rfl end Prod theorem ωSup_apply_ωSup (c₀ : Chain (α →𝒄 β)) (c₁ : Chain α) : ωSup c₀ (ωSup c₁) = Prod.apply (ωSup (c₀.zip c₁)) := by simp [Prod.apply_apply, Prod.ωSup_zip] /-- A family of continuous functions yields a continuous family of functions. -/ @[simps] def flip {α : Type*} (f : α → β →𝒄 γ) : β →𝒄 α → γ where toFun x y := f y x monotone' _ _ h a := (f a).monotone h map_ωSup' _ := by ext x; change f _ _ = _; rw [(f _).continuous]; rfl /-- `Part.bind` as a continuous function. -/ @[simps! apply] noncomputable def bind {β γ : Type v} (f : α →𝒄 Part β) (g : α →𝒄 β → Part γ) : α →𝒄 Part γ := .mk (OrderHom.partBind f g.toOrderHom) fun c => by rw [ωSup_bind, ← f.continuous, g.toOrderHom_eq_coe, ← g.continuous] rfl /-- `Part.map` as a continuous function. -/ @[simps! apply] noncomputable def map {β γ : Type v} (f : β → γ) (g : α →𝒄 Part β) : α →𝒄 Part γ := .copy (fun x => f <$> g x) (bind g (const (pure ∘ f))) <| by ext1 simp only [map_eq_bind_pure_comp, bind, coe_mk, OrderHom.partBind_coe, coe_apply, coe_toOrderHom, const_apply, Part.bind_eq_bind] /-- `Part.seq` as a continuous function. -/ @[simps! apply] noncomputable def seq {β γ : Type v} (f : α →𝒄 Part (β → γ)) (g : α →𝒄 Part β) : α →𝒄 Part γ := .copy (fun x => f x <*> g x) (bind f <| flip <| _root_.flip map g) <| by ext simp only [seq_eq_bind_map, Part.bind_eq_bind, Part.mem_bind_iff, flip_apply, _root_.flip, map_apply, bind_apply, Part.map_eq_map] end ContinuousHom namespace fixedPoints open Function /-- Iteration of a function on an initial element interpreted as a chain. -/ def iterateChain (f : α →o α) (x : α) (h : x ≤ f x) : Chain α := ⟨fun n => f^[n] x, f.monotone.monotone_iterate_of_le_map h⟩ variable (f : α →𝒄 α) (x : α) /-- The supremum of iterating a function on x arbitrary often is a fixed point -/ theorem ωSup_iterate_mem_fixedPoint (h : x ≤ f x) : ωSup (iterateChain f x h) ∈ fixedPoints f := by rw [mem_fixedPoints, IsFixedPt, f.continuous] apply le_antisymm · apply ωSup_le intro n simp only [Chain.map_coe, OrderHomClass.coe_coe, comp_apply] have : iterateChain f x h (n.succ) = f (iterateChain f x h n) := Function.iterate_succ_apply' .. rw [← this] apply le_ωSup · apply ωSup_le rintro (_ | n) · apply le_trans h change ((iterateChain f x h).map f) 0 ≤ ωSup ((iterateChain f x h).map (f : α →o α)) apply le_ωSup · have : iterateChain f x h (n.succ) = (iterateChain f x h).map f n := Function.iterate_succ_apply' .. rw [this] apply le_ωSup /-- The supremum of iterating a function on x arbitrary often is smaller than any prefixed point. A prefixed point is a value `a` with `f a ≤ a`. -/ theorem ωSup_iterate_le_prefixedPoint (h : x ≤ f x) {a : α} (h_a : f a ≤ a) (h_x_le_a : x ≤ a) : ωSup (iterateChain f x h) ≤ a := by apply ωSup_le intro n induction n with | zero => exact h_x_le_a | succ n h_ind => have : iterateChain f x h (n.succ) = f (iterateChain f x h n) := Function.iterate_succ_apply' .. rw [this] exact le_trans (f.monotone h_ind) h_a /-- The supremum of iterating a function on x arbitrary often is smaller than any fixed point. -/ theorem ωSup_iterate_le_fixedPoint (h : x ≤ f x) {a : α} (h_a : a ∈ fixedPoints f) (h_x_le_a : x ≤ a) : ωSup (iterateChain f x h) ≤ a := by rw [mem_fixedPoints] at h_a obtain h_a := Eq.le h_a exact ωSup_iterate_le_prefixedPoint f x h h_a h_x_le_a end fixedPoints end OmegaCompletePartialOrder
.lake/packages/mathlib/Mathlib/Order/Circular.lean
import Mathlib.Order.Lattice import Mathlib.Tactic.Order /-! # Circular order hierarchy This file defines circular preorders, circular partial orders and circular orders. ## Hierarchy * A ternary "betweenness" relation `btw : α → α → α → Prop` forms a `CircularOrder` if it is - reflexive: `btw a a a` - cyclic: `btw a b c → btw b c a` - antisymmetric: `btw a b c → btw c b a → a = b ∨ b = c ∨ c = a` - total: `btw a b c ∨ btw c b a` along with a strict betweenness relation `sbtw : α → α → α → Prop` which respects `sbtw a b c ↔ btw a b c ∧ ¬ btw c b a`, analogously to how `<` and `≤` are related, and is - transitive: `sbtw a b c → sbtw b d c → sbtw a d c`. * A `CircularPartialOrder` drops totality. * A `CircularPreorder` further drops antisymmetry. The intuition is that a circular order is a circle and `btw a b c` means that going around clockwise from `a` you reach `b` before `c` (`b` is between `a` and `c` is meaningless on an unoriented circle). A circular partial order is several, potentially intersecting, circles. A circular preorder is like a circular partial order, but several points can coexist. Note that the relations between `CircularPreorder`, `CircularPartialOrder` and `CircularOrder` are subtler than between `Preorder`, `PartialOrder`, `LinearOrder`. In particular, one cannot simply extend the `Btw` of a `CircularPartialOrder` to make it a `CircularOrder`. One can translate from usual orders to circular ones by "closing the necklace at infinity". See `LE.toBtw` and `LT.toSBtw`. Going the other way involves "cutting the necklace" or "rolling the necklace open". ## Examples Some concrete circular orders one encounters in the wild are `ZMod n` for `0 < n`, `Circle`, `Real.Angle`... ## Main definitions * `Set.cIcc`: Closed-closed circular interval. * `Set.cIoo`: Open-open circular interval. ## Notes There's an unsolved diamond on `OrderDual α` here. The instances `LE α → Btw αᵒᵈ` and `LT α → SBtw αᵒᵈ` can each be inferred in two ways: * `LE α` → `Btw α` → `Btw αᵒᵈ` vs `LE α` → `LE αᵒᵈ` → `Btw αᵒᵈ` * `LT α` → `SBtw α` → `SBtw αᵒᵈ` vs `LT α` → `LT αᵒᵈ` → `SBtw αᵒᵈ` The fields are propeq, but not defeq. It is temporarily fixed by turning the circularizing instances into definitions. ## TODO Antisymmetry is quite weak in the sense that there's no way to discriminate which two points are equal. This prevents defining closed-open intervals `cIco` and `cIoc` in the neat `=`-less way. We currently haven't defined them at all. What is the correct generality of "rolling the necklace" open? At least, this works for `α × β` and `β × α` where `α` is a circular order and `β` is a linear order. What's next is to define circular groups and provide instances for `ZMod n`, the usual circle group `Circle`, and `RootsOfUnity M`. What conditions do we need on `M` for this last one to work? We should have circular order homomorphisms. The typical example is `daysToMonth : DaysOfTheYear →c MonthsOfTheYear` which relates the circular order of days and the circular order of months. Is `α →c β` a good notation? ## References * https://en.wikipedia.org/wiki/Cyclic_order * https://en.wikipedia.org/wiki/Partial_cyclic_order ## Tags circular order, cyclic order, circularly ordered set, cyclically ordered set -/ assert_not_exists RelIso /-- Syntax typeclass for a betweenness relation. -/ class Btw (α : Type*) where /-- Betweenness for circular orders. `btw a b c` states that `b` is between `a` and `c` (in that order). -/ btw : α → α → α → Prop export Btw (btw) /-- Syntax typeclass for a strict betweenness relation. -/ class SBtw (α : Type*) where /-- Strict betweenness for circular orders. `sbtw a b c` states that `b` is strictly between `a` and `c` (in that order). -/ sbtw : α → α → α → Prop export SBtw (sbtw) /-- A circular preorder is the analogue of a preorder where you can loop around. `≤` and `<` are replaced by ternary relations `btw` and `sbtw`. `btw` is reflexive and cyclic. `sbtw` is transitive. -/ class CircularPreorder (α : Type*) extends Btw α, SBtw α where /-- `a` is between `a` and `a`. -/ btw_refl (a : α) : btw a a a /-- If `b` is between `a` and `c`, then `c` is between `b` and `a`. This is motivated by imagining three points on a circle. -/ btw_cyclic_left {a b c : α} : btw a b c → btw b c a sbtw := fun a b c => btw a b c ∧ ¬btw c b a /-- Strict betweenness is given by betweenness in one direction and non-betweenness in the other. I.e., if `b` is between `a` and `c` but not between `c` and `a`, then we say `b` is strictly between `a` and `c`. -/ sbtw_iff_btw_not_btw {a b c : α} : sbtw a b c ↔ btw a b c ∧ ¬btw c b a := by intros; rfl /-- For any fixed `c`, `fun a b ↦ sbtw a b c` is a transitive relation. I.e., given `a` `b` `d` `c` in that "order", if we have `b` strictly between `a` and `c`, and `d` strictly between `b` and `c`, then `d` is strictly between `a` and `c`. -/ sbtw_trans_left {a b c d : α} : sbtw a b c → sbtw b d c → sbtw a d c export CircularPreorder (btw_refl btw_cyclic_left sbtw_trans_left) /-- A circular partial order is the analogue of a partial order where you can loop around. `≤` and `<` are replaced by ternary relations `btw` and `sbtw`. `btw` is reflexive, cyclic and antisymmetric. `sbtw` is transitive. -/ class CircularPartialOrder (α : Type*) extends CircularPreorder α where /-- If `b` is between `a` and `c` and also between `c` and `a`, then at least one pair of points among `a`, `b`, `c` are identical. -/ btw_antisymm {a b c : α} : btw a b c → btw c b a → a = b ∨ b = c ∨ c = a export CircularPartialOrder (btw_antisymm) /-- A circular order is the analogue of a linear order where you can loop around. `≤` and `<` are replaced by ternary relations `btw` and `sbtw`. `btw` is reflexive, cyclic, antisymmetric and total. `sbtw` is transitive. -/ class CircularOrder (α : Type*) extends CircularPartialOrder α where /-- For any triple of points, the second is between the other two one way or another. -/ btw_total : ∀ a b c : α, btw a b c ∨ btw c b a export CircularOrder (btw_total) /-! ### Circular preorders -/ section CircularPreorder variable {α : Type*} [CircularPreorder α] theorem btw_rfl {a : α} : btw a a a := btw_refl _ -- TODO: `alias` creates a def instead of a lemma (because `btw_cyclic_left` is a def). -- alias btw_cyclic_left ← Btw.btw.cyclic_left theorem Btw.btw.cyclic_left {a b c : α} (h : btw a b c) : btw b c a := btw_cyclic_left h theorem btw_cyclic_right {a b c : α} (h : btw a b c) : btw c a b := h.cyclic_left.cyclic_left alias Btw.btw.cyclic_right := btw_cyclic_right /-- The order of the `↔` has been chosen so that `rw [btw_cyclic]` cycles to the right while `rw [← btw_cyclic]` cycles to the left (thus following the prepended arrow). -/ theorem btw_cyclic {a b c : α} : btw a b c ↔ btw c a b := ⟨btw_cyclic_right, btw_cyclic_left⟩ theorem sbtw_iff_btw_not_btw {a b c : α} : sbtw a b c ↔ btw a b c ∧ ¬btw c b a := CircularPreorder.sbtw_iff_btw_not_btw theorem btw_of_sbtw {a b c : α} (h : sbtw a b c) : btw a b c := (sbtw_iff_btw_not_btw.1 h).1 alias SBtw.sbtw.btw := btw_of_sbtw theorem not_btw_of_sbtw {a b c : α} (h : sbtw a b c) : ¬btw c b a := (sbtw_iff_btw_not_btw.1 h).2 alias SBtw.sbtw.not_btw := not_btw_of_sbtw theorem not_sbtw_of_btw {a b c : α} (h : btw a b c) : ¬sbtw c b a := fun h' => h'.not_btw h alias Btw.btw.not_sbtw := not_sbtw_of_btw theorem sbtw_of_btw_not_btw {a b c : α} (habc : btw a b c) (hcba : ¬btw c b a) : sbtw a b c := sbtw_iff_btw_not_btw.2 ⟨habc, hcba⟩ alias Btw.btw.sbtw_of_not_btw := sbtw_of_btw_not_btw theorem sbtw_cyclic_left {a b c : α} (h : sbtw a b c) : sbtw b c a := h.btw.cyclic_left.sbtw_of_not_btw fun h' => h.not_btw h'.cyclic_left alias SBtw.sbtw.cyclic_left := sbtw_cyclic_left theorem sbtw_cyclic_right {a b c : α} (h : sbtw a b c) : sbtw c a b := h.cyclic_left.cyclic_left alias SBtw.sbtw.cyclic_right := sbtw_cyclic_right /-- The order of the `↔` has been chosen so that `rw [sbtw_cyclic]` cycles to the right while `rw [← sbtw_cyclic]` cycles to the left (thus following the prepended arrow). -/ theorem sbtw_cyclic {a b c : α} : sbtw a b c ↔ sbtw c a b := ⟨sbtw_cyclic_right, sbtw_cyclic_left⟩ -- TODO: `alias` creates a def instead of a lemma (because `sbtw_trans_left` is a def). -- alias btw_trans_left ← SBtw.sbtw.trans_left theorem SBtw.sbtw.trans_left {a b c d : α} (h : sbtw a b c) : sbtw b d c → sbtw a d c := sbtw_trans_left h theorem sbtw_trans_right {a b c d : α} (hbc : sbtw a b c) (hcd : sbtw a c d) : sbtw a b d := (hbc.cyclic_left.trans_left hcd.cyclic_left).cyclic_right alias SBtw.sbtw.trans_right := sbtw_trans_right theorem sbtw_asymm {a b c : α} (h : sbtw a b c) : ¬sbtw c b a := h.btw.not_sbtw alias SBtw.sbtw.not_sbtw := sbtw_asymm theorem sbtw_irrefl_left_right {a b : α} : ¬sbtw a b a := fun h => h.not_btw h.btw theorem sbtw_irrefl_left {a b : α} : ¬sbtw a a b := fun h => sbtw_irrefl_left_right h.cyclic_left theorem sbtw_irrefl_right {a b : α} : ¬sbtw a b b := fun h => sbtw_irrefl_left_right h.cyclic_right theorem sbtw_irrefl (a : α) : ¬sbtw a a a := sbtw_irrefl_left_right end CircularPreorder /-! ### Circular partial orders -/ section CircularPartialOrder variable {α : Type*} [CircularPartialOrder α] -- TODO: `alias` creates a def instead of a lemma (because `btw_antisymm` is a def). -- alias btw_antisymm ← Btw.btw.antisymm theorem Btw.btw.antisymm {a b c : α} (h : btw a b c) : btw c b a → a = b ∨ b = c ∨ c = a := btw_antisymm h end CircularPartialOrder /-! ### Circular orders -/ section CircularOrder variable {α : Type*} [CircularOrder α] theorem btw_refl_left_right (a b : α) : btw a b a := or_self_iff.1 (btw_total a b a) theorem btw_rfl_left_right {a b : α} : btw a b a := btw_refl_left_right _ _ theorem btw_refl_left (a b : α) : btw a a b := btw_rfl_left_right.cyclic_right theorem btw_rfl_left {a b : α} : btw a a b := btw_refl_left _ _ theorem btw_refl_right (a b : α) : btw a b b := btw_rfl_left_right.cyclic_left theorem btw_rfl_right {a b : α} : btw a b b := btw_refl_right _ _ theorem sbtw_iff_not_btw {a b c : α} : sbtw a b c ↔ ¬btw c b a := by rw [sbtw_iff_btw_not_btw] exact and_iff_right_of_imp (btw_total _ _ _).resolve_left theorem btw_iff_not_sbtw {a b c : α} : btw a b c ↔ ¬sbtw c b a := iff_not_comm.1 sbtw_iff_not_btw end CircularOrder /-! ### Circular intervals -/ namespace Set section CircularPreorder variable {α : Type*} [CircularPreorder α] /-- Closed-closed circular interval -/ def cIcc (a b : α) : Set α := { x | btw a x b } /-- Open-open circular interval -/ def cIoo (a b : α) : Set α := { x | sbtw a x b } @[simp] theorem mem_cIcc {a b x : α} : x ∈ cIcc a b ↔ btw a x b := Iff.rfl @[simp] theorem mem_cIoo {a b x : α} : x ∈ cIoo a b ↔ sbtw a x b := Iff.rfl end CircularPreorder section CircularOrder variable {α : Type*} [CircularOrder α] theorem left_mem_cIcc (a b : α) : a ∈ cIcc a b := btw_rfl_left theorem right_mem_cIcc (a b : α) : b ∈ cIcc a b := btw_rfl_right theorem compl_cIcc {a b : α} : (cIcc a b)ᶜ = cIoo b a := by ext rw [Set.mem_cIoo, sbtw_iff_not_btw, cIcc, mem_compl_iff, mem_setOf] theorem compl_cIoo {a b : α} : (cIoo a b)ᶜ = cIcc b a := by ext rw [Set.mem_cIcc, btw_iff_not_sbtw, cIoo, mem_compl_iff, mem_setOf] end CircularOrder end Set /-! ### Circularizing instances -/ /-- The betweenness relation obtained from "looping around" `≤`. See note [reducible non-instances]. -/ abbrev LE.toBtw (α : Type*) [LE α] : Btw α where btw a b c := a ≤ b ∧ b ≤ c ∨ b ≤ c ∧ c ≤ a ∨ c ≤ a ∧ a ≤ b /-- The strict betweenness relation obtained from "looping around" `<`. See note [reducible non-instances]. -/ abbrev LT.toSBtw (α : Type*) [LT α] : SBtw α where sbtw a b c := a < b ∧ b < c ∨ b < c ∧ c < a ∨ c < a ∧ a < b section variable {α : Type*} {a b c : α} attribute [local instance] LE.toBtw LT.toSBtw /-- The following lemmas are about the non-instances `LE.toBtw`, `LT.toSBtw` and `LinearOrder.toCircularOrder`. -/ lemma btw_iff [LE α] : btw a b c ↔ a ≤ b ∧ b ≤ c ∨ b ≤ c ∧ c ≤ a ∨ c ≤ a ∧ a ≤ b := .rfl /-- The following lemmas are about the non-instances `LE.toBtw`, `LT.toSBtw` and `LinearOrder.toCircularOrder`. -/ lemma sbtw_iff [LT α] : sbtw a b c ↔ a < b ∧ b < c ∨ b < c ∧ c < a ∨ c < a ∧ a < b := .rfl end /-- The circular preorder obtained from "looping around" a preorder. See note [reducible non-instances]. -/ abbrev Preorder.toCircularPreorder (α : Type*) [Preorder α] : CircularPreorder α where btw a b c := a ≤ b ∧ b ≤ c ∨ b ≤ c ∧ c ≤ a ∨ c ≤ a ∧ a ≤ b sbtw a b c := a < b ∧ b < c ∨ b < c ∧ c < a ∨ c < a ∧ a < b btw_refl _ := .inl ⟨le_rfl, le_rfl⟩ btw_cyclic_left {a b c} := .rotate sbtw_trans_left {a b c d} := by rintro (⟨hab, hbc⟩ | ⟨hbc, hca⟩ | ⟨hca, hab⟩) (⟨hbd, hdc⟩ | ⟨hdc, hcb⟩ | ⟨hcb, hbd⟩) <;> first | refine .inl ?_; constructor <;> order | refine .inr <| .inl ?_; constructor <;> order | refine .inr <| .inr ?_; constructor <;> order sbtw_iff_btw_not_btw {a b c} := by simp_rw [lt_iff_le_not_ge] grind /-- The circular partial order obtained from "looping around" a partial order. See note [reducible non-instances]. -/ abbrev PartialOrder.toCircularPartialOrder (α : Type*) [PartialOrder α] : CircularPartialOrder α := { Preorder.toCircularPreorder α with btw_antisymm := fun {a b c} => by rintro (⟨hab, hbc⟩ | ⟨hbc, hca⟩ | ⟨hca, hab⟩) (⟨hcb, hba⟩ | ⟨hba, hac⟩ | ⟨hac, hcb⟩) · exact Or.inl (hab.antisymm hba) · exact Or.inl (hab.antisymm hba) · exact Or.inr (Or.inl <| hbc.antisymm hcb) · exact Or.inr (Or.inl <| hbc.antisymm hcb) · exact Or.inr (Or.inr <| hca.antisymm hac) · exact Or.inr (Or.inl <| hbc.antisymm hcb) · exact Or.inl (hab.antisymm hba) · exact Or.inl (hab.antisymm hba) · exact Or.inr (Or.inr <| hca.antisymm hac) } /-- The circular order obtained from "looping around" a linear order. See note [reducible non-instances]. -/ abbrev LinearOrder.toCircularOrder (α : Type*) [LinearOrder α] : CircularOrder α := { PartialOrder.toCircularPartialOrder α with btw_total := fun a b c => by rcases le_total a b with hab | hba <;> rcases le_total b c with hbc | hcb <;> rcases le_total c a with hca | hac · exact Or.inl (Or.inl ⟨hab, hbc⟩) · exact Or.inl (Or.inl ⟨hab, hbc⟩) · exact Or.inl (Or.inr <| Or.inr ⟨hca, hab⟩) · exact Or.inr (Or.inr <| Or.inr ⟨hac, hcb⟩) · exact Or.inl (Or.inr <| Or.inl ⟨hbc, hca⟩) · exact Or.inr (Or.inr <| Or.inl ⟨hba, hac⟩) · exact Or.inr (Or.inl ⟨hcb, hba⟩) · exact Or.inr (Or.inr <| Or.inl ⟨hba, hac⟩) } /-! ### Dual constructions -/ namespace OrderDual instance btw (α : Type*) [Btw α] : Btw αᵒᵈ := ⟨fun a b c : α => Btw.btw c b a⟩ instance sbtw (α : Type*) [SBtw α] : SBtw αᵒᵈ := ⟨fun a b c : α => SBtw.sbtw c b a⟩ instance circularPreorder (α : Type*) [CircularPreorder α] : CircularPreorder αᵒᵈ := { OrderDual.btw α, OrderDual.sbtw α with btw_refl := fun _ => @btw_refl α _ _ btw_cyclic_left := fun {_ _ _} => @btw_cyclic_right α _ _ _ _ sbtw_trans_left := fun {_ _ _ _} habc hbdc => hbdc.trans_right habc sbtw_iff_btw_not_btw := fun {a b c} => @sbtw_iff_btw_not_btw α _ c b a } instance circularPartialOrder (α : Type*) [CircularPartialOrder α] : CircularPartialOrder αᵒᵈ := { OrderDual.circularPreorder α with btw_antisymm := fun {_ _ _} habc hcba => @btw_antisymm α _ _ _ _ hcba habc } instance (α : Type*) [CircularOrder α] : CircularOrder αᵒᵈ := { OrderDual.circularPartialOrder α with btw_total := fun {a b c} => @btw_total α _ c b a } end OrderDual
.lake/packages/mathlib/Mathlib/Order/SetNotation.lean
import Mathlib.Data.Set.Operations import Mathlib.Util.Notation3 /-! # Notation classes for set supremum and infimum In this file we introduce notation for indexed suprema, infima, unions, and intersections. ## Main definitions - `SupSet α`: typeclass introducing the operation `SupSet.sSup` (exported to the root namespace); `sSup s` is the supremum of the set `s`; - `InfSet`: similar typeclass for infimum of a set; - `iSup f`, `iInf f`: supremum and infimum of an indexed family of elements, defined as `sSup (Set.range f)` and `sInf (Set.range f)`, respectively; - `Set.sUnion s`, `Set.sInter s`: same as `sSup s` and `sInf s`, but works only for sets of sets; - `Set.iUnion s`, `Set.iInter s`: same as `iSup s` and `iInf s`, but works only for indexed families of sets. ## Notation - `⨆ i, f i`, `⨅ i, f i`: supremum and infimum of an indexed family, respectively; - `⋃₀ s`, `⋂₀ s`: union and intersection of a set of sets; - `⋃ i, s i`, `⋂ i, s i`: union and intersection of an indexed family of sets. -/ open Set universe u v variable {α : Type u} {ι : Sort v} /-- Class for the `sSup` operator -/ class SupSet (α : Type*) where /-- Supremum of a set -/ sSup : Set α → α /-- Class for the `sInf` operator -/ class InfSet (α : Type*) where /-- Infimum of a set -/ sInf : Set α → α export SupSet (sSup) export InfSet (sInf) /-- Indexed supremum -/ def iSup [SupSet α] (s : ι → α) : α := sSup (range s) /-- Indexed infimum -/ def iInf [InfSet α] (s : ι → α) : α := sInf (range s) instance (priority := 50) infSet_to_nonempty (α) [InfSet α] : Nonempty α := ⟨sInf ∅⟩ instance (priority := 50) supSet_to_nonempty (α) [SupSet α] : Nonempty α := ⟨sSup ∅⟩ /-- Indexed supremum. -/ notation3 "⨆ " (...)", " r:60:(scoped f => iSup f) => r /-- Indexed infimum. -/ notation3 "⨅ " (...)", " r:60:(scoped f => iInf f) => r section delaborators open Lean Lean.PrettyPrinter.Delaborator /-- Delaborator for indexed supremum. -/ @[app_delab iSup] def iSup_delab : Delab := whenPPOption Lean.getPPNotation <| withOverApp 4 do let #[_, ι, _, f] := (← SubExpr.getExpr).getAppArgs | failure unless f.isLambda do failure let prop ← Meta.isProp ι let dep := f.bindingBody!.hasLooseBVar 0 let ppTypes ← getPPOption getPPFunBinderTypes let stx ← SubExpr.withAppArg do let dom ← SubExpr.withBindingDomain delab withBindingBodyUnusedName fun x => do let x : TSyntax `ident := .mk x let body ← delab if prop && !dep then `(⨆ (_ : $dom), $body) else if prop || ppTypes then `(⨆ ($x:ident : $dom), $body) else `(⨆ $x:ident, $body) -- Cute binders let stx : Term ← match stx with | `(⨆ $x:ident, ⨆ (_ : $y:ident ∈ $s), $body) | `(⨆ ($x:ident : $_), ⨆ (_ : $y:ident ∈ $s), $body) => if x == y then `(⨆ $x:ident ∈ $s, $body) else pure stx | _ => pure stx return stx /-- Delaborator for indexed infimum. -/ @[app_delab iInf] def iInf_delab : Delab := whenPPOption Lean.getPPNotation <| withOverApp 4 do let #[_, ι, _, f] := (← SubExpr.getExpr).getAppArgs | failure unless f.isLambda do failure let prop ← Meta.isProp ι let dep := f.bindingBody!.hasLooseBVar 0 let ppTypes ← getPPOption getPPFunBinderTypes let stx ← SubExpr.withAppArg do let dom ← SubExpr.withBindingDomain delab withBindingBodyUnusedName fun x => do let x : TSyntax `ident := .mk x let body ← delab if prop && !dep then `(⨅ (_ : $dom), $body) else if prop || ppTypes then `(⨅ ($x:ident : $dom), $body) else `(⨅ $x:ident, $body) -- Cute binders let stx : Term ← match stx with | `(⨅ $x:ident, ⨅ (_ : $y:ident ∈ $s), $body) | `(⨅ ($x:ident : $_), ⨅ (_ : $y:ident ∈ $s), $body) => if x == y then `(⨅ $x:ident ∈ $s, $body) else pure stx | _ => pure stx return stx end delaborators namespace Set instance : InfSet (Set α) := ⟨fun s => { a | ∀ t ∈ s, a ∈ t }⟩ instance : SupSet (Set α) := ⟨fun s => { a | ∃ t ∈ s, a ∈ t }⟩ /-- Intersection of a set of sets. -/ def sInter (S : Set (Set α)) : Set α := sInf S /-- Notation for `Set.sInter` Intersection of a set of sets. -/ prefix:110 "⋂₀ " => sInter /-- Union of a set of sets. -/ def sUnion (S : Set (Set α)) : Set α := sSup S /-- Notation for `Set.sUnion`. Union of a set of sets. -/ prefix:110 "⋃₀ " => sUnion @[simp, grind =] theorem mem_sInter {x : α} {S : Set (Set α)} : x ∈ ⋂₀ S ↔ ∀ t ∈ S, x ∈ t := Iff.rfl @[simp, grind =] theorem mem_sUnion {x : α} {S : Set (Set α)} : x ∈ ⋃₀ S ↔ ∃ t ∈ S, x ∈ t := Iff.rfl /-- Indexed union of a family of sets -/ def iUnion (s : ι → Set α) : Set α := iSup s /-- Indexed intersection of a family of sets -/ def iInter (s : ι → Set α) : Set α := iInf s /-- Notation for `Set.iUnion`. Indexed union of a family of sets -/ notation3 "⋃ " (...)", " r:60:(scoped f => iUnion f) => r /-- Notation for `Set.iInter`. Indexed intersection of a family of sets -/ notation3 "⋂ " (...)", " r:60:(scoped f => iInter f) => r section delaborators open Lean Lean.PrettyPrinter.Delaborator /-- Delaborator for indexed unions. -/ @[app_delab Set.iUnion] def iUnion_delab : Delab := whenPPOption Lean.getPPNotation do let #[_, ι, f] := (← SubExpr.getExpr).getAppArgs | failure unless f.isLambda do failure let prop ← Meta.isProp ι let dep := f.bindingBody!.hasLooseBVar 0 let ppTypes ← getPPOption getPPFunBinderTypes let stx ← SubExpr.withAppArg do let dom ← SubExpr.withBindingDomain delab withBindingBodyUnusedName fun x => do let x : TSyntax `ident := .mk x let body ← delab if prop && !dep then `(⋃ (_ : $dom), $body) else if prop || ppTypes then `(⋃ ($x:ident : $dom), $body) else `(⋃ $x:ident, $body) -- Cute binders let stx : Term ← match stx with | `(⋃ $x:ident, ⋃ (_ : $y:ident ∈ $s), $body) | `(⋃ ($x:ident : $_), ⋃ (_ : $y:ident ∈ $s), $body) => if x == y then `(⋃ $x:ident ∈ $s, $body) else pure stx | _ => pure stx return stx /-- Delaborator for indexed intersections. -/ @[app_delab Set.iInter] def sInter_delab : Delab := whenPPOption Lean.getPPNotation do let #[_, ι, f] := (← SubExpr.getExpr).getAppArgs | failure unless f.isLambda do failure let prop ← Meta.isProp ι let dep := f.bindingBody!.hasLooseBVar 0 let ppTypes ← getPPOption getPPFunBinderTypes let stx ← SubExpr.withAppArg do let dom ← SubExpr.withBindingDomain delab withBindingBodyUnusedName fun x => do let x : TSyntax `ident := .mk x let body ← delab if prop && !dep then `(⋂ (_ : $dom), $body) else if prop || ppTypes then `(⋂ ($x:ident : $dom), $body) else `(⋂ $x:ident, $body) -- Cute binders let stx : Term ← match stx with | `(⋂ $x:ident, ⋂ (_ : $y:ident ∈ $s), $body) | `(⋂ ($x:ident : $_), ⋂ (_ : $y:ident ∈ $s), $body) => if x == y then `(⋂ $x:ident ∈ $s, $body) else pure stx | _ => pure stx return stx end delaborators @[simp] theorem mem_iUnion {x : α} {s : ι → Set α} : (x ∈ ⋃ i, s i) ↔ ∃ i, x ∈ s i := ⟨fun ⟨_, ⟨⟨a, (t_eq : s a = _)⟩, (h : x ∈ _)⟩⟩ => ⟨a, t_eq.symm ▸ h⟩, fun ⟨a, h⟩ => ⟨s a, ⟨⟨a, rfl⟩, h⟩⟩⟩ @[simp] theorem mem_iInter {x : α} {s : ι → Set α} : (x ∈ ⋂ i, s i) ↔ ∀ i, x ∈ s i := ⟨fun (h : ∀ a ∈ { a : Set α | ∃ i, s i = a }, x ∈ a) a => h (s a) ⟨a, rfl⟩, fun h _ ⟨a, (eq : s a = _)⟩ => eq ▸ h a⟩ @[simp] theorem sSup_eq_sUnion (S : Set (Set α)) : sSup S = ⋃₀ S := rfl @[simp] theorem sInf_eq_sInter (S : Set (Set α)) : sInf S = ⋂₀ S := rfl @[simp] theorem iSup_eq_iUnion (s : ι → Set α) : iSup s = iUnion s := rfl @[simp] theorem iInf_eq_iInter (s : ι → Set α) : iInf s = iInter s := rfl end Set