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

abbrev BCondsTree := Tree BConds BConds

Lean.FVarId in Lean.Expr

Lean.Expr.mdata in Lean.Expr

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

Nat.succ in Init.Prelude

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

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

Lean.DefinitionSafety.safe in Lean.Declaration

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

def mkFinIdxExpr (i : Nat) (n : Nat) : MetaM Expr := do
  return mkApp2 (mkConst ``Fin.ofNat) (mkNatLit n.pred) (mkNatLit i)

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

let atomData := {
        id := id.getId
        curvature := curv
        expr := expr
        argKinds := argKinds
        bconds := #[]
        vconds := vconds
        impVars := impVars
        impObjFun := impObj
        impConstrs := impConstrs.map (·.snd)
        solution := sols
        solEqAtom := solEqAtom
        feasibility := feas
        optimality := opt
        vcondElim := vcondElim
      }
      return atomData

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

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

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

Lean.Syntax.getId in Init.Prelude

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

Real.instAddGroup in Mathlib.Data.Real.Basic

Option.map in Init.Prelude

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

def EggOCTree := OC (String × EggTree)

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

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

def mkFloat (n : Nat) : Expr :=
  mkApp3 (mkConst ``OfNat.ofNat [levelZero])
    (mkConst ``Float) (mkNatLit n) (mkApp (mkConst ``instOfNatFloat) (mkNatLit n))

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

Lean.Expr.mvar in Lean.Expr

Matrix.det in Mathlib.LinearAlgebra.Matrix.Determinant.Basic

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

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

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

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

let objectiveData ← withLambdaBody minExpr.objFun fun p objFun => do
    let objFun ← realToFloat objFun
    return ← determineScalarCoeffsAux objFun p floatDomain

Nat in Init.Prelude

Real.instMul 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

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

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

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

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

Matrix.mulVec in Mathlib.Data.Matrix.Mul

Lean.ReducibilityHints in Lean.Declaration

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

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

Nat.add in Init.Prelude

@[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 atomData ← addAtomDataDecls id.getId atomData

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

Alternative in Init.Control.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]!

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

withLocalDeclsD argDeclInfo fun ys => do
    f monoXs ys monoArgKind

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

instHPow in Init.Prelude

EuclideanSpace.single in Mathlib.Analysis.InnerProductSpace.PiL2

Lean.Literal.natVal in Lean.Expr

inductive EggRewriteDirection where
  | Forward
  | Backward
deriving Inhabited, DecidableEq

Lean.MessageData.nil in Lean.Message

Unit in Init.Prelude

Lean.Json.getObj? in Lean.Data.Json.Basic

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)

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

RCLike.ofReal in Mathlib.Analysis.RCLike.Basic

abbrev SexpM := EStateM SexpError SexpState

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

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]

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

Array.append in Init.Data.Array.Basic

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

def toUpperTri {m α : Type _} [LinearOrder m] [Zero α] (A : Matrix m m α) :
    Matrix m m α :=
  fun i j => if i ≤ j then A i j else 0

def h := p₃.solution.1

Lean.Core.checkMaxHeartbeats in Lean.CoreM

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

Float.exp in Init.Data.Float

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

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

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

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

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

add in test.generate_revDeriv

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

Div in Init.Prelude

Real.instInv in Mathlib.Data.Real.Basic

def aggressiveSimpConfig : Simp.Config :=
  { zeta             := true
    beta             := true
    eta              := true
    iota             := true
    proj             := true
    decide           := true
    arith            := true
    dsimp            := true
    unfoldPartialApp := true
    etaStruct        := .all }

Lean.Literal in Lean.Expr

Lean.mkNode in Init.Prelude

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

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

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

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

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

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

Iff in Init.Core

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

def rotatedSoCone (v w : ℝ) (x : n → ℝ) : Prop :=
  (∑ i, x i ^ 2) ≤ (v * w) * 2 ∧ 0 ≤ v ∧ 0 ≤ w

abbrev Argument := Expr

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

Float.sqrt in Init.Data.Float

