You are an expert Lean4 and formal verification agent proving a Lean4 theorem. Your output **must** strictly adhere to the specified format.

### Input Information
You will receive the following components, relevant to the target theorem:
* <all_available_defs>: Definitions available from imported modules (either from the current Lean repository or from Mathlib)
* <all_available_lemmas>: Lemmas/theorems available that may assist the proof.
* <local_ctx>...</local_ctx>: The local file context (imports, namespaces, definitions, comments, etc.) from the top of the file up to—but not including—the target theorem or any previously defined local lemmas/theorems.
* <target_theorem>...</target_theorem>: The target theorem statement, ending with `:=`.

**Notes**
1. Definitions include their full bodies, but for definitions whose bodies contain proofs, the proof parts are replaced by `admit` (i.e., admit /- proof elided -/), while the rest of the definition is kept unchanged; lemmas include only their statements.
2. You may freely reference any definition or lemma contained in these tags without redefining them.
3. The tags for available definitions and lemmas (all_available_defs, all_available_lemmas) may be omitted if empty.

### Output Format & Requirements
Your output MUST contain a complete, syntactically correct Lean 4 proof for the target theorem.

**Strict Output Structure:**
<reasoning> 
...
</reasoning> 

<lean4_invented_lemmas>
-- each lemma is a full Lean 4 declaration with a complete proof
...
</lean4_invented_lemmas>

<lean4_proof>
-- Lean 4 proof body of the target theorem
...
</lean4_proof>

**Requirements:**
1. <reasoning> and <lean4_invented_lemmas> are OPTIONAL. Include them only if they aid proof construction.
2. <lean4_proof> MUST contain only the proof body (tactics/terms), starting by "by", NOT the theorem declaration.
3. <lean4_invented_lemmas> (if present) MUST contain syntactically correct lemma declarations that type checks AND complete proof bodies. Defining a lemma using `axiom` is NOT allowed.
4. <reasoning> contains high-level proof planning.
5. If you create a lemma under <lean4_invented_lemmas> whose name is namespaced (e.g., X.Y.Z), you MUST always refer to it using its fully qualified name. Do NOT rely on shortened names. For example, write rw [X.Y.Z], not rw [Z] for invented lemmas.
6. All Lean 4 code MUST be syntactically correct. No `sorry`, `admit`, or non-Lean text. Comments allowed using `--` or `/- ... -/`.
7. Follow the tags and structure EXACTLY. No extra text before, between, or after the sections.
8. Do NOT wrap invented lemmas in a `mutual` block unless they have genuine mutual recursion. Declare each lemma independently.

### Examples are provided here (example input are under "User Prompt", and example assistant response are under "Agent Response"):
Example 1 ------------------- 
User Prompt:
<all_available_defs>
structure BitVec (w : Nat) where
  /-- Construct a `BitVec w` from a number less than `2^w`.
  O(1), because we use `Fin` as the internal representation of a bitvector. -/
  ofFin ::

  /-- Interpret a bitvector as a number less than `2^w`.
  O(1), because we use `Fin` as the internal representation of a bitvector. -/
  toFin : Fin (hPow 2 w)
</all_available_defs>

<all_available_lemmas>
theorem List.getElem_append_left{α : Type u_1} {l₁ l₂ : List α} {i : Nat} (hn : i < l₁.length) : (l₁ ++ l₂)[i] = l₁[i]
theorem getElem_eq_testBit_toNat (x : BitVec w) (i : Nat) (h : i < w) :
  x[i] = x.toNat.testBit i := rfl
@[simp, grind =] theorem toNat_cons (b : Bool) (x : BitVec w) :
    (cons b x).toNat = (b.toNat <<< w) ||| x.toNat
@[simp, grind =] theorem getLsbD_of_ge (x : BitVec w) (i : Nat) (ge : w ≤ i) : getLsbD x i = false
theorem testBit_toNat (x : BitVec w) : x.toNat.testBit i = x.getLsbD i
</all_available_lemmas>

<local_ctx>
import Mathlib.Computability.NFA
import Mathlib.Data.FinEnum
import Mathlib.Data.Rel
import Mathlib.Data.Vector.Basic
import Blase.AutoStructs.ForLean

open Set
open Mathlib
open SetRel

-- this is better because card is defeq to n
instance (α : Type) : Inter (Language α) := ⟨Set.inter⟩
instance (α : Type) : Union (Language α) := ⟨Set.union⟩

/--
The set of `n`-tuples of bit vectors of an arbitrary width.
-/
structure BitVecs (n : Nat) where
  w : Nat
  bvs : List.Vector (BitVec w) n

