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>
StrongLT in Mathlib.Order.Basic

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

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

Array.range in Init.Data.Array.Basic

Task.Priority.dedicated in Init.Core

Matrix.toBlock in Mathlib.Data.Matrix.Block

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

abbrev Solution := Array NewVarAssignment

Float.log in Init.Data.Float

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

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

equivalence* eqv₃/q₃ : p₃ 100 10 0.5 2 0.5 2 :=

Lean.mkApp3 in Lean.Expr

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

Lean.logInfo in Lean.Log

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

Real.instInv in Mathlib.Data.Real.Basic

def addPSDVariable (p : Problem) (d : Nat) : Problem :=
  { p with PSDVariables := p.PSDVariables.addDimension d }

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

structure EncodedMatrixList where
  n : Nat
  values : List EncodedMatrixListEntry

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

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

Lean.Expr.proj in Lean.Expr

liftTermElabM do
      trace[CvxLean.debug] "Addding atom {atomData}"
      addAtom <| AtomData.graph atomData
  | _ => throwUnsupportedSyntax

Real.instNNRatCast in Mathlib.Data.Real.Basic

Fintype.card in Mathlib.Data.Fintype.Card

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

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

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

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

Lean.Level in Lean.Level

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

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

Float.mul in Init.Data.Float

RCLike.ofReal in Mathlib.Analysis.RCLike.Basic

List.replicate in Init.Data.List.Basic

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

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

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

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

LinearOrder in Mathlib.Order.Defs.LinearOrder

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

def makeConstrForward (oldDomain : Expr) (xs : Array Expr) (originalConstrVars : Array LocalDecl)
    (oldProblem : Expr) (constraints : Array Expr) (isVCond : Array Bool)
    (constraintsEq : Array Expr) (feasibility : OC FeasibilityProofsTree) : MetaM Expr := do
  
  withLocalDeclD `p oldDomain fun p => do
    let prs := (← Meta.mkProjections oldDomain p).map (·.2.2)

instance : ToString MatrixAffine where
  toString sa := s!"MatrixAffine [{sa.n}, {sa.H}, {sa.D}]"

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

inductive EggTreeOpArgTag
  | arg
  | val (s : String)

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

Lean.TransformStep in Lean.Meta.Transform

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

abbrev NewConstrVarsTree := Tree (Array LocalDecl) Unit

def RuleToTacticExt : Type :=
  SimplePersistentEnvExtension RuleToTacticExtEntry RuleToTacticExtState
deriving Inhabited

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

Option.map in Init.Prelude

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

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

liftExcept in Init.Control.Except

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

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

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

@[rel]
def refl : p ≽' p :=
  { phi := id,
    phi_feasibility := fun _ h => h,
    phi_optimality := fun _ _ => le_refl _ }

SetLike in Mathlib.Data.SetLike.Basic

instHMul in Init.Prelude

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

def exp {m} (x : m → Float) : m → Float :=
  fun i => Float.exp (x i)

@[tactic changeOfVariables]
def evalChangeOfVariables : Tactic := fun stx => match stx with
  | `(tactic| change_of_variables ($newVarStx) ($varToChangeStx ↦ $changeStx)) => do
      (changeOfVariablesBuilder newVarStx varToChangeStx changeStx).toTactic
      evalTactic <| ← `(tactic| conv_opt => norm_num1)
      saveTacticInfoForToken stx
  | _ => throwUnsupportedSyntax

inductive SexpTok
  | sexp : Sexp →  SexpTok
  | opening : String.Pos → SexpTok
  deriving BEq, Inhabited, Repr

IO.getEnv in Init.System.IO

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

Real.instSub in Mathlib.Data.Real.Basic

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

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

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

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

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

@[tactic renameVars]
partial def evalRenameVars : Tactic := fun stx => match stx with
| `(tactic| rename_vars [$ids,*]) => do
    let names := (ids.elemsAndSeps.map Syntax.getId).filter (· != Lean.Name.anonymous)
    (renameVarsBuilder names).toTactic
    saveTacticInfoForToken stx
| _ => throwUnsupportedSyntax

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

Lean.PrettyPrinter.Delaborator.Delab in Lean.PrettyPrinter.Delaborator.Basic

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