partial def runEquivalenceTactic (mvarId : MVarId) (stx : Syntax) : TermElabM Unit := do
  runTransformationTactic TransformationGoal.Equivalence mvarId stx

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

Matrix.toSquareBlock in Mathlib.Data.Matrix.Block

def renameVarsBuilder (names : Array Name) : EquivalenceBuilder Unit := fun eqvExpr g => do
  let lhsMinExpr ← eqvExpr.toMinimizationExprLHS
  let vars ← decomposeDomain (← instantiateMVars eqvExpr.domainLHS)

Real.instNNRatCast in Mathlib.Data.Real.Basic

IO.FS.writeFile in Init.System.IO

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

@[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 Vec.soCone (t : m → ℝ) (X : Matrix m n ℝ) : Prop :=
  ∀ i, Real.soCone (t i) (X i)

let (_, mvarId) ← mvarId.assertHypotheses hyps

UInt64 in Init.Prelude

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

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

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)

Lean.addAndCompile in Lean.AddDecl

structure EncodedMatrixList where
  n : Nat
  values : List EncodedMatrixListEntry

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

Lean.Syntax in Init.Prelude

Lean.Meta.inferType in Lean.Meta.Basic

abbrev CanonExpr := Expr

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

def Matrix.nonnegOrthCone {n m} [Fintype n] [Fintype m] (M : Matrix n m ℝ) : Prop :=
  ∀ i j, Real.nonnegOrthCone (M i j)

Lean.Expr.replaceFVars in Lean.Expr

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

def mkSolEqAtomOC (originalVarsDecls : Array LocalDecl) (atoms : OC GraphAtomDataTree)
    (canonWithSolution : OC CanonExprsWithSolutionTree) (vcondVars : OC VCondsTree)
    (originalConstrVars : Array LocalDecl) : MetaM (OC SolEqAtomProofsTree) :=
  withExistingLocalDecls originalVarsDecls.toList do
    withExistingLocalDecls originalConstrVars.toList do
      let solEqAtom ← OC.map3M mkSolEqAtom atoms canonWithSolution vcondVars
      trace[CvxLean.debug] "`solEqAtom`: {solEqAtom}."
      return solEqAtom

def setPSDConstraintsScalarVariablesCoord (p : Problem) (emll : EncodedMatrixListList) : Problem :=
  { p with PSDConstraintsScalarVariablesCoord := emll }

Lean.MData in Lean.Expr

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

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

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

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

abbrev Solution := Array NewVarAssignment

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

abbrev CanonExprsTree := Tree CanonExpr CanonExpr

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

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

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

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

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

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

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)

Matrix.NormedAddCommGroup.ofMatrix in Mathlib.Analysis.Matrix.PosDef

Lake.proc in Lake.Util.Proc

Min.min in Init.Prelude

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

def fromArray (A : Array (Array (Array (Array Float)))) :
    EncodedMatrixListList := Id.run <| do
  let mut emll := 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
        for (l, aijkl) in aijk.data.enum do
          if k >= l && (aijkl > 0 || aijkl < 0) then
            emll := emll.addEntry (EncodedMatrixListListEntry.mk i j k l aijkl)
  return emll

IO.getEnv in Init.System.IO

def w := p₃.solution.2.1

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

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)

HDiv in Init.Prelude

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

Lean.mkStrLit in Lean.Expr

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

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)

Lean.Meta.withLocalDeclD in Lean.Meta.Basic

