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>
Real.instInv in Mathlib.Data.Real.Basic

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 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 -/

def RuleToTacticExt : Type :=
  SimplePersistentEnvExtension RuleToTacticExtEntry RuleToTacticExtState
deriving Inhabited

Lean.ToMessageData in Lean.Message

Except.ok in Init.Prelude

@[tactic showVars]
def evalShowVars : Tactic
  | `(tactic| show_vars $p) => do
      replaceMainGoal [← Meta.showVars (← getMainGoal) (← withMainContext do getFVarId p)]
  | _ => throwUnsupportedSyntax

def setObjectiveShiftCoord (p : Problem) (ev : EncodedValue) : Problem :=
  { p with objectiveShiftCoord := ev }

let (_, mvarId) ← mvarId.assertHypotheses hyps

structure EncodedMatrixList where
  n : Nat
  values : List EncodedMatrixListEntry

Eq.mp in Init.Core

Float.sub in Init.Data.Float

def mkVConditions (originalVarsDecls : Array LocalDecl) (oc : OC Expr)
    (constraints : List (Name × Expr)) (atoms : OC GraphAtomDataTree) (args : OC ArgumentsTree)
    (failedAtom : OC Bool) (failedAtomMsgs : OC (Array MessageData))
    (originalConstrVars : Array LocalDecl) :
    MetaM (OC VCondsIdxsTree × Array Bool × OC VCondsTree) := do
  withExistingLocalDecls originalVarsDecls.toList do
    let vcondData ← OC.map2M (findVConditions originalConstrVars oc.constrs) atoms args

def positivityMaybeNormNum : TacticM Unit :=
  withMainContext do
    let g ← getMainGoal
    let t : Q(Prop) ← withReducible g.getType'
    let fvs := (collectFVars {} t).fvarSet
    let tac ←
      if fvs.isEmpty then
        `(tactic| (try { norm_num } <;> positivity))
      else
        `(tactic| positivity)
    let [] ← evalTacticAt tac g | throwError "`positivity_maybe_norm_num` failed."

partial def delabConstraints : DelabM (List (TSyntax ``Parser.constraint)) := do
  let e ← getExpr
  match e with
  | Expr.app (Expr.app (Expr.const `And _) _l) _r =>
      let l : TSyntax _ ← withNaryArg 0 delabConstraint
      let r : List (TSyntax _) ← withNaryArg 1 delabConstraints
      return l :: r
  | _ => return [← delabConstraint]

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})."

size in SciLean.Data.Prod

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

def fromIndexAndEncodedMatrixEntry (i : Nat) (eme : EncodedMatrixEntry) : EncodedMatrixListEntry :=
  EncodedMatrixListEntry.mk i eme.i eme.j eme.value

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

abbrev CanonExprsTree := Tree CanonExpr CanonExpr

def expCone (x y z : ℝ) : Prop :=
  (0 < y ∧ y * exp (x / y) ≤ z) ∨ (y = 0 ∧ 0 ≤ z ∧ x ≤ 0)

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

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

private def endOfLine : Parsec Unit :=
  skipChar '\u000a' <|> eof

Lean.LocalDecl.fvarId in Lean.LocalContext