IO.FS.withFile in Init.System.IO

BaseIO.toIO in Init.System.IO

guard in Init.Control.Basic

def addMatrixValuedAffineConstraint (p : Problem) (d : Nat) (Hk : EncodedMatrixList)
    (Dk : EncodedMatrix)  : Problem :=
  Id.run <| do
    let k := p.PSDConstraints.n
    let mut newP := p
    newP := newP.addPSDConstraint d
    newP := newP.addPSDConstraintsScalarVariablesCoord k Hk
    newP := newP.addPSDConstraintsShiftCoord k Dk
    newP

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

Lean.Elab.Term.commitIfNoErrors? in Lean.Elab.Term.TermElabM

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

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

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

@[command_elab registerRuleToTactic] def elabRuleToTactic : CommandElab
| `(register_rule_to_tactic $rwName; $rwTarget => $rwGoal := $tac;) => do
    let rwNameStr := rwName.getString
    
    let _rwTargetStr := rwTarget.getString
    let _rwGoalStr := rwGoal.getString
    liftTermElabM <| addRuleToTacticEntry rwNameStr tac false
| _ => throwUnsupportedSyntax

def isRelativelyConstant (e : Expr) (vars : Array FVarId) : Bool := Id.run do
  let fvarSet := (Lean.collectFVars {} e).fvarSet
  for v in vars do
    if fvarSet.contains v then return false
  return true

Repr in Init.Data.Repr

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

Lean.FVarId.getDecl in Lean.Meta.Basic

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

abbrev AtomDataTrees := GraphAtomDataTree × ArgumentsTree × CurvatureTree × BCondsTree

Lean.ReducibilityHints in Lean.Declaration

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

invertibleOfLeftInverse in Mathlib.Algebra.Group.Invertible.Defs

Eq in Init.Prelude

def ofEggOCTree (ocTree : EggOCTree) : EggTree :=
  let objFun := ocTree.objFun.2
  let constrs := ocTree.constrs.map
    fun (h, c) => Tree.node "constr" #[Tree.leaf h, c]
  let objFunNode := Tree.node "objFun" #[objFun]
  let constrNode := Tree.node "constrs" constrs
  Tree.node "prob" #[objFunNode, constrNode]

Lean.Expr.isConstOf in Lean.Expr

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

instHDiv in Init.Prelude

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

Function.LeftInverse in Init.Data.Function

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]

BaseIO in Init.System.IO

Decidable in Init.Prelude

structure EncodedMatrixListEntry where
  i : Nat
  j : Nat
  k : Nat
  value : Float

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

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

LinearMap in Mathlib.Algebra.Module.LinearMap.Defs

Sum.inr in Init.Core

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

Nat in Init.Prelude

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

List in Init.Prelude

Lean.instantiateMVarDeclMVars in Lean.MetavarContext

Lean.Syntax.atom in Init.Prelude

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

def makeBackwardMap (xs : Array Expr) (mkDomainFunc : Expr → MetaM Expr) : MetaM Expr := do
  let backwardBody ← foldProdMk xs
  let backwardMap ← mkDomainFunc backwardBody
  trace[CvxLean.debug] "Backward map: {backwardMap}."
  check backwardMap
  trace[CvxLean.debug] "Backward map checked."

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

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

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

def toBwd (R : p ≼ q) : Solution q → Solution p :=
  fun sol =>
    { point := R.psi sol.point,
      isOptimal := R.psi_optimality sol.point sol.isOptimal }

Lake.logInfo in Lake.Util.Log

Finsupp in Mathlib.Data.Finsupp.Defs

Lean.Meta.MetaM in Lean.Meta.Basic

def h := p₃.solution.1

Preorder in Mathlib.Order.Defs.PartialOrder

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

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

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

let (objFunForward, constrForward) ←
      withExistingLocalDecls pat.originalConstrVars.toList do
        let objFunForward ← makeObjFunForward D originalVars pat.originalConstrVars ogProblemExpr
          (pat.constraints.toArray.map Prod.snd) pat.solEqAtom.objFun.val
        let constrForward ← makeConstrForward D originalVars pat.originalConstrVars ogProblemExpr
          (pat.constraints.toArray.map Prod.snd) pat.isVCond (pat.solEqAtom.constrs.map Tree.val)
          pat.feasibility
        return (objFunForward, constrForward)

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

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

Matrix.trace in Mathlib.LinearAlgebra.Matrix.Trace

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

HSMul in Init.Prelude

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

def SexpM.pop: SexpM SexpTok := do
  let state ← get
  match state.stack with
  | [] => panic! "empty stack"
  | x :: xs =>
      set { state with stack := xs }
      return x

let objFunForward := objFunForward.replaceFVars
        ((originalConstrVars).map (mkFVar ·.fvarId)) hProj
      let objFunForward ← mkLambdaFVars #[h] objFunForward

Float.pow in Init.Data.Float

MonadWithReaderOf in Init.Prelude

Lean.Meta.withLetDecl in Lean.Meta.Basic

def SexpM.advance: SexpM Unit := do
  modify (fun state => { state with it := state.it.next })

IO.rand in Init.Data.Random

abbrev VCondsIdxs := Array VCondIdx

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

structure Relaxation where
  phi : D → E
  phi_feasibility : ∀ x, p.feasible x → q.feasible (phi x)
  phi_optimality : ∀ x, p.feasible x → q.objFun (phi x) ≤ p.objFun x

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 covarianceMatrix {N n : ℕ} (y : Fin N → Fin n → ℝ) : Matrix (Fin n) (Fin n) ℝ :=
  fun i j : Fin n => (∑ k : Fin N, y k i * y k j) / N

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

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

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

Lean.Meta.ParamInfo in Lean.Meta.Basic

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)

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

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

Sum.inl in Init.Core

partial def fold [Inhabited γ] (init : γ) (f : γ → α → γ) : Tree α β → γ
  | node val children => Id.run do
      let mut res := init
      for child in children do
        res ← fold res f child
      res := f res val
      return res
  | leaf _ => init

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

let lhsMinExpr ← eqvExpr.toMinimizationExprLHS
    let vars ← decomposeDomain (← instantiateMVars lhsMinExpr.domain)

def addRotatedSOConstraint (data : ProblemData) (a : Array Float) (b : Float) : ProblemData :=
  data.addScalarAffineConstraintOnlyVector a b ScalarConeType.QR

abbrev BCondsTree := Tree BConds BConds

Lean.Core.betaReduce in Lean.Meta.Transform

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

def addScalarConstraintsPSDVariablesCoord (p : Problem) (i : Nat) (eml : EncodedMatrixList) :
    Problem :=
  let emll := EncodedMatrixListList.fromIndexAndEncodedMatrixList i eml
  { p with scalarConstraintsPSDVariablesCoord :=
      p.scalarConstraintsPSDVariablesCoord.stack emll }

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)

let vcondElim := atom.vcondElim
      let vcondElim := vcondElim.map (mkAppN · (childCanonExpr.map Tree.val))
      let vcondElim := vcondElim.map (mkAppN · (newVars.map (mkFVar ·.fvarId)))
      let vcondElim := vcondElim.map (mkAppN · (newConstrVars.map (mkFVar ·.fvarId)))
      let vcondElim := vcondElim.map (mkAppN · monoArgs)
      let vcondElim := vcondElim.map (mkAppN · (childOptimalityFiltered.map (·.val.1)))

Matrix.BlockTriangular in Mathlib.LinearAlgebra.Matrix.Block

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

String.join in Init.Data.String.Defs

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

def mkAndProj (e : Expr) (i : Nat) (total : Nat) : MetaM Expr := do
  match total, i with
    | 1, 0 => return e
    | 0, _ => throwError "total too small"
    | _, 0 => return ← mkAppM ``And.left #[e]
    | total + 1, i + 1 => mkAndProj (← mkAppM ``And.right #[e]) i total

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

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

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

Lean.Expr.fvar in Lean.Expr

def mkArray (ty : Expr) (as : Array Expr) : MetaM Expr :=
  mkArrayAux ty as.data.reverse

let proof ← elabTerm stx (some transfTy)

instance {a : ℝ} : ChangeOfVariables (fun x : ℝ => a * x) :=
  { inv := fun x => (1 / a) * x
    condition := fun _ => a ≠ 0
    property := fun _ h => by admit /- proof elided -/

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

Lean.mkApp6 in Lean.Expr

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

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

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

def SexpM.pushTok (tok: SexpTok): SexpM Unit := do
  modify (fun state => { state with stack := tok :: state.stack })

LDL.lower in Mathlib.Analysis.Matrix.LDL

def findRegisteredAtoms (e : Expr) : MetaM (Array (Arguments × GraphAtomData)) := do
  let discrTree ← getAtomDiscrTree
  let atoms ← discrTree.getMatch (← zetaReduce (← e.removeMData))
  trace[Meta.debug] "discrTree {atoms.size} {e}"
  let mut goodAtoms := #[]
  for atom in atoms do
    let (mvars, _, pattern) ← lambdaMetaTelescope atom.expr
    if ← isDefEq pattern e then
      let args ← mvars.mapM instantiateMVars
      goodAtoms := goodAtoms.push (args, atom.graph!)
    else
      trace[CvxLean.debug]
        "Pattern did not match. (Pattern {toString pattern}; Expression {toString e})"
  
  goodAtoms := goodAtoms.insertionSort (fun a b => (a.2.expr.size - b.2.expr.size != 0))
  return goodAtoms

Lean.mkApp in Lean.Expr

def showVars (goal : MVarId) (p : FVarId) : MetaM MVarId := do
  
  let (revertedVars, goal) ← MVarId.withContext goal do
    let pDecl ← FVarId.getDecl p
    let fVarIds := (← getLCtx).decls.toArray.filterMap id
      |>.filter (fun decl => decl.index > pDecl.index)
      |>.map LocalDecl.fvarId
    let (_, goal) ← MVarId.revert goal fVarIds
    return (fVarIds, goal)
  
  let goal ← MVarId.withContext goal do
    let pDecl ← FVarId.getDecl p
    let domain ← instantiateMVars pDecl.type
    return ← withDomainLocalDecls domain (mkFVar p) fun xs _ => do
      let target ← instantiateMVars (← MVarId.getDecl goal).type
      let newTarget ← Meta.replaceProjections target p xs
      let mVar ← mkFreshExprMVar newTarget MetavarKind.syntheticOpaque
      MVarId.assign goal (← mkLetFVars xs mVar)
      return mVar.mvarId!
  
  let (_, goal) ← MVarId.introNP goal revertedVars.size
  return goal

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

let currNamespace ← getCurrNamespace
      let probId := currNamespace ++ probIdStx.getId
      let relId := currNamespace ++ relIdStx.getId

Lean.Meta.inferType in Lean.Meta.Basic

Matrix.diagonal in Mathlib.Data.Matrix.Diagonal

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

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

proofs in SciLean.Lean.Meta.LiftLets

def ScalarAffineSections : Type := Array Nat

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

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

Min in Init.Prelude

@[delab app]
partial def delabMinimization : Delab := do
  
  match ← getExpr with
  | .app (.app (.app (.app (.const `Minimization.mk _) domain) _codomain) _objFun) constraints =>
      let idents ← withType <| withNaryArg 0 do
        let tys ← delabDomain
        let tys ← tys.mapM fun (name, stx) => do `(Parser.minimizationVar| ($(mkIdent name) : $stx))
        return tys.toArray
      let (objFun, isMax) ← withNaryArg 2 do withDomainBinding domain do
        match ← getExpr with
        | .app (.app (.app (.const ``maximizeNeg _) _) _) e =>
            withExpr e do
              return (← delab, true)
        | _ =>
            return (← delab, false)
      let noConstrs ← withLambdaBody constraints fun _ constrsBody => do
        isDefEq constrsBody (mkConst ``True)
      let constraints := ← withNaryArg 3 do
        let cs ← withDomainBinding domain delabConstraints
        return mkNode ``Parser.constraints #[mkNullNode <| cs.toArray.map (·.raw)]
      if noConstrs then
        if isMax then
          `(optimization $idents* maximize $objFun)
        else
          `(optimization $idents*  minimize $objFun)
      else
        if isMax then
          `(optimization $idents* maximize $objFun subject to $constraints)
        else
          `(optimization $idents* minimize $objFun subject to $constraints)
  | _ => Alternative.failure

EStateM in Init.Prelude

def Sexp.toList? : Sexp → Option (List Sexp)
  | .atom _  => none
  | .list xs => some xs

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

Matrix.toSquareBlockProp in Mathlib.Data.Matrix.Block

def makeForwardMap (oldDomain : Expr) (xs : Array Expr) (forwardImagesNewVars : Array Expr) :
    MetaM Expr := do
  withLocalDeclD `p oldDomain fun p => do
    let prs := (← Meta.mkProjections oldDomain p).map (·.2.2)
    let forwardBody := xs ++ forwardImagesNewVars
    let forwardMap ← mkLambdaFVars #[p] <| (← foldProdMk forwardBody).replaceFVars xs prs.toArray
    trace[CvxLean.debug] "Forward map: {forwardMap}."
    check forwardMap
    trace[CvxLean.debug] "Forward map checked."