let (objFun, constraints, originalVarsDecls) ←
    withLambdaBody ogProblem.constraints fun p constraints => do
      let pr := (← Meta.mkProjections D 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 (Name × Expr) ← Meta.decomposeConstraints constraints
        let constraints ← constraints.mapM (fun (n, e) => do
          return (n, ← Expr.removeMData e))
        let objFunP := ogProblem.objFun.bindingBody!.instantiate1 p
        let objFun ← Meta.replaceProjections objFunP p.fvarId! xs
        return (objFun, constraints, originalVarsDecls)

let gs ← getUnsolvedGoals
    if gs.length != 0 then
      throwError "`remove_constr` error: failed to close all goals."

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

Lean.Expr.consumeMData in Lean.Expr

instance {a : ℝ} : ChangeOfVariables (fun x : ℝ => a / x) :=
  { inv := fun x => a / x
    condition := fun x => x ≠ 0 ∧ a ≠ 0
    property := fun _ ⟨_, ha⟩ => by admit /- proof elided -/

BaseIO.toIO in Init.System.IO

@[red]
def rewrite_objFun (hrw : ∀ x, cs x → f x = g x) : ⟨f, cs⟩ ≼ ⟨g, cs⟩ :=
  ofEquivalence <| Equivalence.rewrite_objFun hrw

@[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 addPSDVariable (p : Problem) (d : Nat) : Problem :=
  { p with PSDVariables := p.PSDVariables.addDimension d }

Float.ofInt in Init.Data.OfScientific

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

OrderDual.toDual in Mathlib.Order.Synonym

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

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

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

noncomputable def entr (x : Real) :=
  -(x * log x)

def makeObjFunForward (oldDomain : Expr) (xs : Array Expr) (originalConstrVars : Array LocalDecl)
    (oldProblem : Expr) (constraints : Array Expr) (objFunEq : Expr) : MetaM Expr := do
  
  withLocalDeclD `p oldDomain fun p => do
    let prs := (← Meta.mkProjections oldDomain p).map (·.2.2)

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

def mapM (f : α → MetaM β) (oc : OC α) : MetaM (OC β) := do
  return OC.mk (← f oc.objFun) (← oc.constrs.mapM f)

Float.pow in Init.Data.Float

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

Lean.instantiateMVars in Lean.MetavarContext

Max.max in Init.Prelude

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

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

PiLp.innerProductSpace in Mathlib.Analysis.InnerProductSpace.PiL2

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

Ring in Mathlib.Algebra.Ring.Defs

inductive ScalarConeType
  | Zero | PosOrth | Exp | Q | QR

Sum in Init.Core

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

partial def SexpM.takeString (startPos : String.Pos) : SexpM Substring := do
  match (← SexpM.peek) with
  | none => SexpM.mkSubstring startPos (← SexpM.curPos)
  | some (' ', _) => SexpM.mkSubstring startPos (← SexpM.curPos)
  | some ('(', _) => SexpM.mkSubstring startPos (← SexpM.curPos)
  | some (')', _) => SexpM.mkSubstring startPos (← SexpM.curPos)
  | some _ => do
      SexpM.advance
      SexpM.takeString startPos

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

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

def mkAndIntro (xs : Array Expr) : MetaM Expr := do
  let mut res := xs[xs.size - 1]!
  for i in [:xs.size - 1] do
    res ← mkAppM ``And.intro #[xs[xs.size - 2 - i]!, res]
  return res

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

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

Lean.Syntax.ident in Init.Prelude

HMul.hMul in Init.Prelude

LinearMap in Mathlib.Algebra.Module.LinearMap.Defs

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

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

instance : ToString Sexp := ⟨Sexp.toString⟩

return backwardMap

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

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

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

NormedAddGroup in Mathlib.Analysis.Normed.Group.Basic

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

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

def runTransformationTactic (transf : TransformationGoal) (mvarId : MVarId) (stx : Syntax) :
    TermElabM Unit := do
  let tacticStx := ⟨stx[1]⟩
  let rflTacticStx ←
    match transf with
      | TransformationGoal.Solution => `(tactic| skip)
      | TransformationGoal.Equivalence => `(tactic| equivalence_rfl)
      | TransformationGoal.Reduction => `(tactic| reduction_rfl)
      | TransformationGoal.Relaxation => `(tactic| relaxation_rfl)
  let code ← `(tactic| $tacticStx <;> $rflTacticStx)

Equiv.sumComm in Mathlib.Logic.Equiv.Sum

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

Bool in Init.Prelude

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

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

structure EncodedVectorEntry where
  i : Nat
  value : Float

gNext.setTag Name.anonymous
  setGoals [gNext]

abbrev AtomDataTrees := GraphAtomDataTree × ArgumentsTree × CurvatureTree × BCondsTree

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]

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

SetLike in Mathlib.Data.SetLike.Basic

let (objFunBackward, constrBackward) ←
        withExistingLocalDecls pat.newConstrVarsArray.toList do
          let objFunBackward ← makeObjFunBackward E canonProblemExpr originalVars newVars
            pat.optimality.objFun.val canonConstrs pat.newConstrs pat.newConstrVarsArray

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

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

let newObjFun ← withLocalDeclD `p newDomain fun p => do
    let objFunBody := mkAppNBeta lhsMinExpr.objFun #[p]
    mkLambdaFVars #[p] objFunBody
  let newConstrs ← withLocalDeclD `p newDomain fun p => do
    let objFunBody := mkAppNBeta lhsMinExpr.constraints #[p]
    mkLambdaFVars #[p] objFunBody
  let rhsMinExpr : MinimizationExpr :=
    { domain := newDomain,
      codomain := lhsMinExpr.codomain,
      objFun := newObjFun,
      constraints := newConstrs }
  if !(← isDefEq eqvExpr.rhs rhsMinExpr.toExpr) then
    throwRenameVarsError "failed to unify the goal."

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

Lean.Parser.termParser in Lean.Parser.Basic

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

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

Lean.Meta.mkFreshExprMVar in Lean.Meta.Basic

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

Lean.TSyntax in Init.Prelude

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

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

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

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

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

IO in Init.System.IO

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

structure EncodedVector where
  n : Nat
  values : List EncodedVectorEntry

noncomputable instance instDivReal : Div ℝ :=

LE in Init.Prelude

let forwardMap ← makeForwardMap D originalVars pat.forwardImagesNewVars

instance : Hashable Key := ⟨Key.hash⟩

Mathlib.Meta.Positivity.core in Mathlib.Tactic.Positivity.Core

inductive TransformationGoal
  | Solution | Equivalence | Reduction | Relaxation

withLocalDeclD `h (← mkAppM ``Minimization.constraints #[oldProblem, p]) fun h => do
      let (_, cprs) := Meta.composeAndWithProj constraints.toList
      let hProj := (cprs h).toArray

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

MonadReaderOf in Init.Prelude

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

let vcondIdx : OC VCondsIdxsTree := vcondData.map
      (fun t => t.map (fun iores => iores.foldl (init := #[]) (fun (acc : Array ℕ) iore =>
        match iore with
          | Sum.inl i => acc.push i
          | Sum.inr _ => acc))
        id)

return forwardMap

sequence in Mathlib.Control.Traversable.Basic

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

Lean.mkConst in Lean.Expr

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

def Matrix.quadForm {n : ℕ} (R : Matrix (Fin n) (Fin n) ℝ) (x : Fin n → ℝ) : ℝ :=
  x ⬝ᵥ R.mulVec x

inductive Sexp
  | atom : String → Sexp
  | list : List Sexp → Sexp
  deriving BEq, Inhabited, Repr

def decomposeLabel (e : Expr) : m (Name × Expr) := do
  match e with
  | Expr.mdata m e =>
      match m.get? `CvxLeanLabel with
      | some (name : Name) => return (name, e)
      | none => decomposeLabel e
  | _ => return (`_, e)

instance : ToString EncodedVector where
  toString ev :=
    (toString ev.n) ++ "\n" ++
    (ev.values.foldl (fun acc eve => acc ++ (toString eve) ++ "\n") "")

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

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

Array.range in Init.Data.Array.Basic

abbrev VCondsIdxs := Array VCondIdx

Function.comp in Init.Prelude

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

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

Sub in Init.Prelude

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

Lean.Meta.ParamInfo in Lean.Meta.Basic

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

abbrev VCondsTree := Tree VConds Unit

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

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

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

Lean.LocalDecl.fvarId in Lean.LocalContext

OfNat in Init.Prelude

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

noncomputable instance (priority := high) {n} : NormedAddCommGroup (Fin n → ℝ) :=
  PiLp.normedAddCommGroup 2 _

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

Lean.Json.Parser.num in Lean.Data.Json.Parser

String.Iterator in Init.Data.String.Iterator

Neg in Init.Prelude

Lean.mkNullNode in Init.Prelude

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

def ofEggOCTree (oc : EggOCTree) : EggMinimization :=
  { objFun := EggTree.toEggString oc.objFun.2,
    constrs := Array.data <| oc.constrs.map fun (h, c) => (h, EggTree.toEggString c) }

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

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

Lean.TransformStep.continue in Lean.Meta.Transform
</all_available_defs>

<all_available_lemmas>
lemma feasible_and_bounded_of_feasible (Rx : p ≽' q) {x : D} (h_feas_x : p.feasible x) :
    q.feasible (Rx.phi x) ∧ q.objFun (Rx.phi x) ≤ p.objFun x

lemma soCone_sub_add_two_mul_of_nonneg {x y : ℝ} (z : ℝ) :
    soCone (x - y) ![x + y, 2 * z] ↔ y ≤ x ∧ z ^ (2 : ℝ) ≤ -(x * y)

lemma BlockTriangular_blockDiagonal [DecidableEq α] (d : α → Matrix m m R) :
    BlockTriangular (blockDiagonal d) Prod.snd

lemma PosDef.conjTranspose_mul_mul [DecidableEq n] (M N : Matrix n n 𝕜) (hM : M.PosDef)
    (hN : N.det ≠ 0) : (Nᴴ * M * N).PosDef

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

lemma IsHermitian.one_add {A : Matrix n n ℝ} (hA : A.IsHermitian) : (1 + A).IsHermitian

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

lemma LDL.diagEntries_pos {A : Matrix n n ℝ} (hA: A.PosDef) (i : n) :
    0 < LDL.diagEntries hA i

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

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

theorem toUpperTri_add {m : Type _} [LinearOrder m]
    (A B : Matrix m m ℝ) :
    Matrix.toUpperTri (A + B) = Matrix.toUpperTri A + Matrix.toUpperTri B

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

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 has_eigenvector_one {x : M} (hx : x ≠ 0) : HasEigenvector (1 : End R M) 1 x

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

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 conjTranspose_eq_transpose {m n : Type _} {A : Matrix m n ℝ} : Aᴴ = Aᵀ

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

lemma rotateSoCone_rotatedSoCone {n : ℕ} {t : ℝ} {x : Fin n.succ → ℝ} (h : soCone t x) :
    let (v, w, x) := rotateSoCone t x; rotatedSoCone v w x

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

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

lemma BlockTriangular_blockDiagonal' [DecidableEq α]
    (d : ∀ (i : α), Matrix (m' i) (m' i) R) :
    BlockTriangular (blockDiagonal'  d) Sigma.fst

lemma upperTriangular_inv_of_upperTriangular [Fintype m] [LinearOrder m]
    [Invertible M] (hM : upperTriangular M) : upperTriangular M⁻¹

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

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

lemma LogDetAtom.optimality_D_posdef {t : n → ℝ} {Y Z D : Matrix n n ℝ}
    (ht : ∀ i, (t i).exp ≤ Y.diag i) (hD : D = Matrix.diagonal (Y.diag)) (_hZ : Z = Y.toUpperTri)
    (hPSD : (fromBlocks D Z Zᵀ A).PosSemidef) : D.PosDef

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

lemma toSquareBlock_inv_mul_toSquareBlock_eq_one [LinearOrder α]
    [Invertible M] (hM : BlockTriangular M b) (k : α) :
    M⁻¹.toSquareBlock b k * M.toSquareBlock b k = 1

lemma Real.one_sub_sq_nonneg_of_le_one {x : ℝ} : 0 ≤ x → 0 ≤ 1 - x → 0 ≤ 1 - x ^ (2 : ℝ)

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

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
</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 div_le_iff (hb : StrongLT 0 b) : a / b ≤ c ↔ a ≤ c * b :=
</target_theorem>