if let [g] ← g.apply (mkConst ``Minimization.Equivalence.rewrite_constraints) then
      let (_, g) ← g.intros
      if let _ :: _ ← evalTacticAt (← `(tactic| tauto)) g then
        throwReorderConstrsError "failed to prove reordering correct."
    else
      throwReorderConstrsError "failed to rewrite constraints."

@[tactic reorderConstrs]
def evalReorderConstrs : Tactic := fun stx => match stx with
  | `(tactic| reorder_constrs [$ids,*]) => do
      let ids := ids.getElems.map Syntax.getId
      (reorderConstrsBuilder ids).toTactic
      saveTacticInfoForToken stx
  | _ => throwUnsupportedSyntax

def EggRewriteDirection.toString : EggRewriteDirection → String
  | Forward => "fwd"
  | Backward => "bwd"

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

def SexpM.decrementDepth: SexpM Unit :=
  modify (fun state => { state with depth := state.depth - 1 })

inductive TransformationGoal
  | Solution | Equivalence | Reduction | Relaxation

let lhsMinExpr ← MinimizationExpr.fromExpr lhs
      let D := lhsMinExpr.domain
      let E ← Meta.mkFreshTypeMVar
      let R := lhsMinExpr.codomain
      let RPreorder ← Meta.mkFreshExprMVar (mkAppN (Lean.mkConst ``Preorder [levelZero]) #[R])
      let rhs ← Meta.mkFreshExprMVar (userName := rhsName)
        (mkAppN (Lean.mkConst ``Minimization) #[E, R])
      let transfTy :=
        match transf with
          | TransformationGoal.Solution =>
              mkAppN (mkConst ``Minimization.Solution) #[D, E, R, RPreorder, lhs]
          | TransformationGoal.Equivalence =>
              mkAppN (mkConst ``Minimization.Equivalence) #[D, E, R, RPreorder, lhs, rhs]
          | TransformationGoal.Reduction =>
              mkAppN (mkConst ``Minimization.Reduction) #[D, E, R, RPreorder, lhs, rhs]
          | TransformationGoal.Relaxation =>
              mkAppN (mkConst ``Minimization.Relaxation) #[D, E, R, RPreorder, lhs, rhs]

Lean.Literal in Lean.Expr

List.get in Init.Prelude

structure DimensionList where
  n : Nat
  dimensions : List Nat

def toExpr (redExpr : ReductionExpr) : Expr :=
  mkApp6 (mkConst ``Minimization.Reduction) redExpr.domainLHS redExpr.domainRHS redExpr.codomain
    redExpr.codomainLHSreorder redExpr.lhs redExpr.rhs

Lean.Syntax.missing in Init.Prelude

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

Decidable in Init.Prelude

repr in Init.Data.Repr

Lake.proc in Lake.Util.Proc

@[equiv]
def rewrite_constraint_3 (hrw : ∀ x, c1 x → c2 x → cs x → (c3 x ↔ c3' x)) :
    ⟨f, [[c1, c2, c3, cs]]⟩ ≡ ⟨f, [[c1, c2, c3', cs]]⟩ :=
  equivalence_of_rw_constr hrw

Add in Init.Prelude

structure Summary where
  name            : String
  problemStatus   : String
  solutionStatus  : String
  objectiveName   : String
  primalObjective : Float
  dualObjective   : Float

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

@[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) }

private def summary : Parsec Summary :=
  Summary.mk <$>
  ((skipString "NAME" *> ws' *> skipChar ':' *> ws') *> pure "anonymous" <* endOfLine) <*>
  stringSummaryLine "PROBLEM STATUS"   <*>
  stringSummaryLine "SOLUTION STATUS"  <*>
  stringSummaryLine "OBJECTIVE NAME"   <*>
  floatSummaryLine  "PRIMAL OBJECTIVE" <*>
  floatSummaryLine  "DUAL OBJECTIVE"   <* ws' <* endOfLine

abbrev VCondElimMap := Std.HashMap Nat Expr

Lean.Parser.termParser in Lean.Parser.Basic

noncomputable instance instDivReal : Div ℝ :=

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

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

def isEmpty (em : EncodedMatrix) : Prop := em.n = 0

Pi.basisFun in Mathlib.LinearAlgebra.StdBasis

instance : ToExpr (Array (Array Float)) :=

def mapMwithCounter (f : Nat → α → MetaM (β × Nat)) (oc : OC α) : MetaM (OC β) := do
  let mut n := 0
  let (objFun, n') ← f n oc.objFun
  n := n'
  let mut constrs := #[]
  for constr in oc.constrs do
    let (c, n') ← f n constr
    constrs := constrs.push c
    n := n'
  return OC.mk objFun constrs

Matrix.diagonal in Mathlib.Data.Matrix.Diagonal

let rhs ← instantiateMVars rhs
      let rhs ← mkLambdaFVars (xs.map Prod.snd) rhs
      let rhs ← instantiateMVars rhs
      simpleAddDefn probId rhs

IsLeast in Mathlib.Order.Bounds.Defs

unsafe def evalFloatMatrix (e : Expr) : MetaM (Array (Array Float)) := do
  let (tyn, tym) ←
    match (← inferType e) with
    | .forallE _ tyn (.forallE _ tym (.const ``Float _) _) _ =>
        pure (tyn, tym)
    | .app (.app (.app (.const ``Matrix _) tyn) tym) (.const ``Float _) =>
        pure (tyn, tym)
    | _ => throwCoeffsError "not a float matrix ({e})."
  let elemsn ← elemsOfFintype tyn
  let elemsm ← elemsOfFintype tym
  let mut res := #[]
  for i in elemsn do
    let mut row := #[]
    for j in elemsm do
      let val ← evalFloat (mkApp2 e i j)
      row := row.push val
    res := res.push row
  return res

BaseIO in Init.System.IO

Real.instLE in Mathlib.Data.Real.Basic

Lean.LocalDeclKind.default in Lean.LocalContext

Float.mul in Init.Data.Float

def Variable.toSimpleVarSol (v : Sol.Variable) : SimpleVarSol :=
  { name := v.name,
    value := v.activity }

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

Lean.Parser.Term.bracketedBinder in Lean.Parser.Term.Basic

target EggPreDCP (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 #[] false

unsafe def unrollVectors (constraints : Expr) : MetaM (Array Expr) := do
  let mut res := #[]
  let cs ← decomposeConstraints constraints
  for (_, c) in cs do
    let c' := Expr.consumeMData c
    match c' with
    
    | .app (.app (.app (.const ``Real.Vec.zeroCone _) (.app (.const ``Fin _) n)) _) e =>
        let n : Nat ← evalExpr Nat (mkConst ``Nat) n
        for i in [:n] do
          let idxExpr ← mkFinIdxExpr i n
          let ei := mkApp e idxExpr
          res := res.push (← mkAppM ``Real.zeroCone #[ei])
    
    | .app (.app (.app (.const ``Real.Vec.nonnegOrthCone _) (.app (.const ``Fin _) n)) _) e =>
        let n : Nat ← evalExpr Nat (mkConst ``Nat) n
        for i in [:n] do
          let idxExpr ← mkFinIdxExpr i n
          let ei := mkApp e idxExpr
          res := res.push (← mkAppM ``Real.nonnegOrthCone #[ei])
    
    | .app (.app (.app (.app (.app
      (.const ``Real.Vec.expCone _) (.app (.const ``Fin _) n)) _) a) b) c =>
        let n : Nat ← evalExpr Nat (mkConst ``Nat) n
        for i in [:n] do
          let idxExpr ← mkFinIdxExpr i n
          let ai := mkApp a idxExpr
          let bi := mkApp b idxExpr
          let ci := mkApp c idxExpr
          res := res.push (← mkAppM ``Real.expCone #[ai, bi, ci])
    
    | .app (.app (.app (.app (.app (.const ``Real.Vec.soCone _)
        exprN@(.app (.const ``Fin _) _n)) (.app (.const ``Fin _) m)) finTypeN) t) X =>
        let m : Nat ← evalExpr Nat (mkConst ``Nat) m
        for i in [:m] do
          let idxExpr ← mkFinIdxExpr i m
          let ti := mkApp t idxExpr
          let Xi := mkApp X idxExpr
          res := res.push (mkAppN (mkConst ``Real.soCone) #[exprN, finTypeN, ti, Xi])
    
    
    | .app (.app (.app (.app (.app (.app (.const ``Real.Vec.rotatedSoCone _)
        exprN@(.app (.const ``Fin _) _n)) (.app (.const ``Fin _) m)) finTypeN) v) w) X =>
        let m : Nat ← evalExpr Nat (mkConst ``Nat) m
        for i in [:m] do
          let idxExpr ← mkFinIdxExpr i m
          let vi := mkApp v idxExpr
          let wi := mkApp w idxExpr
          let Xi := mkApp X idxExpr
          res := res.push (mkAppN (mkConst ``Real.rotatedSoCone) #[exprN, finTypeN, vi, wi, Xi])
    | _ =>
        res := res.push c

@[command_elab registerObjFunRuleToTactic] def elabRegisterObjFunRuleToTactic : CommandElab
| `(register_objFun_rule_to_tactic $rwName; $rwTarget => $rwGoal := $tac;) => do
    let rwNameStr := rwName.getString
    
    let _rwTargetStr := rwTarget.getString
    let _rwGoalStr := rwGoal.getString
    liftTermElabM <| addRuleToTacticEntry rwNameStr tac true
| _ => throwUnsupportedSyntax

@[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

let objFunForward := objFunForward.replaceFVars xs prs.toArray
      let objFunForward ← mkLambdaFVars #[p] objFunForward
      trace[CvxLean.debug] "φ optimality proof: {objFunForward}."
      trace[CvxLean.debug] "φ optimality proof type: {← inferType objFunForward}."
      check objFunForward

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

Lean.Elab.Term.ensureHasType in Lean.Elab.Term.TermElabM

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

Lean.Elab.Term.synthesizeSyntheticMVarsNoPostponing in Lean.Elab.SyntheticMVars

def SexpM.incrementDepth: SexpM Unit :=
  modify (fun state => { state with depth := state.depth + 1 })

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

let (constraintsData, sections) ←
    withLambdaBody minExpr.constraints fun p constraints => do
    let mut data : ProblemData := ProblemData.empty
    let mut sections := #[]

Lean.Syntax in Init.Prelude

instance {n} : ToExpr (Fin n) where
  toExpr x := mkApp (mkConst ``Fin.ofNat) (toExpr x.val)
  toTypeExpr := mkApp (mkConst ``Fin) (toExpr n)

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]!

partial def mkOptimalityAndVCondElim : GraphAtomDataTree → ArgumentsTree → CanonExprsTree →
    NewVarsTree → NewConstrVarsTree → CurvatureTree → BCondsTree →
    MetaM OptimalityAndVCondElimProofsTree
  | Tree.node atom childAtoms,
    Tree.node args childArgs,
    Tree.node _canonExpr childCanonExpr,
    Tree.node newVars childNewVars,
    Tree.node newConstrVars childNewConstrVars,
    Tree.node curvature childCurvature,
    Tree.node bconds childBConds => do
      
      let mut childOptimality := #[]
      let mut childOptimalityFiltered := #[]
      for i in [:childAtoms.size] do
        if atom.argKinds[i]! != ArgKind.Constant && atom.argKinds[i]! != ArgKind.Neither then
          let opt ← mkOptimalityAndVCondElim childAtoms[i]! childArgs[i]! childCanonExpr[i]!
              childNewVars[i]! childNewConstrVars[i]! childCurvature[i]! childBConds[i]!
          childOptimality := childOptimality.push opt
          childOptimalityFiltered := childOptimalityFiltered.push opt
        else
          childOptimality := childOptimality.push <| Tree.leaf (mkStrLit s!"dummy {args[i]!}", #[])
      let mut monoArgs := #[]
      for i in [:args.size] do
        if atom.argKinds[i]! != ArgKind.Constant && atom.argKinds[i]! != ArgKind.Neither then
          monoArgs := monoArgs.push args[i]!

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

Lean.mkApp in Lean.Expr

@[red]
def map_domain {f : D → R} {cs : D → Prop} {fwd : D → E} {bwd : E → D}
    (h : ∀ x, cs x → bwd (fwd x) = x) :
    ⟨f, cs⟩ ≼ ⟨fun x => f (bwd x), (fun x => cs (bwd x))⟩ :=
  ofEquivalence <| Equivalence.map_domain h

Lake.logInfo in Lake.Util.Log

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

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]

private def constraintsHeaders : Parsec Unit :=
  skipString "INDEX"       <* ws' <*
  skipString "NAME"        <* ws' <*
  skipString "AT"          <* ws' <*
  skipString "ACTIVITY"    <* ws' <*
  skipString "LOWER LIMIT" <* ws' <*
  skipString "UPPER LIMIT" <* ws' <*
  skipString "DUAL LOWER"  <* ws' <*
  skipString "DUAL UPPER"  <* ws' <* endOfLine

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))

@[term_elab namedConstraint]
def elabNamedConstraint : Term.TermElab := fun stx expectedType? => do
  match stx with
  | `({** $t ** $id **}) =>
      match id.raw with
      | Syntax.ident _ _ val _ =>
          let e ← Term.elabTerm t expectedType?
          return Meta.mkLabel val e
      | _ => throwUnsupportedSyntax
  | _ => throwUnsupportedSyntax

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

Alternative.failure in Init.Control.Basic

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 -/

def map (f : α → β) (oc : OC α) : OC β :=
  OC.mk (f oc.objFun) (oc.constrs.map f)

instance [ToMessageData α] [ToMessageData β] : ToMessageData (Tree α β) where
  toMessageData := toMessageData

IO.FS.Mode.read in Init.System.IO

Lean.Parser.ppSpace in Lean.Parser.Extra

let paramsDecls ← (← getLCtx).decls.toArray.filterMapM (fun decl? => do
    if let some decl := decl? then
      if (← inferType decl.type).isType then return some decl else return none
    else return none)

private def summaryIdentifier (id : String) : Parsec Unit :=
  skipString id *> ws' *> skipChar ':' *> ws'

let (stdin, eggProcess) ← eggProcess.takeStdin
  stdin.putStr requestJson

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

noncomputable instance : InnerProductSpace 𝕜 (n → 𝕜) :=
  PiLp.innerProductSpace (fun _ : n => 𝕜)

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

@[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 -/

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

Prod.snd in Init.Prelude

x in doc.literate.literate_lean_test

structure EggRewrite where
   
  rewriteName : String
   
  direction : EggRewriteDirection
   
  location : String
   
  subexprFrom : String
   
  subexprTo : String
   
  expectedTerm : String

def ofStrongEquivalence (E : p ≡' q) : p ≽' q :=
  { phi := E.phi,
    phi_feasibility := E.phi_feasibility,
    phi_optimality := E.phi_optimality }

def isEmpty (cp : ConeProduct) : Prop := cp.k = 0

Matrix.blockDiagonal in Mathlib.Data.Matrix.Block

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

IO.getEnv in Init.System.IO

Matrix.PosSemidef.sqrt in Mathlib.Analysis.Matrix.Order

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

OrderDual in Mathlib.Order.Basic

def normNumOptBuilder : EquivalenceBuilder Unit :=
  Conv.convertOpt (fullProb := true) (convTac := Mathlib.Tactic.elabNormNum1Conv mkNullNode)

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 -/

structure EncodedMatrixListListEntry where
  i : Nat
  j : Nat
  k : Nat
  l : Nat
  value : Float

Empty in Init.Prelude

Eq.mpr in Init.Core

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)

Lean.Meta.mkAppM in Lean.Meta.AppBuilder

abbrev Solution := Array NewVarAssignment

Lean.Json.parse in Lean.Data.Json.Parser

def diagonal (x : Fin n → Float) : Matrix (Fin n) (Fin n) Float :=
  fun i j => (if i = j then x i else 0)

if let _ :: _ ← g.apply fullProof then
      throwError "`remove_constr` error: failed to prove equivalence."

Lean.MVarId.getDecl in Lean.Meta.Basic

return (objFunBackward, constrBackward)

instance : ToString ConeProduct where
  toString cp :=
    (toString cp.n) ++ " " ++ (toString cp.k) ++ "\n" ++
    (cp.cones.foldl (fun acc c => acc ++ (toString c) ++ "\n") "")

def fromComponents (objFun : String × EggTree) (constr : Array (String × EggTree))
    (vars : List String) : MetaM EggOCTreeExtended := do
  let mut domainConstrs := #[]
  let mut i := 0
  for (h, c) in constr do
    
    let h := s!"{i}:" ++ h
    match processDomainExprTree h c vars with
    | some r => domainConstrs := domainConstrs.push r
    | none => pure ()
    i := i + 1

Float.add in Init.Data.Float

partial def realToFloat (e : Expr) : MetaM Expr := do
  let e ← e.removeMData
  let discrTree ← getRealToFloatDiscrTree
  let translations ← discrTree.getMatch e
  for translation in translations do
    let (mvars, _, pattern) ← lambdaMetaTelescope translation.real
    if ← isDefEq pattern e then
      \n{pattern} \n{e}"
  match e with
  | Expr.app a b => return mkApp (← realToFloat a) (← realToFloat b)
  | Expr.lam n ty b d => do
      withLocalDecl n d (← realToFloat ty) fun fvar => do
        let b := b.instantiate1 fvar
        let bF ← realToFloat b
        mkLambdaFVars #[fvar] bF
  | Expr.forallE n ty b d => do
      withLocalDecl n d (← realToFloat ty) fun fvar => do
        let b := b.instantiate1 fvar
        let bF ← realToFloat b
        mkForallFVars #[fvar] bF
  | Expr.mdata m e => return mkMData m (← realToFloat e)
  | Expr.letE n ty t b _ => return mkLet n (← realToFloat ty) (← realToFloat t) (← realToFloat b)
  | Expr.proj typeName idx struct => return mkProj typeName idx (← realToFloat struct)
  | e@(Expr.const n _) => do
      if ← isOptimizationParam n then
        let paramExpr ← getOptimizationParamExpr n e
        let paramExprF ← realToFloat paramExpr
        \n{e.toMessageData}"
        return paramExprF
      else
        return e
  | _ => return e

return constrBackward

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

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

Lean.Meta.whnf in Lean.Meta.Basic

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

let (objectiveDataA, objectiveDataB) := objectiveData
  let pd := constraintsData.setObjectiveOnlyVector objectiveDataA objectiveDataB

Lean.Elab.Term.TermElab in Lean.Elab.Term.TermElabM

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

IO.FS.Mode.write in Init.System.IO

Lean.Meta.inferType in Lean.Meta.Basic

let responseType := (outJson.getObjValD "response").getStr!

Lean.Meta.withReducible in Lean.Meta.Basic

def removeTrivialConstrsBuilder : EquivalenceBuilder Unit := fun eqvExpr g => g.withContext do
  let lhs ← eqvExpr.toMinimizationExprLHS
  let constrNames ← withLambdaBody lhs.constraints fun _ constrsBody => do
    let cs ← decomposeConstraints constrsBody
    return cs.map fun c => c.1
  let mut g := g
  for n in constrNames do
    let eqvBuilder := removeConstrBuilder n (← `(term| (by admit /- proof elided -/
    )))
    let gs ← Tactic.run g <|
      Tactic.tryCatch eqvBuilder.toTactic (fun _ => do pure ())
    if gs.length != 1 then
      throwError "`remove_trivial_constrs` error: failed to remove {n}."
    g := gs[0]!

let iffProof ← withLambdaBody newConstrs fun p newConstrsBody => do
      
      let newImpliesOld ← withLocalDeclD `h newConstrsBody fun h => do
        let l ← mkProjs (numConstrs - 1) h
        let xs := (← mkProjections lhsMinExpr.domain p).map (fun (_, _, e) => e)
        let extra := mkAppNBeta toShow ((xs ++ l).toArray)
        let l := (l.take idxToRemove).append <| extra :: l.drop idxToRemove
        return ← mkLambdaFVars #[h] <| ← composeAndIntro l
      
      let oldConstrsBody := lhsMinExpr.constraints.bindingBody!.instantiate1 p
      let oldImpliesNew ← withLocalDeclD `h oldConstrsBody fun h => do
        let l ← mkProjs numConstrs h
        let l := l.eraseIdx idxToRemove
        mkLambdaFVars #[h] <| ← composeAndIntro l
      return ← mkLambdaFVars #[p] <| ← mkAppM ``Iff.intro #[oldImpliesNew, newImpliesOld]

instance : ToString EncodedMatrixEntry where
  toString eme :=
    (toString eme.i) ++ " " ++
    (toString eme.j) ++ " " ++
    (toString eme.value)

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)

def uncheckedTreeFromMinimizationExpr (goalExprs : MinimizationExpr) : MetaM EggOCTree := do
  let (objFun, constraints, originalVarsDecls) ← withLambdaBody goalExprs.constraints
    fun p constraints => do
      let pr := (← Meta.mkProjections goalExprs.domain p).toArray
      let originalVarsDecls ←
        withLocalDeclsD (pr.map fun (n, ty, _) => (n, fun _ => return ty))
          fun xs => xs.mapM fun x => x.fvarId!.getDecl
      withExistingLocalDecls originalVarsDecls.toList do
        let xs := originalVarsDecls.map fun decl => mkFVar decl.fvarId
        let constraints ← Meta.replaceProjections constraints p.fvarId! xs
        let constraints : List (Lean.Name × Expr) ←
          Meta.decomposeConstraints constraints
        let constraints ←
          constraints.mapM (fun ((n : Lean.Name), e) => do
            return (n, ← Expr.removeMData e))
        let objFunP := goalExprs.objFun.bindingBody!.instantiate1 p
        let objFun ← Meta.replaceProjections objFunP p.fvarId! xs
        return (objFun, constraints, originalVarsDecls)

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)

def removeMData (e : Expr) : CoreM Expr := do
  let post (e : Expr) : CoreM TransformStep := do
    return TransformStep.done e.consumeMData
  Core.transform e (post := post)

Lean.Core.checkMaxHeartbeats in Lean.CoreM

-- Equivalence mode.
equivalence eqv₂/q₂ : p₂ :=

def evalStep (step : EggRewrite) (vars params : List Name) (paramsDecls : List LocalDecl)
    (tagsMap : HashMap String ℕ) : EquivalenceBuilder Unit := fun eqvExpr g => g.withContext do
  let tag ← liftMetaM <| do
    if step.location == "objFun" then
      return "objFun"
    else if let [_, tag] := step.location.splitOn ":" then
      return tag
    else
      throwPreDCPError "unexpected tag name {step.location}."
  let tagNum := tagsMap.find! step.location
  let atObjFun := tagNum == 0

def fold (oc : OC α) (init : β) (f : β → α → β) : β := Id.run do
  let b ← f init oc.objFun
  let b ← oc.constrs.foldl f b
  return b

Lean.Core.betaReduce in Lean.Meta.Transform

Finset in Mathlib.Data.Finset.Defs

@[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.Parser.ppGroup in Lean.Parser.Extra

Real.pi in Mathlib.Analysis.SpecialFunctions.Trigonometric.Basic

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

Sum.inl in Init.Core

BaseIO.toIO in Init.System.IO

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

def toMatrix {n : ℕ} (x : Fin n → α) : Matrix (Fin n) (Fin 1) α :=
  fun i => ![x i]

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

Real.instSub in Mathlib.Data.Real.Basic

abbrev VCondsTree := Tree VConds Unit

Inv in Init.Prelude

def invertible_toBlock_of_BlockTriangular [LinearOrder α] [Invertible M]
    (hM : BlockTriangular M b) (k : α) :
    Invertible (M.toBlock (fun i => b i < k) (fun i => b i < k)) :=
  invertibleOfLeftInverse _ ((⅟M).toBlock (fun i => b i < k) (fun i => b i < k))
    (by admit /- proof elided -/
      )

abbrev Argument := Expr

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

IO.Process.Stdio.null in Init.System.IO

HAdd in Init.Prelude

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

partial def mkCanonExprs : GraphAtomDataTree → NewVarsTree → MetaM CanonExprsTree
  | Tree.node atom childAtoms, Tree.node newVars childNewVars => do
      let mut childCanonExprs := #[]
      for i in [:childAtoms.size] do
        childCanonExprs := childCanonExprs.push <| ← mkCanonExprs childAtoms[i]! childNewVars[i]!
      let canonExpr := atom.impObjFun
      let canonExpr := mkAppNBeta canonExpr (childCanonExprs.map (·.val))
      let canonExpr := mkAppNBeta canonExpr (newVars.map (mkFVar ·.fvarId))
      return Tree.node canonExpr childCanonExprs
  | Tree.leaf e, Tree.leaf () => pure <| Tree.leaf e
  | _, _ => throwDCPError "canonized expressions tree mismatch."

def p₂ :=
  optimization (x : ℝ)
    minimize (x)
    subject to
      c1 : 1 / 1000 ≤ x
      c2 : 1 / sqrt x ≤ exp x

Lean.MessageData in Lean.Message

List.finRange in Init.Data.List.FinRange

instance : Inhabited SexpState where
  default := SexpState.fromString ""

def fromIndexAndEncodedMatrixList (i : Nat) (eml : EncodedMatrixList) :
    EncodedMatrixListList := Id.run <| do
  let mut emll := empty
  for emle in eml.values do
    let emlle := EncodedMatrixListListEntry.fromIndexAndEncodedMatrixList i emle
    emll := emll.addEntry emlle
  emll

Lean.Meta.transform in Lean.Meta.Transform

Lean.Parser.Term.app in Lean.Parser.Term

Finsupp in Mathlib.Data.Finsupp.Defs

def h := p₃.solution.1

unsafe def exprFromSolutionData (minExpr : MinimizationExpr) (solData : SolutionData) :
    MetaM Expr := do
  let vars ← decomposeDomainInstantiating minExpr

instance : ToString EncodedMatrixList where
  toString eml :=
    (toString eml.n) ++ "\n" ++
    (eml.values.foldl (fun acc emle => acc ++ (toString emle) ++ "\n") "")

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

inductive EggTreeOpArgTag
  | arg
  | val (s : String)

def canonize (ogProblem : MinimizationExpr) : MetaM (MinimizationExpr × Expr) := do
  let ogProblemExpr := ogProblem.toExpr
  let D := ogProblem.domain
  let R := ogProblem.codomain

structure EncodedValue where
  value : Option Float

partial def toEggString : EggTree → String
  | Tree.node n children =>
    let childrenStr := (children.map EggTree.toEggString).data
    "(" ++ n ++ " " ++ (" ".intercalate childrenStr) ++ ")"
  | Tree.leaf n => n

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 ≤ δ

partial def Sexp.toString : Sexp → String
  | .atom s  => s
  | .list xs => "(" ++ " ".intercalate (xs.map Sexp.toString) ++ ")"

Fin.ofNat in Init.Data.Fin.Basic

PiLp in Mathlib.Analysis.Normed.Lp.PiLp

let proof ← elabTerm stx (some transfTy)

def EggOCTree := OC (String × EggTree)

Lean.Syntax.atom in Init.Prelude

Lean.Meta.check in Lean.Meta.Check

def _root_.Lean.Json.getArr! (j : Json) : Array Json :=
  match j with
  | Json.arr a => a
  | _ => #[]

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

abbrev BCondsTree := Tree BConds BConds

let gCondition := gsAfterApply[0]!
    let (_, gCondition) ← gCondition.introN 2 [`x, `h]
    let gsFinal ← evalTacticAt
      (← `(tactic| (simp [ChangeOfVariables.condition] at * <;> arith))) gCondition
    if gsFinal.length != 0 then
      trace[CvxLean.debug] "Could not prove {gsFinal}."
      throwChangeOfVariablesError "failed to solve change of variables condition."

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

def EggRewrite.toString (e : EggRewrite) : String :=
  "{" ++
  surroundQuotes "rewrite_name" ++ " : " ++ surroundQuotes e.rewriteName ++ ", " ++
  surroundQuotes "direction" ++ " : " ++ surroundQuotes (e.direction.toString) ++ ", " ++
  surroundQuotes "location" ++ " : " ++ surroundQuotes e.location ++ ", " ++
  surroundQuotes "subexpr_from" ++ " : " ++ surroundQuotes e.subexprFrom ++ ", " ++
  surroundQuotes "subexpr_to" ++ " : " ++ surroundQuotes e.subexprTo ++ ", " ++
  surroundQuotes "expected_term" ++ " : " ++ surroundQuotes e.expectedTerm ++
  "}"

def entr : m → ℝ := fun i => Real.entr (x i)

let tree ← tree.mapM (fun o => match o with
    | some (n, t) => return (n, t)
    | none => throwPreDCPError "could not create unchecked DCP tree.")
  return tree

instance : ToString EncodedValue where
  toString ev := match ev.value with
    | some f => toString f
    | none => ""

partial def size : Tree α β → Nat
  | node _ children => children.foldl (fun acc child => acc + size child) 0
  | leaf _ => 1

Real.instNNRatCast in Mathlib.Data.Real.Basic

Lean.Expr.app in Lean.Expr

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

Float.ofScientific in Init.Data.OfScientific

Lean.TransformStep in Lean.Meta.Transform

Option in Init.Prelude

abbrev NewConstrVarsTree := Tree (Array LocalDecl) Unit

match transf with
    | TransformationGoal.Solution =>
        if let [eqv, sol, _, _] ← gToChange.apply (mkConst ``Minimization.Equivalence.toBwd) then
          
          gToChange := eqv
          gNext := sol
        else
          throwTacticBuilderError "could not apply equivalence tactic to `Solution`."
    | TransformationGoal.Equivalence => do
        pure ()
    | TransformationGoal.Reduction => do
        if let [eqv] ← gToChange.apply (mkConst ``Minimization.Reduction.ofEquivalence) then
          gToChange := eqv
        else
          throwTacticBuilderError "could not apply equivalence tactic to `Reduction`."
    | TransformationGoal.Relaxation => do
        throwTacticBuilderError "equivalence tactic does not apply to `Relaxation`."

let optimality ←
        match curvature, atom.curvature with
          | Curvature.Concave, Curvature.Affine => mkAppM ``And.left #[atom.optimality]
          | Curvature.Convex, Curvature.Affine => mkAppM ``And.right #[atom.optimality]
          | _, _ => pure atom.optimality
      let optimality := mkAppN optimality (childCanonExpr.map Tree.val)
      let optimality := mkAppN optimality bconds
      check optimality
      let optimality := mkAppN optimality (newVars.map (mkFVar ·.fvarId))
      let optimality := mkAppN optimality (newConstrVars.map (mkFVar ·.fvarId))
      let optimality := mkAppN optimality monoArgs
      let optimality := mkAppN optimality (childOptimalityFiltered.map (·.val.1))
      check optimality

Set.Ioi in Mathlib.Order.Interval.Set.Defs

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

noncomputable def klDiv (x y : Real) :=
  x * log (x / y) - x + y

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

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."

Mathlib.Meta.Positivity.PositivityExt in Mathlib.Tactic.Positivity.Core

@[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

noncomputable instance instMinReal : Min ℝ :=

unsafe def evalFloat (e : Expr) : MetaM Float := do
  evalExpr Float (mkConst ``Float) e

@[tactic convOpt]
partial def evalConvOpt : Tactic := fun stx => match stx with
  | `(tactic| conv_opt => $code) => (convertFullProb true code).toTactic
  
  | `(tactic| conv_opt =>) => do (convertFullProb false stx).toTactic
  | _ => throwUnsupportedSyntax

Lean.mkStrLit in Lean.Expr

HSMul in Init.Prelude

Sub.sub in Init.Prelude

abbrev VCondsIdxs := Array VCondIdx

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

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

Repr in Init.Data.Repr

invertibleMul in Mathlib.Algebra.Group.Invertible.Defs

abbrev CanonExpr := Expr

instance : Hashable Key := ⟨Key.hash⟩

IO.Process.Stdio in Init.System.IO

Lean.ReducibilityHints.regular in Lean.Declaration

Lean.Meta.mkFreshExprMVar in Lean.Meta.Basic

def Vec.soCone (t : m → ℝ) (X : Matrix m n ℝ) : Prop :=
  ∀ i, Real.soCone (t i) (X i)

Lean.Expr.lam in Lean.Expr

instance : ToMessageData RealToFloatData where
  toMessageData := fun d =>
    m!"real: {d.real}
    float: {d.float}"

Lean.Declaration.defnDecl in Lean.Declaration

MonadControlT in Init.Control.Basic

Lean.mkNode in Init.Prelude

LE in Init.Prelude

partial def getMatch (d : DiscrTree α) (e : Expr) : MetaM (Array α) := do
  Core.checkMaxHeartbeats "getMatch"
  let result := getStarResult d
  let (k, args) ← getMatchKeyArgs e (root := true)
  match k with
  | Key.star => return result
  | _        => getMatchRoot d k args result

let D := eqvExpr.domainLHS
    let R := eqvExpr.codomain
    let RPreorder := eqvExpr.codomainPreorder
    let fullProof ← mkAppOptM ``Minimization.Equivalence.rewrite_constraints
      #[D, R, RPreorder, lhsMinExpr.objFun, lhsMinExpr.constraints, newConstrs, iffProof]
    check fullProof
    let rhs := { lhsMinExpr with constraints := newConstrs }
    if !(← isDefEq eqvExpr.rhs rhs.toExpr) then
      throwError "`remove_constr` error: failed to unify RHS."

instance : Coe String Sexp where
  coe s := Sexp.fromString s

def fromArray (A : Array (Array Float)) : EncodedMatrix := Id.run <| do
  let mut em := empty
  for (i, ai) in A.data.enum do
    for (j, aij) in ai.data.enum do
      if i >= j && (aij > 0 || aij < 0) then
        em := em.addEntry (EncodedMatrixEntry.mk i j aij)
  return em

structure EncodedVectorEntry where
  i : Nat
  value : 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

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.")

def getAllOptimizationParams : MetaM (List Name) := do
  return (optimizationParamAttr.ext.getState (← getEnv)).toList

let atomData ← liftTermElabM <| canonAtomData atomData.curvature atomData
    let atomData ← addAtomDataDecls id.getId atomData

Task.Priority in Init.Core

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

noncomputable instance LDL.invertible_diag : Invertible (LDL.diag hA) :=

LDL.lower in Mathlib.Analysis.Matrix.LDL

def addExpConstraint (data : ProblemData) (a : Array Float) (b : Float) : ProblemData :=
  data.addScalarAffineConstraintOnlyVector a b ScalarConeType.Exp

Lean.PersistentEnvExtension in Lean.Environment

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}"

Module.End in Mathlib.Algebra.Module.LinearMap.End

def withCopyOfMonoXs {α} [Inhabited α] (xs : Array Expr) (argKinds : Array ArgKind)
    (f : Array Expr → Array Expr → Array ArgKind → TermElabM α) : TermElabM α := do
  
  let mut argDeclInfo : Array (Name × (Array Expr → TermElabM Expr)) := #[]
  let mut monoXs := #[]
  let mut monoArgKind := #[]
  for i in [:xs.size] do
    if argKinds[i]! != ArgKind.Constant ∧ argKinds[i]! != ArgKind.Neither then
      let ty := ← inferType xs[i]!
      let name := (← FVarId.getDecl xs[i]!.fvarId!).userName
      argDeclInfo := argDeclInfo.push (name, fun _ => pure ty)
      monoXs := monoXs.push xs[i]!
      monoArgKind := monoArgKind.push argKinds[i]!

private def constraints : Parsec (List Constraint) :=
  constraintsTitle   *>
  constraintsHeaders *>
  Array.data <$> many constraint

def cleanUpCompBuilder : EquivalenceBuilder Unit := fun eqvExpr g => g.withContext do
  let lhsMinExpr ← eqvExpr.toMinimizationExprLHS
  let newObjFun ← cleanUpCompAux lhsMinExpr.objFun "objFun"
  let newConstraints ← cleanUpCompAux lhsMinExpr.constraints "constr"
  let rhsMinExpr := { lhsMinExpr with objFun := newObjFun, constraints := newConstraints }
  let newEqvExpr := { eqvExpr with lhs := lhsMinExpr.toExpr, rhs := rhsMinExpr.toExpr }
  if (← isDefEq (mkMVar g) newEqvExpr.toExpr) then
    throwError "`clean_up_comp` error: Failed to unify the goal."
  let simpComp ← ({} : SimpTheorems).addDeclToUnfold ``Function.comp
  let simpContext := { config := {}, simpTheorems := #[simpComp] }
  if let (some newGoal, _) ← simpTarget g simpContext then
    if let _ :: _ ← evalTacticAt (← `(tactic| equivalence_rfl)) newGoal then
      throwError "`clean_up_comp` error: Failed to close the goal."

abbrev AtomDataTrees := GraphAtomDataTree × ArgumentsTree × CurvatureTree × BCondsTree

Lean.mkArrow in Lean.CoreM

Float.neg in Init.Data.Float

@[command_elab «reduction»]
def evalReduction : 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 false
  | _ => throwUnsupportedSyntax

def replaceProjections (e : Expr) (p : FVarId) (rs : Array Expr) : MetaM Expr := do
  let pre (e : Expr) : MetaM TransformStep := do
    match ← decomposeProj e p rs.data with
    | some r => return TransformStep.done r
    | none => return TransformStep.continue
  transform e (pre := pre)
where
  decomposeProj (e : Expr) (p : FVarId) (rs : List Expr) (first : Option Bool := none) :
      MetaM (Option Expr) := do
    
    
    
    
    match first, e, rs with
    | _, .fvar fVarId, [r] =>
        if fVarId == p then return r else return none
    | some true, .fvar fVarId, r :: _ :: _ =>
        if fVarId == p then return r else return none
    | none, .app (.app (.app (.const ``Prod.fst _) _) _) e, r :: rs => do
        decomposeProj e p (r :: rs) (first := true)
    | _, .app (.app (.app (.const ``Prod.snd _) _) _) e, _ :: rs => do
        decomposeProj e p rs (first := first == some true)
    | _, _, [] => return none
    | _, _, _ :: _ => return none

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

Mathlib.Meta.NormNum.deriveSimp in Mathlib.Tactic.NormNum.Core

def const (n : ℕ) (k : α) : Fin n → α  :=
  fun _ => k

def mkVCondVars (originalConstrFVars : Array FVarId) (vcondIdx : PreVCondsTree) :
    Tree (Array Expr) Unit :=
  vcondIdx.map (fun iores => iores.map fun iore =>
    match iore with
    | Sum.inl i => mkFVar originalConstrFVars[i]!
    | Sum.inr e => e) id

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

Lean.annotation? in Lean.Expr

structure ConeProduct where
  n : Nat
  k : Nat
  cones : List Cone

def constraint : Parser :=
  leading_parser (ppLine >> checkColGe >> ppGroup (Term.binderIdent >> " : " >> termParser))

def exp : m → ℝ := fun i => Real.exp (x i)

@[equiv]
def rewrite_constraint_1_last (hrw : ∀ x, c1 x ↔ c1' x) : ⟨f, [[c1]]⟩ ≡ ⟨f, [[c1']]⟩ :=
  equivalence_of_rw_constr hrw

def w := p₃.solution.2.1

inductive EggRewriteDirection where
  | Forward
  | Backward
deriving Inhabited, DecidableEq

modify fun s => { s with syntheticMVars := {} }

structure DiscrTree (α : Type) where
  root : PersistentHashMap Key (Trie α) := {}

def getRealToFloatDiscrTree : MetaM (DiscrTree RealToFloatData) := do
  return realToFloatExtension.getState (← getEnv)

Float.sqrt in Init.Data.Float

instance : Coe (List Sexp) Sexp where
  coe := Sexp.fromList

return constrTags

x
</all_available_defs>

<all_available_lemmas>
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

lemma div_le_iff (hb : StrongLT 0 b) : a / b ≤ c ↔ a ≤ c * b

lemma sum_exp_pos {n} (hn : 0 < n) (x : Fin n → ℝ) :
    0 < Vec.sum (Vec.exp x)

theorem vecCons_zero_zero {n} [Zero α] : vecCons (0 : α) (0 : Fin n → α) = 0

lemma PosDef.nonsingular_inv [DecidableEq n] {M : Matrix n n 𝕜} (hM : M.PosDef) : M⁻¹.PosDef

lemma conjTranspose_eq_transpose {m n : Type _} {A : Matrix m n ℝ} : Aᴴ = Aᵀ

lemma Real.log_nonneg_of_ge_one {x : ℝ} : 0 ≤ x - 1 → 0 ≤ log x

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

lemma upperTriangular.toUpperTri_eq {A : Matrix n n ℝ}
    (hA : upperTriangular A) : A.toUpperTri = A

@[simp]
lemma PosSemidef.sqrt_mul_sqrt {A : Matrix n n ℝ} (hA : A.PosSemidef) :
    hA.1.sqrt * hA.1.sqrt = A

theorem spectral_theorem'' :
    hA.eigenvectorMatrix * diagonal (RCLike.ofReal ∘ hA.eigenvalues) * hA.eigenvectorMatrixᴴ =
    A

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

lemma one_div_eq_pow_neg_one {a : ℝ} (ha : 0 < a) : 1 / a = a ^ (-1 : ℝ)

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

lemma det_add_det_le_det_add [Nonempty n] (A B : Matrix n n ℝ) (hA : A.PosSemidef)
    (hB : B.PosSemidef) : A.det + B.det ≤ (A + B).det

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)

neg_nonneg_of_nonpos in Mathlib.Algebra.Order.Group.Defs

lemma IsHermitian.fromBlocks₂₂ [Fintype n] [DecidableEq n] (A : Matrix m m 𝕜) (B : Matrix m n 𝕜)
    {D : Matrix n n 𝕜} (hD : D.IsHermitian) :
    (Matrix.fromBlocks A B Bᴴ D).IsHermitian ↔ (A - B * D⁻¹ * Bᴴ).IsHermitian

lemma eigenvectorMatrix_inv_mul : hA.eigenvectorMatrixInv * hA.eigenvectorMatrix = 1

lemma soCone_add_sub_two_mul_of_nonneg {x y : ℝ} (z : ℝ)
    (hx : 0 ≤ x) (hy : 0 ≤ y) : soCone (x + y) ![x - y, 2 * z] ↔ z ^ (2 : ℝ) ≤ x * y

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

lemma IsHermitian.fromBlocks₁₁ [Fintype m] [DecidableEq m] {A : Matrix m m 𝕜} (B : Matrix m n 𝕜)
    (D : Matrix n n 𝕜) (hA : A.IsHermitian) :
    (Matrix.fromBlocks A B Bᴴ D).IsHermitian ↔ (D - Bᴴ * A⁻¹ * B).IsHermitian

lemma PosDef_diagonal [DecidableEq n] {f : n → ℝ} (hf : ∀ i, 0 < f i) : (diagonal f).PosDef
</all_available_lemmas>

<local_ctx>
import Mathlib.LinearAlgebra.Matrix.PosDef

import Mathlib.Algebra.Star.Pi

namespace Matrix

variable {m n : Type _} [Fintype m] [Fintype n]

variable {𝕜 : Type _}

variable [NormedField 𝕜] [PartialOrder 𝕜] [StarRing 𝕜] [StarOrderedRing 𝕜]

variable [RCLike 𝕜]

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)
</local_ctx>

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