structure Problem where
  version : Nat
  objSense : ObjSense
  scalarVariables : ConeProduct
  PSDVariables : DimensionList
  scalarConstraints : ConeProduct
  PSDConstraints : DimensionList
  objectivePSDVariablesCoord : EncodedMatrixList
  objectiveScalarVariablesCoord : EncodedVector
  objectiveShiftCoord : EncodedValue
  scalarConstraintsPSDVariablesCoord : EncodedMatrixListList
  scalarConstraintsScalarVariablesCoord : EncodedMatrix
  scalarConstraintsShiftCoord : EncodedVector
  PSDConstraintsScalarVariablesCoord : EncodedMatrixListList
  PSDConstraintsShiftCoord : EncodedMatrixList

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

Lean.Meta.withLocalDeclD in Lean.Meta.Basic

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

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

Lean.Elab.Command.liftTermElabM in Lean.Elab.Command

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

add in test.generate_revDeriv

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

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

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

structure EncodedVector where
  n : Nat
  values : List EncodedVectorEntry

Real.sqrt in Mathlib.Data.Real.Sqrt

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

withLocalDeclsD argDeclInfo fun ys => do
    f monoXs ys monoArgKind

abs in Mathlib.Algebra.Order.Group.Unbundled.Abs

Submodule in Mathlib.Algebra.Module.Submodule.Defs