def BitVecs.cast (bvs : BitVecs n) (h : n = n') : BitVecs n' :=
  { w := bvs.w, bvs := h ▸ bvs.bvs }

abbrev BitVecs.empty : BitVecs n := ⟨0, List.Vector.replicate n .nil⟩
abbrev BitVecs.singleton {w : Nat} (bv : BitVec w) : BitVecs 1 := ⟨w, bv ::ᵥ .nil⟩
abbrev BitVecs.pair {w : Nat} (bv1 bv2 : BitVec w) : BitVecs 2 := ⟨w, bv1 ::ᵥ bv2 ::ᵥ .nil⟩

/--
The set of `n`-tuples of bit vectors of an arbitrary width, encoded as a list of
bit vectors of width `n`. The width of the encoded bit vectors is the length of
the list.
-/
abbrev BitVecs' (n : Nat) := List (BitVec n)

@[simps]
def dec (bvs' : BitVecs' n) : BitVecs n where
  w := bvs'.length
  bvs := List.Vector.ofFn fun k => BitVec.ofFn fun i => bvs'[i].getLsbD k

@[simp]
</local_ctx>

<target_theorem>
lemma dec_snoc n (bvs' : BitVecs' n) (a : BitVec n) :
  dec (bvs' ++ [a]) =
    { w := bvs'.length + 1
      bvs := List.Vector.ofFn fun k =>
        BitVec.cons (a.getLsbD k) ((dec bvs').bvs.get k) } :=
</target_theorem>

Agent Response:
<reasoning> 
The goal is to understand what `dec` does after appending one more bitvector `a` to `bvs'`. By definition, `dec` builds a width `= length` and a vector of bitvectors whose `i`-th bit at position `k` is `bvs'[i].getLsbD k`. So for `bvs' ++ [a]`, we expect the width to increase by 1 and each resulting bitvector to be `BitVec.cons` of the new bit coming from `a`.

First, I use `ext` twice: once on the record to focus on the `bvs` field, and once on the resulting bitvector. This reduces everything to a pointwise statement:
for fixed `k` and `i` with `i < bvs'.length + 1`,
the bit `(bvs' ++ [a])[i].getLsbD k` should match the bit at index `i` of `BitVec.cons (a.getLsbD k) ((dec bvs').bvs.get k)`.

At this point I need a clean description of indexing into `BitVec.cons`: if we have `x : BitVec n`, then `(cons b x)[i]` should give `b` at the new “last” index `n` and `x[i]` otherwise. That motivates an auxiliary lemma `getElem_cons` expressing exactly this behavior, proved via the `testBit`/`toNat` characterization and a case split on `i < n`, `i = n`, `i > n`.

Using `getElem_cons`, the RHS becomes an `if` on whether `i = bvs'.length`. So I split into cases:
- If `i = bvs'.length`, then `(bvs' ++ [a])[i]` is the appended `a`, so both sides reduce to `a.getLsbD k`.
- If `i ≠ bvs'.length`, the bound `i < bvs'.length + 1` forces `i < bvs'.length`. Then `(bvs' ++ [a])[i] = bvs'[i]` by `List.getElem_append_left`, and the RHS takes the “else” branch and likewise gives the bit from `bvs'[i]`. In both subcases, `simp` (plus the definition of `dec`) finishes.

So the whole proof is: `ext` to bit level, unfold `dec` with `simp_all`, rewrite with `getElem_cons`, split on the boundary index `i = length bvs'`, and in the “< length” branch use `List.getElem_append_left` and bounds to line up both sides.
</reasoning> 

<lean4_invented_lemmas>
@[grind =]
theorem getElem_cons {b : Bool} {n} {x : BitVec n} {i : Nat} (h : i < n + 1) :
    (cons b x)[i] = if h : i = n then b else x[i] := by
  simp only [BitVec.getElem_eq_testBit_toNat, BitVec.toNat_cons, Nat.testBit_or]
  rw [Nat.testBit_shiftLeft]
  rcases Nat.lt_trichotomy i n with i_lt_n | i_eq_n | n_lt_i
  · have p1 : ¬(n ≤ i) := by omega
    have p2 : i ≠ n := by omega
    simp [p1, p2]
  · simp only [i_eq_n, ge_iff_le, Nat.le_refl, decide_true, Nat.sub_self, Nat.testBit_zero,
    Bool.true_and, BitVec.testBit_toNat, BitVec.getLsbD_of_ge, Bool.or_false]
    cases b <;> trivial
  · have p1 : i ≠ n := by omega
    have p2 : i - n ≠ 0 := by omega
    simp [p1, p2, Nat.testBit_bool_toNat]
</lean4_invented_lemmas>

<lean4_proof>
by
  ext k i hi <;> simp_all
  rw [getElem_cons]
  split
  next heq => simp_all
  next h =>
    have hlt : i < List.length bvs' := by simp at hi; omega
    rw [List.getElem_append_left hlt]
    simp
</lean4_proof>

### Your task:
<all_available_defs>
noncomputable instance PosDef.Invertible [DecidableEq n] {M : Matrix n n 𝕜} (hM : M.PosDef) :
    Invertible M :=
  invertibleOfIsUnitDet M (isUnit_iff_ne_zero.2 hM.det_ne_zero)

private def minorAux (A : Matrix (Fin n.succ) (Fin n.succ) Float) (a b : Fin n.succ) :
    Matrix (Fin n) (Fin n) Float :=
  fun i j =>
    let i' : Fin n.succ := if i.val < a.val then i else i.succ;
    let j' : Fin n.succ := if j.val < b.val then j else j.succ;
    A i' j'

def minor (A : Matrix (Fin n) (Fin n) Float) (a b : Fin n) :
    Matrix (Fin n.pred) (Fin n.pred) Float :=
  match n with
  | 0 => fun _ => Fin.elim0
  | _ + 1 => minorAux A a b

def det {n : ℕ} (A : Matrix (Fin n) (Fin n) Float) : Float :=
  if h : 0 < n then
    if n == 1 then A ⟨0, h⟩ ⟨0, h⟩ else
      (List.finRange n).foldl (fun s i =>
        s + (-1) ^ (Float.ofNat i.val) * A i ⟨0, h⟩ * det (minor A i ⟨0, h⟩)) 0
  else 0

@[red]
def rewrite_constraint_5_last (hrw : ∀ x, c1 x → c2 x → c3 x → c4 x → (c5 x ↔ c5' x)) :
    ⟨f, [[c1, c2, c3, c4, c5]]⟩ ≼ ⟨f, [[c1, c2, c3, c4, c5']]⟩ :=
  ofEquivalence <| Equivalence.rewrite_constraint_5_last hrw

@[tactic removeConstr]
partial def evalRemoveConstr : Tactic := fun stx => match stx with
| `(tactic| remove_constr $id => $tacStx) => do
    (removeConstrBuilder id.getId (← `(term| by admit /- proof elided -/
    ))).toTactic
    saveTacticInfoForToken stx
| _ => throwUnsupportedSyntax

Lean.trace in Lean.Util.Trace

def setVersion (p : Problem) (v : Nat) : Problem :=
  { p with version := v }

@[command_elab atomWithBCondsCommand] unsafe def elabAtomWithBCondsCommand : CommandElab
  | `(declare_atom $id [ $curv ] $args* : $expr :=
      bconditions $bconds*
      vconditions $vconds*
      implementationVars $impVars*
      implementationObjective $impObj
      implementationConstraints $impConstrs*
      solution $sols*
      solutionEqualsAtom $solEqAtom
      feasibility $feas*
      optimality $opt
      vconditionElimination $vcondElim*) => do
    let atomData ← liftTermElabM do
      let curv ← elabCurvature curv.raw
      let (argDecls, argKinds) ← elabArgKinds args.rawImpl
      let (expr, bodyTy) ← elabExpr expr.raw argDecls
      let (bconds, _) ← elabBConds argDecls bconds.rawImpl
      let (vconds, vcondMap) ← elabVConditions argDecls vconds.rawImpl
      let (impVars, impVarMap) ← elabImpVars argDecls impVars.rawImpl
      let impObj ← elabImpObj argDecls impVars impObj.raw bodyTy
      let impConstrs ← elabImpConstrs argDecls impVars bconds impConstrs.rawImpl
      let sols ← elabSols argDecls impVars impVarMap sols.rawImpl
      let solEqAtom ← elabSolEqAtom argDecls vconds impObj sols expr solEqAtom.raw
      let feas ← elabFeas argDecls vconds bconds impConstrs sols feas.rawImpl
      let opt ← elabOpt curv argDecls expr bconds impVars impObj impConstrs argKinds opt.raw
      let vcondElim ← elabVCondElim curv argDecls bconds vconds vcondMap impVars impConstrs argKinds
        vcondElim.rawImpl

@[command_elab «equivalence»]
def evalEquivalence : CommandElab := fun stx => match stx with
  | `(equivalence $eqvId / $probId $declSig := $proofStx) => do
      liftTermElabM do
        let (binders, lhsStx) := expandDeclSig declSig.raw
        elabBindersEx binders.getArgs fun xs =>
          evalEquivalenceAux probId eqvId xs lhsStx proofStx false
  | _ => throwUnsupportedSyntax

Float.ofInt in Init.Data.OfScientific

instance ChangeOfVariables.comp {D E F} (c₁ : E → D) (c₂ : F → E) [cov₁ : ChangeOfVariables c₁]
    [cov₂ : ChangeOfVariables c₂] : ChangeOfVariables (c₁ ∘ c₂) :=
  { inv := cov₂.inv ∘ cov₁.inv
    condition := fun x => cov₁.condition x ∧ cov₂.condition (cov₁.inv x)
    property := fun x ⟨hx₁, hx₂⟩ => by admit /- proof elided -/

abbrev GraphAtomDataTree := Tree GraphAtomData Expr

let constrsOptimalityProofs := pat.optimality.constrs.map Tree.val
        let objFunOptimalityProof := pat.optimality.objFun.val
        let adjustedOptimality ←
          withLocalDeclsDNondep bconds fun bs => do
            
            
            let optimalityXsBConds := mkAppN atomData.optimality (xs ++ bs ++ vs)
            withLocalDeclsDNondep (canonConstrs.map (fun rc => (`_, rc))) fun cs => do
              
              let mut optimalityAfterCanon := optimalityXsBConds
              for i in [:canonConstrs.size] do
                let c := mkApp constrsOptimalityProofs[i]! cs[i]!
                optimalityAfterCanon := mkApp optimalityAfterCanon c
              
              
              
              
              let monoArgsCount := getMonoArgsCount objCurv atomData.argKinds
              let optCondAdjusted ←
                lambdaTelescope (← whnf optimalityAfterCanon) <| fun optArgs e => do
                
                let monoArgs := optArgs[:2 * monoArgsCount]
                let optCondition ← mkLambdaFVars optArgs[2 * monoArgsCount:] e
                let atomRange ← inferType (mkAppNBeta atomData.expr xs)
                
                let newCond ←
                  if atomData.curvature == Curvature.Convex then
                    mkAppOptM ``le_trans #[
                      atomRange, none, none, none, none,
                      optCondition, objFunOptimalityProof]
                  else
                    mkAppOptM ``le_trans #[
                      atomRange, none, none, none, none,
                      objFunOptimalityProof, optCondition]
                mkLambdaFVars monoArgs newCond

@[equiv]
def ChangeOfVariables.toEquivalence {D E R} [Preorder R] {f : D → R} {cs : D → Prop} (c : E → D)
    [cov : ChangeOfVariables c] (h : ∀ x, cs x → cov.condition x) :
    ⟨f, cs⟩ ≡ ⟨fun x => f (c x), fun x => cs (c x)⟩ :=
  Equivalence.ofStrongEquivalence <|
  { phi := fun x => cov.inv x
    psi := fun y => c y
    phi_feasibility := fun x hx => by admit /- proof elided -/

abbrev VCondsIdxsTree := Tree VCondsIdxs Unit

NNRatCast in Mathlib.Data.Rat.Init

IO.Process.Stdio.piped in Init.System.IO

def stack (eml1 eml2 : EncodedMatrixListList) : EncodedMatrixListList :=
  EncodedMatrixListList.mk (eml1.n + eml2.n) (eml1.values ++ eml2.values)

instance : ToExpr Float where
  toExpr f :=
    match Json.Parser.num f.toString.mkIterator with
    | Parsec.ParseResult.success _ res =>
        let e :=
          mkApp5
            (mkConst ``OfScientific.ofScientific [levelZero])
            (mkConst ``Float)
            (mkConst ``instOfScientificFloat)
            (toExpr res.mantissa.natAbs)
            (toExpr true)
            (toExpr res.exponent)
        if res.mantissa < 0 then
          mkApp (mkConst ``Float.neg) e
        else
          e
    | Parsec.ParseResult.error _ _  =>
        mkApp (mkConst ``Float.ofNat) (toExpr (0 : Nat))
  toTypeExpr := mkConst ``Float

Lean.ReducibilityHints.regular in Lean.Declaration

instance : ToString EggRewrite where
  toString := EggRewrite.toString

instHPow in Init.Prelude

@[equiv]
def epigraph_form : ⟨f, cs⟩ ≡ ⟨fun (t, _) => t, fun (t, x) => f x ≤ t ∧ cs x⟩ :=
  Equivalence.ofStrongEquivalence <|
  { phi := fun x => (f x, x),
    psi := fun (_, x) => x,
    phi_feasibility := fun {x} h_feas_x => by admit /- proof elided -/

structure EncodedMatrixEntry where
  i : Nat
  j : Nat
  value : Float

def opMap : HashMap String (String × Array EggTreeOpArgTag) :=
  HashMap.ofList [
    ("prob",        ("prob",    #[.arg, .arg])),
    ("objFun",      ("objFun",  #[.arg])),
    ("constr",      ("constr",  #[.arg, .arg])),
    ("constrs",     ("constrs", #[])),
    ("maximizeNeg", ("neg",     #[.arg])),
    ("var",         ("var",     #[.arg])),
    ("param",       ("param",   #[.arg])),
    ("eq",          ("eq",      #[.arg, .arg])),
    ("le",          ("le",      #[.arg, .arg])),
    ("lt",          ("lt",      #[.arg, .arg])),
    ("neg",         ("neg",     #[.arg])),
    ("inv",         ("inv",     #[.arg])),
    ("oneDiv",      ("div",     #[.val "1", .arg])),
    ("abs",         ("abs",     #[.arg])),
    ("sqrt",        ("sqrt",    #[.arg])),
    ("powOne",      ("pow",     #[.arg, .val "1"])),
    ("sq",          ("pow",     #[.arg, .val "2"])),
    ("powNegOne",   ("pow",     #[.arg, .val "-1"])),
    ("powNegTwo",   ("pow",     #[.arg, .val "-2"])),
    ("log",         ("log",     #[.arg])),
    ("exp",         ("exp",     #[.arg])),
    ("xexp",        ("xexp",    #[.arg])),
    ("entr",        ("entr",    #[.arg])),
    ("min",         ("min",     #[.arg, .arg])),
    ("max",         ("max",     #[.arg, .arg])),
    ("add",         ("add",     #[.arg, .arg])),
    ("sub",         ("sub",     #[.arg, .arg])),
    ("mul",         ("mul",     #[.arg, .arg])),
    ("mul1",        ("mul",     #[.arg, .arg])),
    ("mul2",        ("mul",     #[.arg, .arg])),
    ("mul3",        ("mul",     #[.arg, .arg])),
    ("mul4",        ("mul",     #[.arg, .arg])),
    ("div",         ("div",     #[.arg, .arg])),
    ("div1",        ("div",     #[.arg, .arg])),
    ("div2",        ("div",     #[.arg, .arg])),
    ("quadOverLin", ("qol",     #[.arg, .arg])),
    ("geoMean",     ("geo",     #[.arg, .arg])),
    ("logSumExp₂",  ("lse",     #[.arg, .arg])),
    ("norm2₂",      ("norm2",   #[.arg, .arg]))
  ]

@[equiv]
def rewrite_objFun (hrw : ∀ x, cs x → f x = g x) : ⟨f, cs⟩ ≡ ⟨g, cs⟩ :=
  Equivalence.ofStrongEquivalence <|
  { phi := id,
    psi := id,
    phi_feasibility := fun _ hx => hx
    psi_feasibility := fun _ hx => hx
    phi_optimality := fun {x} hx => le_of_eq (hrw x hx).symm
    psi_optimality := fun {x} hx => le_of_eq (hrw x hx) }

def fromExpr (e : Expr) : MetaM RelaxationExpr := do
  match e with
  | .app (.app (.app (.app (.app (.app (.const ``Minimization.Relaxation _)
      domainP) domainQ) codomain) codomainPreorder) p) q => do
      return RelaxationExpr.mk domainP domainQ codomain codomainPreorder p q
  | _ => throwError "Expression not of the form `Minimization.Relaxation ...`."

abbrev CanonExpr := Expr

EStateM.run in Init.Prelude

Max in Init.Prelude

let _ ← adjustedImpConstrs.mapM check
        trace[CvxLean.debug] "adjustedImpConstrs: {adjustedImpConstrs}"

Matrix.diag in Mathlib.Data.Matrix.Diagonal

private def constraintsTitle : Parsec Unit :=
  skipString "CONSTRAINTS" <* ws' <* endOfLine

def addCone (cp : ConeProduct) (c : Cone) : ConeProduct :=
  ConeProduct.mk (cp.n + c.dim) (cp.k + 1) (cp.cones.concat c)

Lean.addAndCompile in Lean.AddDecl

Lean.mkAnnotation in Lean.Expr

let renamedVars ← manipulateVars vars names.data
  let newDomain := composeDomain renamedVars

Lean.Parser.checkColGe in Lean.Parser.Basic

inductive SexpError
  | unmatchedOpenParen (ix: String.Iterator) : SexpError
  | unmatchedCloseParen (ix: String.Iterator) : SexpError
  | notSingleSexp (s: String) (xs: List Sexp) : SexpError
  deriving BEq, Repr

private def summaryLine (id : String) (p : Parsec α) : Parsec α :=
  summaryIdentifier id *> p <* ws' <* endOfLine

Min.min in Init.Prelude

Lean.Name.quickLt in Lean.Data.Name

@[command_elab «reductionAndBwdMap»]
def evalReductionAndBwdMap : CommandElab := fun stx => match stx with
  | `(reduction* $eqvId / $probId $declSig := $proofStx) => do
      liftTermElabM do
        let (binders, lhsStx) := expandDeclSig declSig.raw
        elabBindersEx binders.getArgs fun xs =>
          evalReductionAux probId eqvId xs lhsStx proofStx true
  | _ => throwUnsupportedSyntax

Lean.LocalDecl.cdecl in Lean.LocalContext

abbrev NewConstrsTree := Tree (Array Expr) Unit

@[equiv]
def ofReductions (R₁ : p ≼ q) (R₂ : q ≼ p) : p ≡ q :=
  { phi := R₂.psi,
    psi := R₁.psi,
    phi_optimality := R₂.psi_optimality,
    psi_optimality := R₁.psi_optimality }

def mkExistsIntro (xs : Array Expr) (e : Expr) : MetaM Expr := do
  let mut res := e
  for i in [:xs.size] do
    let x := xs[xs.size - i - 1]!
    res ← mkAppOptM ``Exists.intro
      #[none, some <| ← mkLambdaFVars #[x] (← inferType res), some x, some res]
  return res

instance : ToExpr (Array Float) :=

let newConstrProofs := pat.feasibility.fold #[] fun acc fs => fs.fold acc Array.append
        let newFeasibility ← newConstrProofs.mapM (fun e =>
          withLocalDeclsDNondep vconds fun cs => do
            withLocalDeclsDNondep bconds fun bs => do
              mkLambdaFVars (xs ++ cs ++ bs) (e.replaceFVars vs vsSol))

@[equiv]
def decompose_constraint (g : D → E) (cs' : D → E → Prop) (hc : ∀ x, cs x ↔ cs' x (g x)) :
    ⟨f, cs⟩ ≡ ⟨fun (x, _) => f x, fun (x, y) => y = g x ∧ cs' x y⟩ :=
  Equivalence.ofStrongEquivalence <|
  { phi := fun x => (x, g x),
    psi := fun (x, _) => x,
    phi_feasibility := fun {x} h_feas_x => by admit /- proof elided -/

inductive Curvature where
  | Constant | Affine | Concave | Convex | AffineSet | ConvexSet
deriving BEq, Inhabited

def elabRelaxationProof (lhs : Expr) (rhsName : Name) (stx : Syntax) : TermElabM (Expr × Expr) :=
  elabTransformationProof TransformationGoal.Relaxation lhs rhsName stx

partial def mkNewConstrs : GraphAtomDataTree → BCondsTree → NewVarsTree → CanonExprsTree →
    MetaM NewConstrsTree
  | Tree.node atom childAtoms, Tree.node bconds childBConds, Tree.node newVars childNewVars,
    Tree.node _canonExprs childCanonExprs => do
      let mut childNewConstrs := #[]
      for i in [:childAtoms.size] do
        childNewConstrs := childNewConstrs.push <|
          ← mkNewConstrs childAtoms[i]! childBConds[i]! childNewVars[i]! childCanonExprs[i]!
      let newConstrs := atom.impConstrs
      let newConstrs := newConstrs.map (mkAppNBeta · (childCanonExprs.map Tree.val))
      let newConstrs := newConstrs.map (mkAppNBeta · bconds)
      let newConstrs := newConstrs.map (mkAppNBeta · (newVars.map (mkFVar ·.fvarId)))
      return Tree.node newConstrs childNewConstrs
  | Tree.leaf _, Tree.leaf _, Tree.leaf _, Tree.leaf _ => pure <| Tree.leaf ()
  | _, _, _, _ => throwDCPError "new constraints tree mismatch."

partial def getNumericalValue? : EggTree → Option Float
  | Tree.leaf s =>
      Option.map Float.ofInt s.toInt?
  | Tree.node "neg" #[(t : EggTree)] =>
      Option.map Float.neg t.getNumericalValue?
  | Tree.node "sqrt" #[(t : EggTree)] =>
      Option.map Float.sqrt t.getNumericalValue?
  | Tree.node "log" #[(t : EggTree)] =>
      Option.map Float.log t.getNumericalValue?
  | Tree.node "exp" #[(t : EggTree)] =>
      Option.map Float.exp t.getNumericalValue?
  | Tree.node "add" #[(t1 : EggTree), (t2 : EggTree)] =>
      Option.map₂ Float.add t1.getNumericalValue? t2.getNumericalValue?
  | Tree.node "sub" #[(t1 : EggTree), (t2 : EggTree)] =>
      Option.map₂ Float.sub t1.getNumericalValue? t2.getNumericalValue?
  | Tree.node "mul" #[(t1 : EggTree), (t2 : EggTree)] =>
      Option.map₂ Float.mul t1.getNumericalValue? t2.getNumericalValue?
  | Tree.node "div" #[(t1 : EggTree), (t2 : EggTree)] =>
      Option.map₂ Float.div t1.getNumericalValue? t2.getNumericalValue?
  | Tree.node "pow" #[(t1 : EggTree), (t2 : EggTree)] =>
      Option.map₂ Float.pow t1.getNumericalValue? t2.getNumericalValue?
  | _ => none

Lean.mkApp4 in Lean.Expr

def getVariableNameSet (domain : Expr) : m (HashSet Name) := do
  let mut res : HashSet Name := {}
  for (name, _) in ← decomposeDomain domain do
    res := res.insert name
  return res

@[equiv]
def rewrite_constraint_10
    (hrw :
      ∀ x, c1 x → c2 x → c3 x → c4 x → c5 x → c6 x → c7 x → c8 x → c9 x → cs x → (c10 x ↔ c10' x)) :
    ⟨f, [[c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, cs]]⟩ ≡
    ⟨f, [[c1, c2, c3, c4, c5, c6, c7, c8, c9, c10', cs]]⟩ :=
  equivalence_of_rw_constr hrw

return (canonProblem, eqvProof)

let stdout ← IO.asTask eggProcess.stdout.readToEnd Task.Priority.dedicated
  let stdout : String ← IO.ofExcept stdout.get
  let exitCode ← eggProcess.wait
  dbg_trace s!"Egg exit code: {exitCode}"

Matrix.diagonal in Mathlib.Data.Matrix.Diagonal

def stack (ev1 ev2 : EncodedVector) : EncodedVector :=
  EncodedVector.mk (ev1.n + ev2.n) (ev1.values ++ ev2.values)

def EggOCTreeExtended := EggOCTree × Array EggDomainIdentified

Array.zipWith in Init.Data.Array.Basic

Sum in Init.Core

def solutionEqualsAtom := leading_parser withPosition <|
  nonReservedSymbol "solutionEqualsAtom" >>
  checkColGt "indented term" >> termParser

private abbrev getMatchKeyArgs (e : Expr) (root : Bool) : MetaM (Key × Array Expr) :=
  getKeyArgs e (isMatch := true) (_root := root)

def elabTransformationProof (transf : TransformationGoal) (lhs : Expr) (rhsName : Name)
    (stx : Syntax) : TermElabM (Expr × Expr) := do
  withRef stx do
    let syntheticMVarsSaved := (← get).syntheticMVars
    modify fun s => { s with syntheticMVars := {} }
    try
      
      let lhs := ← do
        let (n, _) := lhs.getAppFnArgs
        if n != ``Minimization.mk then
          let r ← unfold lhs n
          return r.expr
        else
          return lhs

structure StrongEquivalence where
  phi : D → E
  psi : E → D
  phi_feasibility : ∀ x, p.feasible x → q.feasible (phi x)
  psi_feasibility : ∀ y, q.feasible y → p.feasible (psi y)
  phi_optimality : ∀ x, p.feasible x → q.objFun (phi x) ≤ p.objFun x
  psi_optimality : ∀ y, q.feasible y → p.objFun (psi y) ≤ q.objFun y

def isEmpty (eml : EncodedMatrixList) : Prop := eml.n = 0

def p :=
  optimization (x y : ℝ)
    minimize -2 * x
    subject to
      c₁ : 0 ≤ x
      c₂ : 1 < y
      c₃ : log (y - 1) ≤ 2 * sqrt x + 1
      c₄ : 3 * x + 5 * y ≤ 10

let gsFinal ← evalTacticAt (← `(tactic| equivalence_rfl)) g
  if gsFinal.length != 0 then
    throwError "`remove_trivial_constrs` error: could not close last goal."

dotProduct in Mathlib.Data.Matrix.Mul

Finset.sum in Mathlib.Algebra.BigOperators.Group.Finset.Defs

def Vec.zeroCone {n} [Fintype n] (x : n → ℝ) : Prop :=
  ∀ i, Real.zeroCone (x i)

let ds := pat.newConstrVarsArray.map (mkFVar ·.fvarId)
              mkLambdaFVars (xs ++ bs ++ vs ++ zs ++ cs ++ ds) optCondAdjusted

Lean.Meta.MetaM in Lean.Meta.Basic

partial def mkFeasibility : GraphAtomDataTree → CanonExprsWithSolutionTree → BCondsTree →
    VCondsTree → SolEqAtomProofsTree → MetaM FeasibilityProofsTree
  | Tree.node atom childAtoms,
    Tree.node _canonWithSolution childCanonWithSolution,
    Tree.node bconds childBConds,
    Tree.node vcondVars childVCondVars,
    Tree.node _solEqAtom childSolEqAtom => do
        
        let mut childFeasibility := #[]
        for i in [:childAtoms.size] do
          let c ← mkFeasibility childAtoms[i]! childCanonWithSolution[i]! childBConds[i]!
            childVCondVars[i]! childSolEqAtom[i]!
          childFeasibility := childFeasibility.push c
        
        let mut vconds := #[]
        for i in [:vcondVars.size] do
          let mut vcondEqCanonVCond ← mkEqRefl atom.vconds[i]!.2
          for c in childSolEqAtom do
            vcondEqCanonVCond ← mkCongr vcondEqCanonVCond c.val
          vconds := vconds.push <| ← mkEqMPR vcondEqCanonVCond vcondVars[i]!
        
        let feasibility := atom.feasibility
        let feasibility := feasibility.map (mkAppN · (childCanonWithSolution.map (·.val.1)))
        let feasibility := feasibility.map (mkAppN · bconds)
        let feasibility := feasibility.map (mkAppN · vconds)
        let _ ← feasibility.mapM check
        return Tree.node feasibility childFeasibility
  | Tree.leaf _, Tree.leaf _, Tree.leaf _, Tree.leaf _, Tree.leaf _  => return Tree.leaf ()
  | _, _, _, _, _ => throwError "feasibility proofs tree mismatch."

let constrBackward ← mkLambdaFVars #[p, h] constrBackwardBody
      trace[CvxLean.debug] "ψ feasibility proof: {constrBackward}."
      trace[CvxLean.debug] "ψ feasibility proof type: {← inferType constrBackward}."
      check constrBackward

Lean.Json.str in Lean.Data.Json.Basic

return Tree.node (optimality, vcondElim) childOptimality
  | Tree.leaf e, Tree.leaf _, Tree.leaf _, Tree.leaf _, Tree.leaf _, Tree.leaf _, Tree.leaf _ => do
      trace[CvxLean.debug] "Optimality Leaf {e}."
      return Tree.leaf (← mkAppM ``le_refl #[e], #[])
  | _, _, _, _, _, _, _ =>
      throwDCPError "optimality and vcondition elimination proof tree mismatch."

let mut stepsCount := 0
    let mut g := g
    for (_componentName, steps) in stepsByComponent do
      
      
      for step in steps do
        stepsCount := stepsCount + 1
        let gs ← Tactic.run g <| (evalStep step varsNames paramsNames paramsDecls tagsMap).toTactic
        if gs.length != 1 then
          trace[CvxLean.debug] "Remaining goals: {gs}."
          throwPreDCPError "failed to rewrite {step.rewriteName} ({gs.length} goals remaining)."
        else
          trace[CvxLean.debug] "Rewrote {step.rewriteName}."
          g := gs[0]!

def cumsum (t : Fin n → α) : Fin n → α :=
  fun i => if h : 0 < n then ∑ j in [[⟨0, h⟩, i]], t j else 0

modify in Init.Prelude

InnerProductSpace in Mathlib.Analysis.InnerProductSpace.Defs

instance : ToString Summary where
  toString s :=
    s!"NAME             : {s.name} \n" ++
    s!"PROBLEM STATUS   : {s.problemStatus} \n" ++
    s!"SOLUTION STATUS  : {s.solutionStatus} \n" ++
    s!"OBJECTIVE NAME   : {s.objectiveName} \n" ++
    s!"PRIMAL OBJECTIVE : {s.primalObjective} \n" ++
    s!"DUAL OBJECTIVE   : {s.dualObjective} \n"

return (sls ++ srs, mls ++ mrs)
  | _ => throwCoeffsError "unsupported type ({ty})."

def zeroCone (x : ℝ) : Prop :=
  x = 0

instance [i : Fact (0 < n)] : OfNat (Fin n) 0 := ⟨⟨0, i.out⟩⟩

def toExpr (solExpr : SolutionExpr) : Expr :=
  mkApp4 (mkConst ``Minimization.Solution)
    solExpr.domain solExpr.codomain solExpr.codomainPreorder solExpr.p

Nat.decEq in Init.Prelude

Lean.Elab.Term.TermElabM.run in Lean.Elab.Term.TermElabM

ε in examples.Pendulum2d

Prod.mk in Init.Prelude

Lean.MessageData.paren in Lean.Message

def implementationObjective := leading_parser withPosition <|
  nonReservedSymbol "implementationObjective" >>
  checkColGt "indented term" >> termParser

Lean.FVarId.mk in Lean.Expr

private def char : Parsec Char :=
  asciiLetter <|> hexDigit <|> pchar '_' <|> fail "Invalid character."

def mkOptimalityAndVCondElimOC (originalVarsDecls : Array LocalDecl) (newVarDecls : List LocalDecl)
    (newConstrVarsArray : Array LocalDecl) (atoms : OC GraphAtomDataTree) (args : OC ArgumentsTree)
    (canonExprs : OC CanonExprsTree) (newVars : OC NewVarsTree)
    (newConstrVars : OC NewConstrVarsTree) (curvature : OC CurvatureTree) (bconds : OC BCondsTree)
    (vcondIdx : OC VCondsIdxsTree) : MetaM (OC OptimalityProofsTree × VCondElimMap):=
  withExistingLocalDecls originalVarsDecls.toList do
    withExistingLocalDecls newVarDecls do
      withExistingLocalDecls newConstrVarsArray.toList do
        let optimalityAndVCondElim ← OC.map7M mkOptimalityAndVCondElim atoms args canonExprs newVars
          newConstrVars curvature bconds
        let optimality := optimalityAndVCondElim.map (fun oce => oce.map Prod.fst Prod.fst)
        let vcondElim := optimalityAndVCondElim.map (fun oce => oce.map Prod.snd Prod.snd)
        trace[CvxLean.debug] "`optimality`: {optimality}."
        trace[CvxLean.debug] "`vcondElim`: {vcondElim}."
        trace[CvxLean.debug] "`vcondIdx`: {vcondIdx}."
        let vcondElimWithIdx ← OC.map2M (fun a b => Tree.zip a b) vcondIdx vcondElim
        let vcondElimMap := vcondElimWithIdx.fold {}
          fun (map : VCondElimMap) ci =>
            ci.fold map fun (map : VCondElimMap) ci => Id.run do
              let mut res := map
              for i in [:ci.1.size] do
                res := res.insert ci.1[i]! ci.2[i]!
              return res
        return (optimality, vcondElimMap)

instance {cp} : Decidable (isEmpty cp) := Nat.decEq _ _

@[tactic convObj]
partial def evalConvObj : Tactic := fun stx => match stx with
  | `(tactic| conv_obj => $code) => (convertObj true code).toTactic
  
  | `(tactic| conv_obj =>) => (convertObj false stx).toTactic
  | _ => throwUnsupportedSyntax

Lean.mkAtom in Init.Prelude

let vsSol := atomData.solution.map fun s => mkAppNBeta s xs

String.Pos in Init.Data.String.Defs

inductive FindAtomResult
  | Success (res : AtomDataTrees)
  | Error (msgs : Array MessageData)

instance : Trans (@Equivalence D E R _) (@StrongEquivalence E F R _) (@Equivalence D F R _) :=
  { trans := fun E S => Equivalence.trans E (ofStrongEquivalence S) }

let newConstrProofs := feasibility.fold #[] fun acc fs =>
          fs.fold acc Array.append

return forwardMap

instance : ToString SexpError where
  toString
    | .unmatchedOpenParen ix => s!"Unmatched open parenthesis at {ix}"
    | .unmatchedCloseParen ix => s!"Unmatched close parenthesis at {ix}"
    | .notSingleSexp s xs => s!"not a single sexp '{s}', parsed as: '{xs}'"

instance {α} : Inhabited (Trie α) := ⟨Trie.node #[] #[]⟩

@[command_elab «solve»]
unsafe def evalSolve : CommandElab := fun stx =>
  match stx with
  | `(solve $probInstance) =>
    liftTermElabM <| do
      let probTerm ← elabTerm probInstance.raw none
      let probTerm ← whnf probTerm
      let probTerm ← instantiateMVars probTerm

if responseType == "Error" then
    match (outJson.getObjValD "error").getStr? with
    | Except.error _ => throwError "error calling `egg`."
    | Except.ok errorMessage => throwError "from `egg` (\"{errorMessage}\")."

def findIdx' (p : α → Prop) [DecidablePred p] : List α → Option ℕ
  | []     => none
  | (a::l) => if p a then some 0 else (findIdx' p l).map Nat.succ

target EggPreDCPStopOnSuccess (pkg) : FilePath := do
  let buildDir := pkg.dir / "egg-pre-dcp"
  let binFile := buildDir / "target" / "release" / "egg-pre-dcp"
  let dest := buildDir / "utils" / "egg-pre-dcp"
  let manifestFile := buildDir / "Cargo.toml"
  buildCargo binFile manifestFile dest #[] true

NNRatCast.toOfScientific in Mathlib.Algebra.Order.Ring.Unbundled.Rat

def addEntry (ev : EncodedVector) (eve : EncodedVectorEntry) : EncodedVector :=
  if eve.value < 0 || eve.value > 0 then
    EncodedVector.mk (ev.n + 1) (ev.values.concat eve)
  else
    ev

mkLambdaFVars (xs ++ cs ++ bs) adjustedFeas
          oldFeasibilityAdjusted := oldFeasibilityAdjusted.push adjustedFeas

Lean.mkLet in Lean.Expr

Lean.Declaration.defnDecl in Lean.Declaration

Lean.MessageData.joinSep in Lean.Message

def map5M (f : α → β → γ → δ → ε → MetaM ζ) (a : OC α) (b : OC β) (c : OC γ) (d : OC δ) (e : OC ε) :
    MetaM (OC ζ) := do
  let objFun ← f a.objFun b.objFun c.objFun d.objFun e.objFun
  if a.constrs.size != b.constrs.size || b.constrs.size != c.constrs.size
    || c.constrs.size != d.constrs.size || d.constrs.size != e.constrs.size then
    throwError "`OC` error: could not map (5), different number of constraints."
  let mut constrs := #[]
  for i in [:a.constrs.size] do
    constrs := constrs.push <|
      ← f a.constrs[i]! b.constrs[i]! c.constrs[i]! d.constrs[i]! e.constrs[i]!
  return OC.mk objFun constrs

unsafe def determineCoeffsFromExpr (minExpr : MinimizationExpr) :
    MetaM (ProblemData × ScalarAffineSections) := do
  let floatDomain ← realToFloat minExpr.domain

def mkProjs (total : Nat) (h : Expr) : MetaM (List Expr) := do
  let mut acc := []
  for k in [:total] do
    let e ← mkAndProj h (total - k - 1) total
    acc := e :: acc
  return acc

Real.instNeg in Mathlib.Data.Real.Basic

instance : ToMessageData AtomData where
  toMessageData
  | AtomData.graph d => toMessageData d

let (sls₁, mls₁) ← generateBasisOfShape tyl
      let sls ← sls₁.mapM fun l => mkAppM ``Prod.mk #[l, r₀]
      let mls ← mls₁.mapM fun l => mkAppM ``Prod.mk #[l, r₀]

def mkForwardImagesNewVars (canonWithSolution : OC CanonExprsWithSolutionTree) :
    MetaM Solution := do
  let canonWithSolutionTrees := #[canonWithSolution.objFun] ++ canonWithSolution.constrs
  let mut fm := #[]
  for t in canonWithSolutionTrees do
    fm := t.fold fm (fun acc a => Array.append acc a.solution)
  return fm

@[term_elab «optimization»] def elabOptmiziation : Term.TermElab := fun stx _expectedType? => do
  match stx with
  | `(optimization $idents* $lets:letVar* $minOrMax:minOrMax $obj subject to $constraints) =>
      
      let vars ← elabVars idents
      
      let domain := Meta.composeDomain vars.data
      
      let letsStx ← preElabLetVars lets
      
      withLocalDeclD `p domain fun p => do
        
        Meta.withDomainLocalDecls domain p fun xs prs => do
          
          let mut objStx := obj
          let objIdents := Syntax.gatherIdents objStx
          if letsStx.size > 0 then
            for (letVar, letD) in letsStx do
              if letVar ∈ objIdents then
                objStx := ← `(let $letD:letDecl; $objStx)
          let mut obj := Expr.replaceFVars (← Term.elabTerm objStx.raw none) xs prs
          
          let minOrMaxStx := minOrMax.raw[0]!
          if minOrMaxStx.isOfKind `maximize then
            obj ← mkAppM ``maximizeNeg #[obj]
          else if !(minOrMaxStx.isOfKind `minimize) then
            throwParserError "expected minimize or maximize, got: {minOrMaxStx.getKind}"
          obj ← mkLambdaFVars #[p] obj
          
          let constraints ← preElabConstraints constraints
          let constraints ← constraints.mapM fun (n, cStx) => do
            let mut cStx := cStx
            let cIdents := Syntax.gatherIdents cStx
            if letsStx.size > 0 then
              for (letVar, letD) in letsStx do
                if letVar ∈ cIdents then
                  cStx := ← `(let $letD:letDecl; $cStx)
            return Meta.mkLabel n (← Term.elabTerm cStx none)
          let constraints ← mkLambdaFVars #[p] $
            Expr.replaceFVars (Meta.composeAnd constraints.data) xs prs
          
          let res ← mkAppM ``Minimization.mk #[obj, constraints]
          check res
          return ← instantiateMVars res
  | _ => throwUnsupportedSyntax

Matrix.toBlock in Mathlib.Data.Matrix.Block

Set.restrict in Mathlib.Data.Set.Restrict

Lean.mkAnd in Lean.Expr

LinearIsometryEquiv in Mathlib.Analysis.Normed.Operator.LinearIsometry

unsafe def foldMUnsafe [Monad m] (initialKeys : Array Key)
    (f : σ → Array Key → α → m σ) (init : σ) : Trie α → m σ
  | Trie.node vs children => do
    let s ← vs.foldlM (init := init) λ s v => f s initialKeys v
    children.foldlM (init := s) λ s (k, t) =>
      t.foldMUnsafe (initialKeys.push k) f s

def rewriteObjBuilderWithoutTarget (shouldEval : Bool) (tacStx : Syntax) :
    EquivalenceBuilder Unit :=
  rewriteObjBuilder shouldEval tacStx none

let r ← IO.rand 0 (2 ^ 32 - 1)
  let outputPath := s!"solver/problem{r}.sol"
  let inputPath := s!"solver/problem{r}.cbf"
  IO.FS.writeFile inputPath ""
  IO.FS.writeFile outputPath ""
  let res : Except String SolutionData ←
    IO.FS.withFile outputPath IO.FS.Mode.read fun outHandle => do
      IO.FS.withFile inputPath IO.FS.Mode.write fun inHandle => do
        
        inHandle.putStr (ToString.toString cbf)

@[term_elab prodField]
def elabProdField : TermElab :=
  fun stx _ => do
    match stx with
    | `($e # $t) => do
        match t.raw[0]! with
        | Syntax.atom _ val =>
            let some num := val.toNat? | throwUnsupportedSyntax
            let e ← elabTerm e none
            let ty ← instantiateMVars <| ← inferType e
            return ← mkProj e ty num
        | _ => throwUnsupportedSyntax
    | _ => throwUnsupportedSyntax
where
  mkProj (e ty : Expr) (n : Nat) (recursive := false) : TermElabM Expr :=
    match ty, n with
    | (.app (.app (.const ``Prod lvls) α) β), 1 => do
        return mkApp3 (mkConst ``Prod.fst lvls) α β e
    | _, 1 =>
        if recursive then return e else throwUnsupportedSyntax
    | (.app (.app (.const ``Prod lvls) α) β), (n + 1) => do
        let esnd := mkApp3 (mkConst ``Prod.snd lvls) α β e
        mkProj esnd β n true
    | _, _ => throwUnsupportedSyntax

instance : ToString Constraint where
  toString c :=
    s!"{c.index} | " ++
    s!"{c.name} | " ++
    s!"{c.status} | " ++
    s!"{c.activity} | " ++
    s!"{c.lowerLimit} | " ++
    s!"{c.upperLimit} | " ++
    s!"{c.dualLower} | " ++
    s!"{c.dualUpper}"

def addScalarConstraintsScalarVariablesCoord (p : Problem) (i : Nat) (ev : EncodedVector) :
    Problem :=
  let em := EncodedMatrix.fromIndexAndEncodedVector i ev
  { p with scalarConstraintsScalarVariablesCoord :=
      p.scalarConstraintsScalarVariablesCoord.stack em }

structure CanonExprWithSolution where
  canonExpr : CanonExpr
  solution : Solution
deriving Inhabited

instance [ToMessageData α] : ToMessageData (DiscrTree α) := ⟨fun dt => format dt⟩

structure EggDomain where
  hi : String
  lo : String
  hi_open : String
  lo_open : String

let mut oldConstrProofs := #[]
      for i in [:originalConstrVars.size] do
        if not isVCond[i]! then
          oldConstrProofs := oldConstrProofs.push <|
            ← mkAppM ``Eq.mpr #[constraintsEq[i]!, mkFVar originalConstrVars[i]!.fvarId]

@[equiv]
def rewrite_objFun_8 (hrw :
    ∀ x, c1 x → c2 x → c3 x → c4 x → c5 x → c6 x → c7 x → c8 x → f x = g x) :
    ⟨f, [[c1, c2, c3, c4, c5, c6, c7, c8]]⟩ ≡ ⟨g, [[c1, c2, c3, c4, c5, c6, c7, c8]]⟩ :=
  rewrite_objFun (fun x _ => by admit /- proof elided -/
  )

Lean.LocalDecl in Lean.LocalContext

PiLp.instNorm in Mathlib.Analysis.Normed.Lp.PiLp

let newVars := vars.map (fun ⟨n, ty⟩ => ⟨if n = varToChange then newVar else n, ty⟩)
    let newDomain := composeDomain newVars

Sum.inr in Init.Core

Lean.DefinitionSafety.safe in Lean.Declaration

@[command_elab «time_cmd»]
def evalTimeCmd : CommandElab := fun stx => match stx with
  | `(time_cmd $cmd) => do
      let before ← BaseIO.toIO IO.monoMsNow
      elabCommand cmd
      let after ← BaseIO.toIO IO.monoMsNow
      let diff := after - before
      dbg_trace s!"Command time: {diff} ms"
  | _ => throwUnsupportedSyntax

def mkOfNatExpr (i : Nat) (ty : Expr) : MetaM Expr := do
  let ie := mkNatLit i
  let inst ← synthInstance (mkApp2 (mkConst ``OfNat [levelZero]) ty ie)
  return mkApp3 (mkConst ``OfNat.ofNat [levelZero]) ty ie inst

instance (a b : Key) : Decidable (a < b) := inferInstanceAs (Decidable (Key.lt a b))

Real.rpow in Mathlib.Analysis.SpecialFunctions.Pow.Real

Lean.Parser.termParser in Lean.Parser.Basic

def preparePositivity (mvarId : MVarId) : MetaM MVarId := do
  mvarId.withContext do
    
    let mut hyps := #[]
    let le_lemmas := [``sub_nonneg_of_le, ``neg_nonneg_of_nonpos]
    let lt_lemmas := [``sub_pos_of_lt, ``neg_pos_of_neg]
    let mut lctx ← getLCtx
    for localDecl in lctx do
      let ty := localDecl.type
      for (le_or_lt, lemmas) in [(``LE.le, le_lemmas), (``LT.lt, lt_lemmas)] do
        let ty := Expr.consumeMData ty
        match ty.app4? le_or_lt with
        | some (R, _, lhs, rhs) =>
            if !(← isDefEq R q(ℝ)) then
              continue
            if ← isDefEq lhs q(0 : ℝ) then
              continue
            let le_or_lt_lemma :=
              if ← isDefEq rhs q(0 : ℝ) then lemmas[1]! else lemmas[0]!
            
            let val ← mkAppM le_or_lt_lemma #[localDecl.toExpr]
            let ty ← inferType val
            let n := localDecl.userName
            hyps := hyps.push (Hypothesis.mk n ty val)
        | none => continue

Lean.mkAppN in Lean.Expr

BEq in Init.Prelude

def fromIndexAndEncodedVectorEntry (i : Nat) (eve : EncodedVectorEntry) : EncodedMatrixEntry :=
  EncodedMatrixEntry.mk i eve.i eve.value

structure Solution where
  point : D
  isOptimal : p.optimal point

partial def generateZerosOfShape (ty : Expr) : MetaM Expr :=
  match ty.consumeMData with
  
  | .const ``Float _ =>
      return (mkFloat 0)
  
  | .forallE _ ty (.const ``Float _) _ =>
      return (mkLambda `_ BinderInfo.default ty (mkFloat 0))
  
  | .app (.app (.app (.const ``Matrix _) tyn) tym)
      (.const ``Float _) => do
      return (mkLambda `_ BinderInfo.default tyn ((mkLambda `_ BinderInfo.default tym) (mkFloat 0)))
  
  | .app (.app (.const ``Prod _) tyl) tyr => do
      let l ← generateZerosOfShape tyl
      let r ← generateZerosOfShape tyr
      return ← mkAppM ``Prod.mk #[l, r]
  | _ => throwCoeffsError "unsupported type ({ty})."

HSMul.hSMul in Init.Prelude

Matrix.mulVec in Mathlib.Data.Matrix.Mul

Lean.MessageData in Lean.Message

def Vec.rotatedSoCone (v w : m → ℝ) (X : Matrix m n ℝ) : Prop :=
  ∀ i, Real.rotatedSoCone (v i) (w i) (X i)

def _root_.MetaM.ofExcept [ToString ε]: Except ε α → MetaM α :=
  fun e =>
    match e with
    | Except.error msg => throwError (toString msg)
    | Except.ok x => return x

def changeOfVariablesBuilder (newVarStx varToChangeStx : TSyntax `ident)
    (changeStx : TSyntax `term) : EquivalenceBuilder Unit :=
  fun eqvExpr g => g.withContext do
    let newVar := newVarStx.getId
    let varToChange := varToChangeStx.getId

abbrev Arguments := Array Argument

let ocTree : OC (String × EggTree) := {
    objFun := (objFun.1, ← EggTree.adjustOps objFun.2)
    constrs := ← constr.mapIdxM <|
      
      fun i (h, c) => return (s!"{i}:" ++ h, ← EggTree.adjustOps c) }
  return (ocTree, domainConstrs)

instance : Trans (@Relaxation D E R _) (@Relaxation E F R _) (@Relaxation D F R _) :=
  { trans := Relaxation.trans }

Real.sqrt in Mathlib.Data.Real.Sqrt

def empty : EncodedMatrix := EncodedMatrix.mk 0 []

@[red]
def rewrite_constraint_4_last (hrw : ∀ x, c1 x → c2 x → c3 x → (c4 x ↔ c4' x)) :
    ⟨f, [[c1, c2, c3, c4]]⟩ ≼ ⟨f, [[c1, c2, c3, c4']]⟩ :=
  ofEquivalence <| Equivalence.rewrite_constraint_4_last hrw

def addScalarVariable (p : Problem) (c : Cone) : Problem :=
  { p with scalarVariables := p.scalarVariables.addCone c }

noncomputable instance invertible_lower : Invertible (lower hS) :=
  invertibleOfLeftInverse _ _ (mul_inv_of_invertible (lowerInv hS))

def toArray (t : DiscrTree α) : Array (Array Key × α) :=
  t.fold (init := #[]) λ as keys a => as.push (keys, a)

structure EggDomainIdentified where
  constraintName : String
  varOrParamName : String
  domain : EggDomain

Lean.ToExpr in Lean.ToExpr

Lean.Expr.consumeMData in Lean.Expr

@[red]
def rewrite_constraint_5 (hrw : ∀ x, c1 x → c2 x → c3 x → c4 x → cs x → (c5 x ↔ c5' x)) :
    ⟨f, [[c1, c2, c3, c4, c5, cs]]⟩ ≼ ⟨f, [[c1, c2, c3, c4, c5', cs]]⟩ :=
  ofEquivalence <| Equivalence.rewrite_constraint_5 hrw

structure RealToFloatData where
  real : Expr
  float : Expr
deriving BEq, Inhabited

private def insertVal [BEq α] (vs : Array α) (v : α) : Array α :=
  if vs.contains v then vs else vs.push v

@[red]
def rewrite_constraints (hrw : ∀ x, cs x ↔ cs' x) : ⟨f, [[cs]]⟩ ≼ ⟨f, [[cs']]⟩ :=
  ofEquivalence <| Equivalence.rewrite_constraints hrw

liftM in Init.Prelude

def unrotateSoCone {n : ℕ} (v w : Real) (x : Fin n → ℝ) : ℝ × (Fin n.succ → ℝ) :=
  ((v + w) / sqrt 2, Matrix.vecCons ((v - w) / sqrt 2) x)

Neg.neg in Init.Prelude

def val : Tree α α → α
  | node val _ => val
  | leaf val => val

Lean.Parser.Term.binderIdent in Lean.Parser.Term.Basic

instance : Trans (@Relaxation D E R _) (@StrongEquivalence E F R _) (@Relaxation D F R _) :=
  { trans := fun R E => Relaxation.trans R (ofStrongEquivalence E) }

abbrev NewVarsTree := Tree (Array LocalDecl) Unit

def evalEquivalenceAux (probIdStx eqvIdStx : TSyntax `ident) (xs : Array (Syntax × Expr))
    (lhsStx : Syntax) (proofStx : TSyntax `Lean.Parser.Term.byTactic) (bwdMap : Bool) :
    TermElabM Unit := do
  let D ← Meta.mkFreshTypeMVar
  let R ← Meta.mkFreshTypeMVar
  let lhsTy := mkApp2 (Lean.mkConst ``Minimization) D R
  let lhs ← elabTermAndSynthesizeEnsuringType lhsStx (some lhsTy)

instOfScientificFloat in Init.Data.OfScientific

instance {a : ℝ} : ChangeOfVariables (fun x : ℝ => x + a) :=
  { inv := fun x => x - a
    condition := fun _ => True
    property := fun _ _ => by admit /- proof elided -/

partial def size : EggTree → Nat
  | Tree.node "var" _ => 1
  | Tree.node _ children => 1 + (children.map size).foldl Nat.add 0
  | Tree.leaf _ => 1

def addPSDConstraint (p : Problem) (d : Nat) : Problem :=
  { p with PSDConstraints := p.PSDConstraints.addDimension d }

Float.pow in Init.Data.Float

let E := Meta.composeDomain canonVars.toList

def convertFullProb (shouldEval : Bool) (stx : Syntax) : EquivalenceBuilder Unit :=
  convertOpt (fullProb := true) (changeObjFun := false) do
    if shouldEval then evalTactic stx else saveTacticInfoForToken stx

String.join in Init.Data.String.Defs

partial def findVConditions (originalConstrVars : Array LocalDecl) (constraints : Array Expr) :
    GraphAtomDataTree → ArgumentsTree → MetaM PreVCondsTree
  | Tree.node atom childAtoms, Tree.node args childArgs => do
      let mut childrenVCondData := #[]
      for i in [:childAtoms.size] do
        let childVCondData ←
          findVConditions originalConstrVars constraints childAtoms[i]! childArgs[i]!
        childrenVCondData := childrenVCondData.push childVCondData
      let mut vcondData := #[]
      for (_, vcond) in atom.vconds do
        let vcond := mkAppNBeta vcond args

Matrix.vecMul in Mathlib.Data.Matrix.Mul

noncomputable def IsHermitian.sqrt {A : Matrix n n ℝ} (hA : A.IsHermitian) : Matrix n n ℝ :=
  hA.eigenvectorMatrix * Matrix.diagonal (fun i => (hA.eigenvalues i).sqrt) * hA.eigenvectorMatrixᵀ

instance : ToString ScalarAffine where
  toString sa := s!"ScalarAffine [{sa.n}, {sa.m}, {sa.A}, {sa.a}, {sa.b}]"

structure Minimization (D R : Type) where
  objFun : D → R
  constraints : D → Prop

Lean.TransformStep.continue in Lean.Meta.Transform

def fromBlocks {l : Type} {m : Type} {n : Type} {o : Type} {α : Type} :
    Matrix n l α → Matrix n m α → Matrix o l α → Matrix o m α → Matrix (n ⊕ o) (l ⊕ m) α :=
  fun A B C D i j =>
    match i with
    | Sum.inl i =>
      match j with
      | Sum.inl j => A i j
      | Sum.inr j => B i j
    | Sum.inr i =>
      match j with
      | Sum.inl j => C i j
      | Sum.inr j => D i j

def shiftingArgs (curv : Curvature) (xs : Array Expr) (argKinds : Array ArgKind)
    (mkConcl : Array Expr → Array Expr → TermElabM Expr) : TermElabM Expr :=
  withCopyOfMonoXs xs argKinds fun monoXs ys monoArgKind => do
    let mut ty := ← mkConcl monoXs ys
    for i' in [:monoXs.size] do
      let i := monoXs.size - 1 - i'
      ty ← match curvatureInArg curv monoArgKind[i]! with
      | Curvature.Concave => mkArrow (← mkLe monoXs[i]! ys[i]!) ty
      | Curvature.Convex => mkArrow (← mkLe ys[i]! monoXs[i]!) ty
      | Curvature.ConvexSet => mkArrow (← mkLe monoXs[i]! ys[i]!) ty
      | _ => throwAtomDeclarationError "invalid curvature"
    return ← mkForallFVars ys ty

@[inline]
def merge [BEq α] (t u : DiscrTree α) : DiscrTree α :=
  if t.root.size < u.root.size then loop t u else loop u t
  where

@[equiv]
def rewrite_constraint_7_last
    (hrw : ∀ x, c1 x → c2 x → c3 x → c4 x → c5 x → c6 x → (c7 x ↔ c7' x)) :
    ⟨f, [[c1, c2, c3, c4, c5, c6, c7]]⟩ ≡ ⟨f, [[c1, c2, c3, c4, c5, c6, c7']]⟩ :=
  equivalence_of_rw_constr hrw

@[default_instance]
noncomputable instance (priority := high) : HPow ℝ ℝ ℝ :=

List in Init.Prelude

instance : ToMessageData Curvature where
  toMessageData
  | Curvature.Constant => "constant"
  | Curvature.Affine => "affine"
  | Curvature.Concave => "concave"
  | Curvature.Convex => "convex"
  | Curvature.AffineSet => "affine_set"
  | Curvature.ConvexSet => "convex_set"

def map6M (h : α → β → γ → δ → ε → ζ → MetaM η) (a : OC α) (b : OC β) (c : OC γ) (d : OC δ)
    (e : OC ε) (f : OC ζ) : MetaM (OC η) := do
  let objFun ← h a.objFun b.objFun c.objFun d.objFun e.objFun f.objFun
  if a.constrs.size != b.constrs.size || b.constrs.size != c.constrs.size
    || c.constrs.size != d.constrs.size || d.constrs.size != e.constrs.size
    || e.constrs.size != f.constrs.size then
    throwError "`OC` error: could not map (6), different number of constraints."
  let mut constrs := #[]
  for i in [:a.constrs.size] do
    constrs := constrs.push <|
      ← h a.constrs[i]! b.constrs[i]! c.constrs[i]! d.constrs[i]! e.constrs[i]! f.constrs[i]!
  return OC.mk objFun constrs

Real.instMul in Mathlib.Data.Real.Basic

List.get in Init.Prelude

def parseSingleSexp (s: String) : Except SexpError Sexp := do
  match (← parseSexpList s) with
  | [x] => .ok x
  | xs => .error (.notSingleSexp s xs)

return res

Matrix.blockDiagonal in Mathlib.Data.Matrix.Block

instance : Hashable Key := ⟨Key.hash⟩

def p₃ (Awall Aflr α β γ δ : ℝ) :=
  optimization (h w d : ℝ)
    minimize (1 / (h * w * d))
    subject to
      c1 : 0 < h
      c2 : 0 < w
      c3 : 0 < d
      c4 : 2 * (h * w + h * d) ≤ Awall
      c5 : w * d ≤ Aflr
      c6 : α ≤ h / w
      c7 : h / w ≤ β
      c8 : γ ≤ d / w
      c9 : d / w ≤ δ

private def statusKey : Parsec StatusKey :=
  (skipString "UN" *> pure StatusKey.UN) <|>
  (skipString "BS" *> pure StatusKey.BS) <|>
  (skipString "SB" *> pure StatusKey.SB) <|>
  (skipString "LL" *> pure StatusKey.LL) <|>
  (skipString "UL" *> pure StatusKey.UL) <|>
  (skipString "EQ" *> pure StatusKey.EQ) <|>
  (skipString "**" *> pure StatusKey.IN) <|>
  (fail "Invalid status key.")

Lean.Expr.forallE in Lean.Expr

structure MatrixAffine :=
  (n : Nat)
  (H : Array (Array (Array Float)))
  (D : Array (Array Float))

def mkOCWithNames (objFun : Expr) (constraints : List (Name × Expr))
    (originalVarsDecls : Array LocalDecl) : MetaM (OC (Name × Expr)) := do
  withExistingLocalDecls originalVarsDecls.toList do
    let oc := OC.mk (`_, objFun) constraints.toArray
    return oc

def convertConstrs (shouldEval : Bool) (stx : Syntax) : EquivalenceBuilder Unit :=
  convertOpt (fullProb := false) (changeObjFun := false) do
    replaceMainGoal <| ← splitAnds <| ← getMainGoal
    if shouldEval then evalTactic stx else saveTacticInfoForToken stx

return ProcessedAtomTree.mk
    (originalVarsDecls := originalVarsDecls)
    (originalConstrVars := originalConstrVars)
    (newVarDecls := newVarDecls)
    (newConstrs := newConstrs)
    (newConstrVarsArray := newConstrVarsArray)
    (forwardImagesNewVars := forwardImagesNewVars)
    (constraints := constraints)
    (isVCond := isVCond)
    (vcondElimMap := vcondElimMap)
    (solEqAtom := solEqAtom)
    (feasibility := feasibility)
    (canonExprs := canonExprs)
    (optimality := optimality)

repr in Init.Data.Repr

def convertOpt (fullProb changeObjFun : Bool := false) (convTac : TacticM Unit) :
    EquivalenceBuilder Unit :=
  fun _ g => g.withContext do
    
    if let [gEq] ← g.apply (mkConst ``Minimization.Equivalence.ofEq) then
      
      let gToConv ← do
        if fullProb then
          markAsConvGoal gEq
        else
          
          let gs := List.filterMap id <| ← Conv.congr gEq
          if let [objFunGoal, constrsGoal] := gs then
            let gToIgnore := if changeObjFun then constrsGoal else objFunGoal
            let gToChange := if changeObjFun then objFunGoal else constrsGoal
            if let _ :: _ ← evalTacticAt (← `(tactic| rfl)) gToIgnore then
              let failureLocation := if changeObjFun then "constraints" else "objective function"
              throwConvOptError "failed to close {failureLocation} subgoals."
            else
            
            if let [gToConv] ← evalTacticAt (← `(conv| ext $(mkIdent `p))) gToChange then
              if let [gToConv] ← evalTacticAt (← `(conv| show_vars $(mkIdent `p))) gToConv then
                pure gToConv
              else
                throwConvOptError "failed to show optimization variables."
            else
              throwConvOptError "failed to introduce optimization variables."
          else
            throwConvOptError "unexpected goal type."

Lean.Parser.Term.ident in Lean.Parser.Term

instance : ToString EggRewriteDirection where
  toString := EggRewriteDirection.toString

def withExpr (e : Expr) (x : m α) : m α := do
  withTheReader SubExpr (fun cfg => { cfg with expr := e, pos := cfg.pos }) x

let oc ← DCP.mkOCWithNames objFun constraints originalVarsDecls
  let tree ← mkUncheckedTree originalVarsDecls paramsDecls (OC.map some oc)

instance {n : ℕ} {a : Fin n → ℝ} : ChangeOfVariables (fun (v : Fin n → ℝ) => a / v) :=
  { inv := fun v => a / v
    condition := fun v => ∀ i, v i ≠ 0 ∧ a i ≠ 0
    property := fun v hnot0 => by admit /- proof elided -/

private def tmpMVarId : MVarId := { name := `_discr_tree_tmp }

Lean.Syntax.node in Init.Prelude

instance : Inhabited ProblemData where
  default := empty

def optimality := leading_parser withPosition <|
  nonReservedSymbol "optimality" >>
  checkColGt "indented term" >> termParser

let arrayListExpr ← Expr.mkArray (← mkAppM ``List #[mkConst ``Real]) exprs

structure RelaxationExpr where
  domainP : Expr
  domainQ : Expr
  codomain : Expr
  codomainPreorder : Expr
  p : Expr
  q : Expr

def AtomExtension : Type :=
  PersistentEnvExtension
    (Array Key × AtomData) (Array Key × AtomData) (DiscrTree AtomData)
deriving Inhabited

instance : ToString EncodedMatrixListList where
  toString emll :=
    (toString emll.n) ++ "\n" ++
    (emll.values.foldl (fun acc emlle => acc ++ (toString emlle) ++ "\n") "")

script EggClean := do
  let targetDir : FilePath := "." / "egg-pre-dcp" / "target"
  let utilsDir : FilePath  := "." / "egg-pre-dcp" / "utils"
  let out ←
  IO.Process.output {
    cmd := "rm"
    args := #["-rf", targetDir.toString]
  } *>
  IO.Process.output {
    cmd := "rm"
    args := #["-rf", utilsDir.toString]
  }
  pure out.exitCode

def addEntry (eml : EncodedMatrixList) (emle : EncodedMatrixListEntry) : EncodedMatrixList :=
  if emle.value > 0 || emle.value < 0 then
    EncodedMatrixList.mk (eml.n + 1) (eml.values.concat emle)
  else
    eml

@[equiv]
def ofRelaxations (Rx₁ : p ≽' q) (Rx₂ : q ≽' p) : p ≡ q :=
  Equivalence.ofStrongEquivalence (StrongEquivalence.ofRelaxations Rx₁ Rx₂)
</all_available_defs>

<all_available_lemmas>
lemma PosDef.det_ne_zero [DecidableEq n] {M : Matrix n n 𝕜} (hM : M.PosDef) : M.det ≠ 0

lemma PosSemidef_diagonal [DecidableEq n] {f : n → ℝ} (hf : ∀ i, 0 ≤ f i) :
    (diagonal f).PosSemidef

lemma PosSemidef.conjTranspose_mul_mul (M N : Matrix n n 𝕜) (hM : M.PosSemidef) :
    (Nᴴ * M * N).PosSemidef

theorem spectral_theorem (xs : OrthonormalBasis n 𝕜 (EuclideanSpace 𝕜 n)) (as : n → ℝ)
    (hxs : ∀ j, Module.End.HasEigenvector (Matrix.toLin' A) (as j) (xs j)) :
    xs.toBasis.toMatrix (Pi.basisFun 𝕜 n) * A =
    diagonal (RCLike.ofReal ∘ as) * xs.toBasis.toMatrix (Pi.basisFun 𝕜 n)

lemma eigenspace_add {f g : End R M} {a b : R} :
    eigenspace f a ⊓ eigenspace g b ≤ eigenspace (f + g) (a + b)

lemma PosSemidef.add {M N : Matrix n n 𝕜} (hM : M.PosSemidef) (hN : N.PosSemidef) :
    (M + N).PosSemidef

lemma IsHermitian.hasEigenvector_eigenvectorBasis (hA : A.IsHermitian) (i : n) :
    Module.End.HasEigenvector (Matrix.toLin' A) (hA.eigenvalues i) (hA.eigenvectorBasis i)

lemma LogDetAtom.feasibility_exp {A : Matrix n n ℝ} (hA: A.PosDef) (i : n) :
    LDL.diagEntries hA i ≤ ((LDL.diag hA) * ((LDL.lower hA)ᵀ)).diag i

lemma has_eigenvector_add {f g : End R M} {a b : R} {x : M} (hf : HasEigenvector f a x)
    (hg : HasEigenvector g b x) : HasEigenvector (f + g) (a + b) x

lemma lower_eq_to_matrix :
    lower hS =
      ((@gramSchmidtBasis 𝕜 (n → 𝕜) _
        (NormedAddCommGroup.ofMatrix hS.transpose)
        (InnerProductSpace.ofMatrix hS.transpose)
  n _ _ _ (Pi.basisFun 𝕜 n)).toMatrix (Pi.basisFun 𝕜 n))ᵀ

lemma PosSemidef₁₁_of_PosSemidef_toBlock {A B C D : Matrix n n ℝ}
    (h : (fromBlocks A B C D).PosSemidef) : PosSemidef A

neg_pos_of_neg in Mathlib.Algebra.Order.Group.Unbundled.Basic

lemma unrotateSoCone_soCone {n : ℕ} {v w : ℝ} {x : Fin n → ℝ} (h : rotatedSoCone v w x) :
    let (t, x) := unrotateSoCone v w x; soCone t x

lemma upperTriangular.mul [Fintype m] [LinearOrder m] (hM : upperTriangular M)
    (hN : upperTriangular N) : upperTriangular (M * N)

lemma LogDetAtom.solution_eq_atom {A : Matrix n n ℝ} (hA: A.PosDef) :
    ∑ i, Real.log (LDL.diagEntries hA i) = Real.log (A.det)

lemma toBlock_inverse_mul_toBlock_eq_one_of_BlockTriangular [LinearOrder α]
    [Invertible M] (hM : BlockTriangular M b) (k : α) :
    M⁻¹.toBlock (fun i => b i < k) (fun i => b i < k) *
  M.toBlock (fun i => b i < k) (fun i => b i < k) = 1

lemma sum_exp_eq_sum_div {n} (x : Fin n → ℝ) (t : ℝ) :
    Vec.sum (Vec.exp (x - Vec.const n t)) = (Vec.sum (Vec.exp x)) / (Real.exp t)

lemma PosSemidef.mul_mul_of_IsHermitian {M N : Matrix n n 𝕜} (hM : M.PosSemidef)
    (hN : N.IsHermitian) : (N * M * N).PosSemidef

lemma isUnit_det_of_PosDef_inv [DecidableEq n] {M : Matrix n n ℝ} (h : M⁻¹.PosDef) :
    IsUnit M.det

lemma det_eq_prod_eigenvalues (xs : OrthonormalBasis n 𝕜 (EuclideanSpace 𝕜 n)) (as : n → ℝ)
    (hxs : ∀ j, Module.End.HasEigenvector (Matrix.toLin' A) (as j) (xs j)) : det A = ∏ i, as i

theorem smul_vecCons {n} [Zero α] [SMulZeroClass ℝ α] (x : ℝ) (y : α) (v : Fin n → α) :
    x • vecCons y v = vecCons (x • y) (x • v)

lemma diag_inv_mul_diag_eq_one_of_lowerTriangular [Fintype m] [LinearOrder m]
    [Invertible M] (hM : lowerTriangular M) (k : m) : M⁻¹ k k * M k k = 1

lemma sum_quadForm {n : ℕ} (R : Matrix (Fin n) (Fin n) ℝ) {m : ℕ} (y : Fin m → Fin n → ℝ) :
    ∑ i, R.quadForm (y i) = m * (covarianceMatrix y * Rᵀ).trace

neg_nonneg_of_nonpos in Mathlib.Algebra.Order.Group.Defs

lemma lowerTriangular_inv_of_lowerTriangular [Fintype m] [LinearOrder m]
    [Invertible M] (hM : lowerTriangular M) : lowerTriangular M⁻¹

theorem toUpperTri_zero {m : Type _} [LinearOrder m] :
    Matrix.toUpperTri (0 : Matrix m m ℝ) = 0

lemma has_eigenvector_one {x : M} (hx : x ≠ 0) : HasEigenvector (1 : End R M) 1 x

lemma gaussianPdf_pos {n : ℕ} (R : Matrix (Fin n) (Fin n) ℝ) (y : Fin n → ℝ) (h : R.PosDef) :
    0 < gaussianPdf R y
</all_available_lemmas>

<local_ctx>
import Mathlib.LinearAlgebra.Matrix.PosDef

import Mathlib.LinearAlgebra.Matrix.Spectrum

import Mathlib.LinearAlgebra.Eigenspace.Basic

import Mathlib.LinearAlgebra.Matrix.LDL

import Mathlib.LinearAlgebra.Matrix.DotProduct

import CvxLean.Lib.Math.LinearAlgebra.Matrix.PosDef

import CvxLean.Lib.Math.LinearAlgebra.Matrix.Spectrum

import CvxLean.Lib.Math.LinearAlgebra.Eigenspace

namespace Finset

open BigOperators

end Finset

namespace Matrix

variable {n : Type _} [Fintype n] [DecidableEq n] [LinearOrder n] [LocallyFiniteOrderBot n]

open BigOperators Matrix

namespace IsHermitian

variable {𝕜 : Type _} [DecidableEq 𝕜] [RCLike 𝕜] {A : Matrix n n 𝕜} (hA : A.IsHermitian)

end IsHermitian

noncomputable def IsHermitian.sqrt {A : Matrix n n ℝ} (hA : A.IsHermitian) : Matrix n n ℝ :=
  hA.eigenvectorMatrix * Matrix.diagonal (fun i => (hA.eigenvalues i).sqrt) * hA.eigenvectorMatrixᵀ
</local_ctx>

<target_theorem>
lemma PosSemidef.PosDef_iff_det_ne_zero [DecidableEq n] {M : Matrix n n ℝ} (hM : M.PosSemidef) :
    M.PosDef ↔ M.det ≠ 0 :=
</target_theorem>