let constrBackward ← makeConstrBackward pat.vcondElimMap E canonProblemExpr originalVars
            newVars (pat.optimality.constrs.map (·.val)) canonConstrs pat.newConstrs
            pat.newConstrVarsArray

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

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 : ChangeOfVariables sqrt :=
  { inv := (fun x => x ^ 2)
    condition := fun x => 0 ≤ x
    property := fun _ hx => sqrt_sq hx }

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

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

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

Lean.mkAtom in Init.Prelude

let (_, mvarId) ← mvarId.assertHypotheses hyps

Inv in Init.Prelude

if let _ :: _ ← evalTacticAt (← `(tactic| equivalence_rfl)) g then
      throwRenameConstrsError "failed to close the goal."

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

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

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

noncomputable def huber (x : Real) :=
  if abs x ≤ 1 then x ^ 2 else 2 * abs x - 1

Lean.trace in Lean.Util.Trace

Lean.mkAppN in Lean.Expr

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

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]

def fromGoal (goal : MVarId) : MetaM RelaxationExpr := do
  let goalType ← whnf (← MVarId.getDecl goal).type
  fromExpr goalType

Lean.mkIdent in Init.Meta.Defs

abbrev VCondElimMap := Std.HashMap Nat Expr

instance : Hashable Key := ⟨Key.hash⟩

let mkDomain := fun e =>
        withLocalDeclD `p E fun p => do
          let prs := (← Meta.mkProjections E p).map (·.2.2)
          let e := Expr.replaceFVars e (originalVars ++ newVars) prs.toArray
          mkLambdaFVars #[p] e

abbrev CanonExpr := 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

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

Ring in Mathlib.Algebra.Ring.Defs

Lean.mkConst in Lean.Expr

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

partial def adjustOps (t : EggTree) : MetaM EggTree := do
  match t with
  | Tree.node op children =>
      if let some (newOp, argTags) := opMap.find? op then
        let mut children ← children.mapM adjustOps
        let argsGiven := children.size
        let mut newChildren := #[]
        let mut arityError := false
        for argTag in argTags do
          match argTag with
          | .arg =>
              if children.size > 0 then
                newChildren := newChildren.push children[0]!
                children := children.drop 1
              else
                arityError := true
                break
          | .val s =>
              newChildren := newChildren.push (Tree.leaf s)
        arityError := arityError || children.size > 0
        if arityError then
          throwError s!"The op {op} was passed {argsGiven} arguments."
        else
        return Tree.node newOp newChildren
      else
        throwError s!"The atom {op} is not supported by the `pre_dcp` tactic."
  | Tree.leaf "unknown" => throwError "Unknown atom."
  | l => return l

def mkAtomTree (objCurv : Curvature) (originalVarsDecls extraDecls : Array LocalDecl) (oc : OC Expr)
    (extraVars : Array FVarId := #[]) :
    MetaM (
      OC Bool × OC (Array MessageData) ×
      OC GraphAtomDataTree × OC ArgumentsTree × OC CurvatureTree × OC BCondsTree) := do
  withExistingLocalDecls originalVarsDecls.toList do
    withExistingLocalDecls extraDecls.toList do
      let xs := originalVarsDecls.map fun decl => mkFVar decl.fvarId
      
      let atomsAndArgs ← OC.map2M (fun e c => findAtoms e (xs.map (·.fvarId!) ++ extraVars) c) oc
        ⟨objCurv, oc.constrs.map (fun _ => Curvature.ConvexSet)⟩
      let failedAtom : OC Bool := atomsAndArgs.map (·.fst)
      let failedAtomMsgs : OC (Array MessageData) := atomsAndArgs.map (·.snd.fst)
      if failedAtom.objFun then
        throwDCPError
          "failed to make atom tree for the objective function ({failedAtomMsgs.objFun})."

def elabVars (idents : Array (TSyntax `CvxLean.Parser.minimizationVar)) :
    TermElabM (Array (Lean.Name × Expr)) := do
  let idents ← idents.concatMapM decomposeBracketedBinder
  let idents ← idents.mapM fun (id, ty) => do
    match id with
      | Syntax.ident _ _ val _ => return (val, ← Term.elabTerm ty none)
      | _ => throwParserError "expected identifier got {id}."
  return idents

Lean.Syntax 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

PiLp in Mathlib.Analysis.Normed.Lp.PiLp

def mkFeasibilityOC (originalVarsDecls : Array LocalDecl) (atoms : OC GraphAtomDataTree)
    (canonWithSolution : OC CanonExprsWithSolutionTree) (bconds : OC BCondsTree)
    (vcondVars : OC VCondsTree) (originalConstrVars : Array LocalDecl)
    (solEqAtom : OC SolEqAtomProofsTree) : MetaM (OC FeasibilityProofsTree) :=
  withExistingLocalDecls originalVarsDecls.toList do
    withExistingLocalDecls originalConstrVars.toList do
      let feasibility ← OC.map5M mkFeasibility atoms canonWithSolution bconds vcondVars solEqAtom
      trace[CvxLean.debug] "`feasibility`: {feasibility}."
      return feasibility

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

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

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

gNext.setTag Name.anonymous
  setGoals [gNext]

Lean.Meta.mkFreshTypeMVar in Lean.Meta.Basic

RCLike in Mathlib.Analysis.RCLike.Basic

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

Or in Init.Prelude

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

inferInstanceAs in Init.Prelude

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

return res

return stdout
</all_available_defs>

<all_available_lemmas>
lemma upperTriangular_toUpperTri {m : Type _} [LinearOrder m]
    (A : Matrix m m ℝ) : A.toUpperTri.upperTriangular

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 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 one_add_prod_le_prod_one_add {n : Type _} [Fintype n] [Nonempty n]
    (f : n → ℝ) (hf : ∀ i, 0 ≤ f i) : 1 + (∏ i, f i) ≤ ∏ i, (1 + f i)

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 repr_gramSchmidt_diagonal {i : ι} (b : Basis ι 𝕜 E) :
    b.repr (gramSchmidt 𝕜 b i) i = 1

lemma IsHermitian.has_eigenvector_one_add {A : Matrix n n ℝ} (hA : A.IsHermitian) (i : n) :
    Module.End.HasEigenvector
      (1 + Matrix.toLin' A) (1 + (hA.eigenvalues i)) ((hA.eigenvectorBasis) i)

lemma pow_two_le_pow_two {x y : ℝ} (hx : 0 ≤ x) (hy : 0 ≤ y) :
    x ^ (2 : ℝ) ≤ y ^ (2 : ℝ) ↔ x ≤ y

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 toSquareBlock_inv_mul_toSquareBlock_eq_one [LinearOrder α]
    [Invertible M] (hM : BlockTriangular M b) (k : α) :
    M⁻¹.toSquareBlock b k * M.toSquareBlock b k = 1

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

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

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

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 det_add_det_le_det_add' [Nonempty n] (A B : Matrix n n ℝ) (hA : A.PosDef)
    (hB : B.PosSemidef) : A.det + B.det ≤ (A + B).det

lemma Real.exp_sub_one_pos_of_pos {x : ℝ} : 0 < x → 0 < Real.exp x - 1

@[simp]
lemma inv_lower_eq_lowerInv : (lower hS)⁻¹ = lowerInv hS

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 BlockTriangular_blockDiagonal [DecidableEq α] (d : α → Matrix m m R) :
    BlockTriangular (blockDiagonal d) Prod.snd

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

lemma IsHermitian.nonsingular_inv [DecidableEq n] {M : Matrix n n 𝕜} (hM : M.IsHermitian)
    (hMdet : IsUnit M.det) : M⁻¹.IsHermitian

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

lemma PosSemidef.PosSemidef_sqrt {A : Matrix n n ℝ} (hA : A.PosSemidef) :
    hA.1.sqrt.PosSemidef

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

lemma schur_complement_eq₂₂ [Fintype m] [Fintype n] [DecidableEq n] (A : Matrix m m 𝕜)
    (B : Matrix m n 𝕜) {D : Matrix n n 𝕜} (x : m → 𝕜) (y : n → 𝕜) [Invertible D]
    (hD : D.IsHermitian) :
    vecMul (star (x ⊕ᵥ y)) (fromBlocks A B Bᴴ D) ⬝ᵥ (x ⊕ᵥ y) =
      vecMul (star ((D⁻¹ * Bᴴ).mulVec x + y)) D ⬝ᵥ ((D⁻¹ * Bᴴ).mulVec x + y) +
        vecMul (star x) (A - B * D⁻¹ * Bᴴ) ⬝ᵥ x

lemma induces_original_problem_optimality (Rx : p ≽' q) (phi_inv : E → D)
    (phi_left_inv : Function.LeftInverse Rx.phi phi_inv)
    (h_objFun : ∀ x, p.feasible x → p.objFun x = q.objFun (Rx.phi x)) {y : E}
    (h_opt_y : q.optimal y) (h_feas_y : p.feasible (phi_inv y)) : p.optimal (phi_inv y)

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

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

<local_ctx>
import Mathlib.Analysis.NormedSpace.PiLp

import Mathlib.Analysis.InnerProductSpace.PiL2

import CvxLean.Lib.Math.Data.Real

import CvxLean.Lib.Math.Data.Fin

namespace Vec

variable {m : Type u} {n : Type v} [Fintype m] [Fintype n] {α : Type w}

section AddCommMonoid

variable [AddCommMonoid α] {m : Nat} {n : Nat} (x : Fin m → α) (y : Fin n → α)

open BigOperators

open FinsetInterval

end AddCommMonoid

noncomputable section Real

open Real BigOperators

variable (x y : m → ℝ)

end Real

section RealLemmas

variable {a b c : m → ℝ}
</local_ctx>

<target_theorem>
lemma le_div_iff (hc : StrongLT 0 c) : a ≤ b / c ↔ a * c ≤ b :=
</target_theorem>

