fact
stringlengths
5
7.52k
type
stringclasses
9 values
library
stringclasses
2 values
imports
listlengths
0
15
filename
stringclasses
121 values
symbolic_name
stringlengths
1
53
docstring
stringlengths
6
446
compileCargo (name : String) (manifestFile : FilePath) (cargo : FilePath := "cargo") (env : Array (String × Option String)) : LogIO Unit := do logInfo s!"Creating {name}" proc { env := env cmd := cargo.toString args := #["build", "--release", "--manifest-path", manifestFile.toString] }
def
root
[ "import Lake" ]
lakefile.lean
compileCargo
null
buildCargo (targetFile : FilePath) (manifestFile : FilePath) (targetDest : FilePath) (oFileJobs : Array (BuildJob FilePath)) (stopOnSuccess : Bool) : SpawnM (BuildJob FilePath) := let name := targetFile.fileName.getD targetFile.toString buildFileAfterDepArray targetFile oFileJobs fun _ => do let env := if stopOnSuccess then #[("RUSTFLAGS", some "--cfg stop_on_success")] else #[] compileCargo name manifestFile (env := env) createParentDirs targetDest proc { cmd := "cp" args := #[targetFile.toString, targetDest.toString] } 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 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 script EggClean := do let targetDir : FilePath := "." / "egg-pre-dcp" / "target" let utilsDir : FilePath := "." / "egg-pre-dcp" / "utils" let out ← IO.Process.output { cmd := "rm" args := #["-rf", targetDir.toString] } *> IO.Process.output { cmd := "rm" args := #["-rf", utilsDir.toString] } pure out.exitCode
def
root
[ "import Lake" ]
lakefile.lean
buildCargo
null
runEquivalenceTactic (mvarId : MVarId) (stx : Syntax) : TermElabM Unit := do runTransformationTactic TransformationGoal.Equivalence mvarId stx /-- Run equivalence tactic and return both the right-hand term (`q`) and the equivalence proof, of type `Equivalence p q`. -/
def
CvxLean
[ "import CvxLean.Lib.Equivalence", "import CvxLean.Syntax.Minimization", "import CvxLean.Meta.Util.Expr", "import CvxLean.Meta.Util.Simp", "import CvxLean.Meta.Util.Error", "import CvxLean.Meta.Util.Debug", "import CvxLean.Meta.Equivalence", "import CvxLean.Meta.TacticBuilder", "import CvxLean.Command.Solve.Float.RealToFloatLibrary" ]
CvxLean/Command/Equivalence.lean
runEquivalenceTactic
/-- Run a transformation tactic indicating that an equivalence is expected. -/
elabEquivalenceProof (lhs : Expr) (rhsName : Name) (stx : Syntax) : TermElabM (Expr × Expr) := elabTransformationProof TransformationGoal.Equivalence lhs rhsName stx /-- Open an equivalence environment. -/ syntax (name := equivalence) "equivalence" ident "/" ident declSig ":=" Lean.Parser.Term.byTactic : command /-- Open an equivalence environment and try to generate a computable backward map. -/ syntax (name := equivalenceAndBwdMap) "equivalence*" ident "/" ident declSig ":=" Lean.Parser.Term.byTactic : command /-- Open an equivalence environment with a given left-hand-side problem (`lhsStx`) and perhaps some parameters (`xs`). From this, an equivalence goal is set to a target problem which is represented by a metavariable. The proof (`proofStx`) is evaluated to produce the desired equivalence. The metavariable is then instantiated and the resulting problem is stored using the identifier `probIdStx`. The equivalence witness is stored according to the identifier `redIdStx`. Optionally, a floating-point backward solution map is created. See `evalEquivalence` and `evalEquivalenceAndBwdMap`. -/
def
CvxLean
[ "import CvxLean.Lib.Equivalence", "import CvxLean.Syntax.Minimization", "import CvxLean.Meta.Util.Expr", "import CvxLean.Meta.Util.Simp", "import CvxLean.Meta.Util.Error", "import CvxLean.Meta.Util.Debug", "import CvxLean.Meta.Equivalence", "import CvxLean.Meta.TacticBuilder", "import CvxLean.Command.Solve.Float.RealToFloatLibrary" ]
CvxLean/Command/Equivalence.lean
elabEquivalenceProof
/-- Run equivalence tactic and return both the right-hand term (`q`) and the equivalence proof, of type `Equivalence p q`. -/
evalEquivalenceAux (probIdStx eqvIdStx : TSyntax `ident) (xs : Array (Syntax × Expr)) (lhsStx : Syntax) (proofStx : TSyntax `Lean.Parser.Term.byTactic) (bwdMap : Bool) : TermElabM Unit := do let D ← Meta.mkFreshTypeMVar let R ← Meta.mkFreshTypeMVar let lhsTy := mkApp2 (Lean.mkConst ``Minimization) D R let lhs ← elabTermAndSynthesizeEnsuringType lhsStx (some lhsTy) -- NOTE: `instantiateMVars` does not infer the preorder instance. for mvarId in ← getMVars lhs do try { let mvarVal ← synthInstance (← mvarId.getDecl).type mvarId.assign mvarVal } catch _ => pure () let rhsName := probIdStx.getId let (rhs, eqv) ← elabEquivalenceProof lhs rhsName proofStx -- Names for new definitions. let currNamespace ← getCurrNamespace let probId := currNamespace ++ probIdStx.getId let eqvId := currNamespace ++ eqvIdStx.getId -- Add equivalent problem to the environment. let rhs ← instantiateMVars rhs let rhs ← mkLambdaFVars (xs.map Prod.snd) rhs let rhs ← instantiateMVars rhs simpleAddDefn probId rhs -- Add equivalence proof to the environment. let eqv ← instantiateMVars eqv let eqv ← mkLambdaFVars (xs.map Prod.snd) eqv let eqv ← instantiateMVars eqv simpleAddDefn eqvId eqv if bwdMap then lambdaTelescope eqv fun eqvArgs eqvBody => do -- Get psi, reduce it appropriately and convert to float. let psi := (← whnf eqvBody).getArg! 7 trace[CvxLean.debug] "psi: {psi}" let mut simpCtx ← Simp.Context.mkDefault simpCtx := { simpCtx with config := aggressiveSimpConfig } let (.some ext) ← getSimpExtension? `equiv | throwEquivalenceError "could not find `equiv` simp extension." let mut simpThms ← ext.getTheorems simpThms ← simpThms.addDeclToUnfold ``Minimization.Equivalence.mk simpThms ← simpThms.addDeclToUnfold ``Minimization.Equivalence.psi simpThms ← simpThms.addDeclToUnfold ``Eq.mp simpThms ← simpThms.addDeclToUnfold ``Eq.mpr simpCtx := { simpCtx with simpTheorems := #[simpThms] } let (res, _) ← simp psi simpCtx -- NOTE: We ignore arguments with `Prop`s here as keeping them would only mean requiring -- proofs about floats. let eqvNonPropArgs ← eqvArgs.filterM fun arg => do return !(← inferType (← inferType arg)).isProp let psi ← mkLambdaFVars eqvNonPropArgs res.expr trace[CvxLean.debug] "simplified psi: {psi}" try let psiF ← realToFloat psi Lean.simpleAddAndCompileDefn (eqvId ++ `backward_map) psiF catch e => trace[CvxLean.debug] "`equivalence` warning: failed to create `{eqvId}.backward_map`.\n{e.toMessageData}" /-- Create `equivalence` command. -/ @[command_elab «equivalence»]
def
CvxLean
[ "import CvxLean.Lib.Equivalence", "import CvxLean.Syntax.Minimization", "import CvxLean.Meta.Util.Expr", "import CvxLean.Meta.Util.Simp", "import CvxLean.Meta.Util.Error", "import CvxLean.Meta.Util.Debug", "import CvxLean.Meta.Equivalence", "import CvxLean.Meta.TacticBuilder", "import CvxLean.Command.Solve.Float.RealToFloatLibrary" ]
CvxLean/Command/Equivalence.lean
evalEquivalenceAux
null
evalEquivalence : CommandElab := fun stx => match stx with | `(equivalence $eqvId / $probId $declSig := $proofStx) => do liftTermElabM do let (binders, lhsStx) := expandDeclSig declSig.raw elabBindersEx binders.getArgs fun xs => evalEquivalenceAux probId eqvId xs lhsStx proofStx false | _ => throwUnsupportedSyntax /-- Same as `equivalence` but also adds the backward map to the environment. -/ @[command_elab «equivalenceAndBwdMap»]
def
CvxLean
[ "import CvxLean.Lib.Equivalence", "import CvxLean.Syntax.Minimization", "import CvxLean.Meta.Util.Expr", "import CvxLean.Meta.Util.Simp", "import CvxLean.Meta.Util.Error", "import CvxLean.Meta.Util.Debug", "import CvxLean.Meta.Equivalence", "import CvxLean.Meta.TacticBuilder", "import CvxLean.Command.Solve.Float.RealToFloatLibrary" ]
CvxLean/Command/Equivalence.lean
evalEquivalence
/-- Create `equivalence` command. -/
evalEquivalenceAndBwdMap : CommandElab := fun stx => match stx with | `(equivalence* $eqvId / $probId $declSig := $proofStx) => do liftTermElabM do let (binders, lhsStx) := expandDeclSig declSig.raw elabBindersEx binders.getArgs fun xs => evalEquivalenceAux probId eqvId xs lhsStx proofStx true | _ => throwUnsupportedSyntax
def
CvxLean
[ "import CvxLean.Lib.Equivalence", "import CvxLean.Syntax.Minimization", "import CvxLean.Meta.Util.Expr", "import CvxLean.Meta.Util.Simp", "import CvxLean.Meta.Util.Error", "import CvxLean.Meta.Util.Debug", "import CvxLean.Meta.Equivalence", "import CvxLean.Meta.TacticBuilder", "import CvxLean.Command.Solve.Float.RealToFloatLibrary" ]
CvxLean/Command/Equivalence.lean
evalEquivalenceAndBwdMap
/-- Same as `equivalence` but also adds the backward map to the environment. -/
runReductionTactic (mvarId : MVarId) (stx : Syntax) : TermElabM Unit := runTransformationTactic TransformationGoal.Reduction mvarId stx /-- Run reduction tactic and return both the right-hand term (`q`) and the reduction proof, of type `Reduction p q`. -/
def
CvxLean
[ "import Lean", "import CvxLean.Lib.Reduction", "import CvxLean.Syntax.Minimization", "import CvxLean.Meta.Util.Expr", "import CvxLean.Meta.Util.Simp", "import CvxLean.Meta.Util.Error", "import CvxLean.Meta.Util.Debug", "import CvxLean.Meta.Reduction", "import CvxLean.Meta.TacticBuilder", "import CvxLean.Command.Solve.Float.RealToFloatLibrary" ]
CvxLean/Command/Reduction.lean
runReductionTactic
/-- Run a transformation tactic indicating that a reduction is expected. -/
elabReductionProof (lhs : Expr) (rhsName : Name) (stx : Syntax) : TermElabM (Expr × Expr) := elabTransformationProof TransformationGoal.Reduction lhs rhsName stx /-- Open a reduction environment. -/ syntax (name := reduction) "reduction" ident "/" ident declSig ":=" Lean.Parser.Term.byTactic : command /-- Open a reduction environment and try to generate a computable backward map. -/ syntax (name := reductionAndBwdMap) "reduction*" ident "/" ident declSig ":=" Lean.Parser.Term.byTactic : command /-- Open a reduction environment with a given left-hand-side problem (`lhsStx`) and perhaps some parameters (`xs`). From this, a reduction goal is set to a target problem which is represented by a metavariable. The proof (`proofStx`) is evaluated to produce the desired reduction. The metavariable is then instantiated and the resulting problem is stored using the identifier `probIdStx`. The reduction witness is stored according to the identifier `redIdStx`. Optionally, a floating-point backward solution map is created. See `evalReduction` and `evalReductionAndBwdMap`. -/
def
CvxLean
[ "import Lean", "import CvxLean.Lib.Reduction", "import CvxLean.Syntax.Minimization", "import CvxLean.Meta.Util.Expr", "import CvxLean.Meta.Util.Simp", "import CvxLean.Meta.Util.Error", "import CvxLean.Meta.Util.Debug", "import CvxLean.Meta.Reduction", "import CvxLean.Meta.TacticBuilder", "import CvxLean.Command.Solve.Float.RealToFloatLibrary" ]
CvxLean/Command/Reduction.lean
elabReductionProof
/-- Run reduction tactic and return both the right-hand term (`q`) and the reduction proof, of type `Reduction p q`. -/
evalReductionAux (probIdStx redIdStx : TSyntax `ident) (xs : Array (Syntax × Expr)) (lhsStx : Syntax) (proofStx : TSyntax `Lean.Parser.Term.byTactic) (bwdMap : Bool) : TermElabM Unit := do let D ← Meta.mkFreshTypeMVar let R ← Meta.mkFreshTypeMVar let lhsTy := mkApp2 (Lean.mkConst ``Minimization) D R let lhs ← elabTermAndSynthesizeEnsuringType lhsStx (some lhsTy) -- NOTE: `instantiateMVars` does not infer the preorder instance. for mvarId in ← getMVars lhs do try { let mvarVal ← synthInstance (← mvarId.getDecl).type mvarId.assign mvarVal } catch _ => pure () let rhsName := probIdStx.getId let (rhs, red) ← elabReductionProof lhs rhsName proofStx -- Names for new definitions. let currNamespace ← getCurrNamespace let probId := currNamespace ++ probIdStx.getId let redId := currNamespace ++ redIdStx.getId -- Add reduced problem to the environment. let rhs ← instantiateMVars rhs let rhs ← mkLambdaFVars (xs.map Prod.snd) rhs let rhs ← instantiateMVars rhs simpleAddDefn probId rhs -- Add reduction proof to the environment. let red ← instantiateMVars red let red ← mkLambdaFVars (xs.map Prod.snd) red let red ← instantiateMVars red simpleAddDefn redId red if bwdMap then lambdaTelescope red fun eqvArgs redBody => do -- Get psi, reduce it appropriately and convert to float. let psi := (← whnf redBody).getArg! 6 trace[CvxLean.debug] "psi: {psi}" let mut simpCtx ← Simp.Context.mkDefault simpCtx := { simpCtx with config := aggressiveSimpConfig } let (.some redExt) ← getSimpExtension? `red | throwReductionError "could not find `red` simp extension." let (.some equivExt) ← getSimpExtension? `equiv | throwReductionError "could not find `equiv` simp extension." let mut simpEqvThms ← equivExt.getTheorems simpEqvThms ← simpEqvThms.addDeclToUnfold ``Minimization.Equivalence.mk simpEqvThms ← simpEqvThms.addDeclToUnfold ``Minimization.Equivalence.psi let mut simpRedThms ← redExt.getTheorems simpRedThms ← simpRedThms.addDeclToUnfold ``Minimization.Reduction.mk simpRedThms ← simpRedThms.addDeclToUnfold ``Minimization.Reduction.psi simpRedThms ← simpRedThms.addDeclToUnfold ``Eq.mp simpRedThms ← simpRedThms.addDeclToUnfold ``Eq.mpr simpCtx := { simpCtx with simpTheorems := #[simpRedThms, simpEqvThms] } let (res, _) ← simp psi simpCtx -- NOTE: We ignore arguments with `Prop`s here as keeping them would only mean requiring -- proofs about floats. let redNonPropArgs ← eqvArgs.filterM fun arg => do return !(← inferType (← inferType arg)).isProp let psi ← mkLambdaFVars redNonPropArgs res.expr trace[CvxLean.debug] "simplified psi: {psi}" try let psiF ← realToFloat psi Lean.simpleAddAndCompileDefn (redId ++ `backward_map) psiF catch e => trace[CvxLean.debug] "`reduction` warning: failed to create `{redId}.backward_map`.\n{e.toMessageData}" /-- Create `reduction` command. It is similar to the `equivalence` command, but requires a `Reduction` instead of an `Equivalence`. -/ @[command_elab «reduction»]
def
CvxLean
[ "import Lean", "import CvxLean.Lib.Reduction", "import CvxLean.Syntax.Minimization", "import CvxLean.Meta.Util.Expr", "import CvxLean.Meta.Util.Simp", "import CvxLean.Meta.Util.Error", "import CvxLean.Meta.Util.Debug", "import CvxLean.Meta.Reduction", "import CvxLean.Meta.TacticBuilder", "import CvxLean.Command.Solve.Float.RealToFloatLibrary" ]
CvxLean/Command/Reduction.lean
evalReductionAux
null
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 /-- Same as `reduction` but also adds the backward map to the environment. -/ @[command_elab «reductionAndBwdMap»]
def
CvxLean
[ "import Lean", "import CvxLean.Lib.Reduction", "import CvxLean.Syntax.Minimization", "import CvxLean.Meta.Util.Expr", "import CvxLean.Meta.Util.Simp", "import CvxLean.Meta.Util.Error", "import CvxLean.Meta.Util.Debug", "import CvxLean.Meta.Reduction", "import CvxLean.Meta.TacticBuilder", "import CvxLean.Command.Solve.Float.RealToFloatLibrary" ]
CvxLean/Command/Reduction.lean
evalReduction
/-- Create `reduction` command. It is similar to the `equivalence` command, but requires a `Reduction` instead of an `Equivalence`. -/
evalReductionAndBwdMap : CommandElab := fun stx => match stx with | `(reduction* $eqvId / $probId $declSig := $proofStx) => do liftTermElabM do let (binders, lhsStx) := expandDeclSig declSig.raw elabBindersEx binders.getArgs fun xs => evalReductionAux probId eqvId xs lhsStx proofStx true | _ => throwUnsupportedSyntax
def
CvxLean
[ "import Lean", "import CvxLean.Lib.Reduction", "import CvxLean.Syntax.Minimization", "import CvxLean.Meta.Util.Expr", "import CvxLean.Meta.Util.Simp", "import CvxLean.Meta.Util.Error", "import CvxLean.Meta.Util.Debug", "import CvxLean.Meta.Reduction", "import CvxLean.Meta.TacticBuilder", "import CvxLean.Command.Solve.Float.RealToFloatLibrary" ]
CvxLean/Command/Reduction.lean
evalReductionAndBwdMap
/-- Same as `reduction` but also adds the backward map to the environment. -/
runRelaxationTactic (mvarId : MVarId) (stx : Syntax) : TermElabM Unit := runTransformationTactic TransformationGoal.Relaxation mvarId stx /-- Run relaxation tactic and return both the right-hand term (`q`) and the relaxation proof, of type `Relaxation p q`. -/
def
CvxLean
[ "import Lean", "import CvxLean.Lib.Relaxation", "import CvxLean.Syntax.Minimization", "import CvxLean.Meta.Util.Expr", "import CvxLean.Meta.Relaxation", "import CvxLean.Meta.TacticBuilder" ]
CvxLean/Command/Relaxation.lean
runRelaxationTactic
/-- Run a transformation tactic indicating that a relaxation is expected. -/
elabRelaxationProof (lhs : Expr) (rhsName : Name) (stx : Syntax) : TermElabM (Expr × Expr) := elabTransformationProof TransformationGoal.Relaxation lhs rhsName stx /-- Open a relaxation environment. -/ syntax (name := relaxation) "relaxation" ident "/" ident declSig ":=" Lean.Parser.Term.byTactic : command /-- Definition of the `relaxation` command. -/ @[command_elab «relaxation»]
def
CvxLean
[ "import Lean", "import CvxLean.Lib.Relaxation", "import CvxLean.Syntax.Minimization", "import CvxLean.Meta.Util.Expr", "import CvxLean.Meta.Relaxation", "import CvxLean.Meta.TacticBuilder" ]
CvxLean/Command/Relaxation.lean
elabRelaxationProof
/-- Run relaxation tactic and return both the right-hand term (`q`) and the relaxation proof, of type `Relaxation p q`. -/
evalRelaxation : CommandElab := fun stx => match stx with | `(relaxation $relIdStx / $probIdStx $declSig := $proofStx) => do liftTermElabM do let (binders, lhsStx) := expandDeclSig declSig.raw elabBindersEx binders.getArgs fun xs => do let D ← Meta.mkFreshTypeMVar let R ← Meta.mkFreshTypeMVar let lhsTy := mkApp2 (Lean.mkConst ``Minimization) D R let lhs ← elabTermAndSynthesizeEnsuringType lhsStx (some lhsTy) -- NOTE: `instantiateMVars` does not infer the preorder instance. for mvarId in ← getMVars lhs do try { let mvarVal ← synthInstance (← mvarId.getDecl).type mvarId.assign mvarVal } catch _ => pure () let rhsName := probIdStx.getId let (rhs, proof) ← elabRelaxationProof lhs rhsName proofStx.raw -- Names for new definitions. let currNamespace ← getCurrNamespace let probId := currNamespace ++ probIdStx.getId let relId := currNamespace ++ relIdStx.getId -- Add relaxed problem to the environment. let rhs ← instantiateMVars rhs let rhs ← mkLambdaFVars (xs.map Prod.snd) rhs let rhs ← instantiateMVars rhs simpleAddDefn probId rhs -- Add Relaxation proof to the environment. let proof ← mkLambdaFVars (xs.map Prod.snd) proof let proof ← instantiateMVars proof simpleAddDefn relId proof | _ => throwUnsupportedSyntax
def
CvxLean
[ "import Lean", "import CvxLean.Lib.Relaxation", "import CvxLean.Syntax.Minimization", "import CvxLean.Meta.Util.Expr", "import CvxLean.Meta.Relaxation", "import CvxLean.Meta.TacticBuilder" ]
CvxLean/Command/Relaxation.lean
evalRelaxation
/-- Definition of the `relaxation` command. -/
getProblemName (stx : Syntax) : MetaM Name := do -- TODO: Full name with parameters? let idStx := match stx with | Syntax.ident _ _ _ _ => stx | Syntax.node _ _ args => args.getD 0 Syntax.missing | _ => Syntax.missing if ¬ idStx.getId.isStr then throwError "Invalid name for minimization problem: {idStx}." let currNamespace ← getCurrNamespace return currNamespace ++ idStx.getId /-- Call DCP and get the problem in conic form as well as `ψ`, the backward map from the equivalence. -/
def
CvxLean
[ "import CvxLean.Tactic.DCP.AtomLibrary.All", "import CvxLean.Command.Solve.Conic" ]
CvxLean/Command/Solve.lean
getProblemName
/-- Get problem name. Used to add information about the solution to the environment. -/
getCanonizedProblemAndBwdMap (prob : Expr) : MetaM (MinimizationExpr × Expr) := do let ogProb ← MinimizationExpr.fromExpr prob let (canonProb, eqvProof) ← DCP.canonize ogProb let backwardMap ← mkAppM ``Minimization.Equivalence.psi #[eqvProof] return (canonProb, backwardMap) syntax (name := solve) "solve " term : command /-- The `solve` command. It works as follows: 1. Canonize optimization problem to conic form. 2. Extract problem data using `determineCoeffsFromExpr`. 3. Obtain a solution using `solutionDataFromProblemData`, which calls an external solver. 4. Store the result in the enviroment. -/ @[command_elab «solve»]
def
CvxLean
[ "import CvxLean.Tactic.DCP.AtomLibrary.All", "import CvxLean.Command.Solve.Conic" ]
CvxLean/Command/Solve.lean
getCanonizedProblemAndBwdMap
/-- Call DCP and get the problem in conic form as well as `ψ`, the backward map from the equivalence. -/
evalSolve : CommandElab := fun stx => match stx with | `(solve $probInstance) => liftTermElabM <| do let probTerm ← elabTerm probInstance.raw none let probTerm ← whnf probTerm let probTerm ← instantiateMVars probTerm -- NOTE: Needed to solve the "OfNat" mvar bug. for mvarId in ← getMVars probTerm do try { let mvarVal ← synthInstance (← mvarId.getDecl).type mvarId.assign mvarVal } catch _ => pure () -- Create prob.conicForm. let (canonProb, backwardMap) ← getCanonizedProblemAndBwdMap probTerm let canonProbExpr := canonProb.toExpr let probName ← getProblemName probInstance.raw simpleAddDefn (probName ++ `conicForm) canonProbExpr -- Call the solver on prob.conicForm and get a point in E. let (coeffsData, sections) ← determineCoeffsFromExpr canonProb trace[CvxLean.debug] "Coeffs data:\n{coeffsData}" let solData ← solutionDataFromProblemData canonProb coeffsData sections trace[CvxLean.debug] "Solution data:\n{solData}" -- Add status to the environment. simpleAddAndCompileDefn (probName ++ `status) (mkStrLit solData.status) -- TODO: For now, we are only handling this case. if solData.status != "PRIMAL_AND_DUAL_FEASIBLE" then pure () -- Solution makes sense, handle the numerical solution. let solPointExpr ← exprFromSolutionData canonProb solData trace[CvxLean.debug] "Solution point (canonized problem): {solPointExpr}" let backwardMapFloat ← realToFloat <| ← whnf backwardMap let solPointExprFloat ← realToFloat solPointExpr let probSolPointFloat ← whnf <| mkAppN backwardMapFloat #[solPointExprFloat] trace[CvxLean.debug] "Float solution point (original problem): {probSolPointFloat}" -- Add the solution point to the environment. simpleAddAndCompileDefn (probName ++ `solution) probSolPointFloat -- Also add value of optimal point. let probSolValue := mkApp canonProb.objFun solPointExpr let probSolValueFloat ← realToFloat probSolValue check probSolValueFloat let mut probSolValueFloat := Expr.headBeta probSolValueFloat trace[CvxLean.debug] "Float problem value (original problem): {probSolValueFloat}" if probSolValueFloat.getAppFn.isConstOf `CvxLean.maximizeNeg then probSolValueFloat := probSolValueFloat.getAppArgs[2]! simpleAddAndCompileDefn (probName ++ `value) probSolValueFloat pure () | _ => throwUnsupportedSyntax
def
CvxLean
[ "import CvxLean.Tactic.DCP.AtomLibrary.All", "import CvxLean.Command.Solve.Conic" ]
CvxLean/Command/Solve.lean
evalSolve
/-- The `solve` command. It works as follows: 1. Canonize optimization problem to conic form. 2. Extract problem data using `determineCoeffsFromExpr`. 3. Obtain a solution using `solutionDataFromProblemData`, which calls an external solver. 4. Store the result in the enviroment. -/
p₁ := optimization (x y : ℝ) maximize sqrt (x - y) subject to c1 : y = 2 * x - 3 c2 : x ^ (2 : ℝ) ≤ 2 c3 : 0 ≤ x - y #check p₁ -- Apply DCP transformation and call solver. solve p₁ #eval p₁.status #eval p₁.solution #eval p₁.value /- Second example. -/
def
CvxLean
[ "import CvxLean" ]
CvxLean/Demos/LT2024.lean
p₁
null
p₂ := optimization (x : ℝ) minimize (x) subject to c1 : 1 / 1000 ≤ x c2 : 1 / sqrt x ≤ exp x -- solve p₂ -- set_option trace.Meta.debug true -- Equivalence mode. equivalence eqv₂/q₂ : p₂ := by pre_dcp solve q₂ #print q₂.conicForm #eval q₂.status #eval q₂.solution #eval q₂.value /- Third example (geometric programming). -/ /-- Maximizing the volume of a box. See: https://www.cvxpy.org/examples/dgp/max_volume_box.html -/
def
CvxLean
[ "import CvxLean" ]
CvxLean/Demos/LT2024.lean
p₂
null
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 := by change_of_variables! (h') (h ↦ exp h') change_of_variables! (w') (w ↦ exp w') change_of_variables! (d') (d ↦ exp d') pre_dcp solve q₃ #print q₃.conicForm #eval q₃.status #eval q₃.solution #eval q₃.value #check eqv₃
def
CvxLean
[ "import CvxLean" ]
CvxLean/Demos/LT2024.lean
p₃
/-- Maximizing the volume of a box. See: https://www.cvxpy.org/examples/dgp/max_volume_box.html -/
p₃.solution := eqv₃.backward_map q₃.solution #eval p₃.solution
def
CvxLean
[ "import CvxLean" ]
CvxLean/Demos/LT2024.lean
p₃.solution
null
h := p₃.solution.1
def
CvxLean
[ "import CvxLean" ]
CvxLean/Demos/LT2024.lean
h
null
w := p₃.solution.2.1
def
CvxLean
[ "import CvxLean" ]
CvxLean/Demos/LT2024.lean
w
null
d := p₃.solution.2.2 #eval h * w * d #eval 2 * (h * w + h * d) ≤ 100 #eval w * d ≤ 10 #eval 0.5 ≤ h / w #eval h / w ≤ 2 #eval 0.5 ≤ d / w #eval d / w ≤ 2
def
CvxLean
[ "import CvxLean" ]
CvxLean/Demos/LT2024.lean
d
null
p := optimization (x y : ℝ) minimize -2 * x subject to c₁ : 0 ≤ x c₂ : 1 < y c₃ : log (y - 1) ≤ 2 * sqrt x + 1 c₄ : 3 * x + 5 * y ≤ 10 -- Transform (proving `p ≡ q`). equivalence* eqv/q : p := by change_of_variables! (v) (y ↦ v + 1) change_of_variables! (w) (v ↦ exp w) remove_constr c₂ => field_simp; arith -- Make DCP-compliant automatically: -- pre_dcp -- Or, manually: rw_constr c₃ into (w ≤ 2 * sqrt x + 1) => field_simp #print q #check eqv -- Solve (proving `q ≡ q.conicForm`). solve q #print q.conicForm #eval q.status #eval q.value #eval q.solution #eval eqv.backward_map q.solution
def
CvxLean
[ "import CvxLean" ]
CvxLean/Demos/README.lean
p
null
covEstimation (n : ℕ) (N : ℕ) (α : ℝ) (y : Fin N → Fin n → ℝ) := optimization (R : Matrix (Fin n) (Fin n) ℝ) maximize (∏ i, gaussianPdf R (y i)) subject to c_pos_def : R.PosDef c_sparse : R⁻¹.abs.sum ≤ α reduction* red/covEstimationConvex (n : ℕ) (N : ℕ) (α : ℝ) (y : Fin N → Fin n → ℝ) : covEstimation n N α y := by -- Change objective function. reduction_step => apply Reduction.map_objFun_of_order_reflecting (g := fun x => -log (-x)) · intros R S hR hS h apply neg_le_neg simp only [maximizeNeg] at h rwa [neg_neg, neg_neg, neg_le_neg_iff, log_le_log_iff] at h exact prod_gaussianPdf_pos S y hS.1 exact prod_gaussianPdf_pos R y hR.1 conv_opt => simp only [Function.comp, neg_neg, maximizeNeg] -- Move logarithm and sum inward. reduction_step => apply Reduction.rewrite_objFun · intros R hR simp only [log_prod_gaussianPdf _ R hR.1, Finset.sum_add_distrib, Finset.sum_neg_distrib, neg_div] rewrite [Finset.sum_const, Finset.sum_const, Finset.card_fin] rw [← Finset.sum_div, sum_quadForm, @Real.log_sqrt (det R)] apply hR.1.posSemidef.det_nonneg -- Change of variables using matrix inverse. reduction_step => apply Reduction.map_domain (fwd := (·⁻¹)) (bwd := (·⁻¹)) · intros R hR simp only [nonsing_inv_nonsing_inv R hR.1.isUnit_det] -- Dissolve matrix inverse. conv_opt => simp only [Function.comp, Matrix.PosDef_inv_iff_PosDef] reduction_step => apply Reduction.rewrite_objFun · intros R hR rewrite [nonsing_inv_nonsing_inv R (hR.1.isUnit_det), Matrix.det_nonsing_inv] rewrite [Real.inverse_eq_inv, Real.log_inv] rfl reduction_step => apply Reduction.rewrite_constraints · intros R rw [and_congr_right_iff] intro hR rw [nonsing_inv_nonsing_inv R hR.isUnit_det] #print covEstimationConvex -- optimization (R : Matrix (Fin n) (Fin n) ℝ) -- minimize -- -(-(N • log (sqrt ((2 * π) ^ n)) + N • (-log (det R) / 2)) + -- -(↑N * trace ((covarianceMatrix fun x => y x) * Rᵀ) / 2)) -- subject to -- c_pos_def : PosDef R -- c_sparse : sum (Matrix.abs R) ≤ α -- We solve the problem for a simple example. @[optimization_param, reducible]
def
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/CovarianceEstimation.lean
covEstimation
null
nₚ : ℕ := 2 @[optimization_param, reducible]
def
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/CovarianceEstimation.lean
nₚ
null
Nₚ : ℕ := 4 @[optimization_param]
def
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/CovarianceEstimation.lean
Nₚ
null
αₚ : ℝ := 1 @[optimization_param]
def
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/CovarianceEstimation.lean
αₚ
null
yₚ : Fin Nₚ → Fin nₚ → ℝ := ![![0, 2], ![2, 0], ![-2, 0], ![0, -2]] solve covEstimationConvex nₚ Nₚ αₚ yₚ #print covEstimationConvex.conicForm -- minimize -- -(-(Nₚ • log (sqrt ((2 * π) ^ nₚ)) + Nₚ • (-Vec.sum t.0 / 2)) + -- -(↑Nₚ * trace ((covarianceMatrix fun i => yₚ i) * Rᵀ) / 2)) -- subject to -- _ : Real.nonnegOrthCone (αₚ - sum T.2) -- _ : Vec.expCone t.0 1 (diag Y.1) -- _ : -- PSDCone -- (let Z := toUpperTri Y.1; -- let D := diagonal (diag Y.1); -- let X := fromBlocks D Z Zᵀ R; -- X) -- _ : Matrix.nonnegOrthCone (T.2 - R) -- _ : Matrix.nonnegOrthCone (T.2 + R) #eval covEstimationConvex.status -- "PRIMAL_AND_DUAL_FEASIBLE" #eval covEstimationConvex.value -- 14.124098 #eval covEstimationConvex.solution -- ![![0.499903, 0.000000], ![0.000000, 0.499905]] -- We recover the optimal solution in the original problem.
def
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/CovarianceEstimation.lean
yₚ
null
Rₚ_opt := red.backward_map nₚ Nₚ αₚ.float yₚ.float covEstimationConvex.solution #eval Rₚ_opt -- !![2.000240, -0.000000; -0.000000, 2.000232]
def
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/CovarianceEstimation.lean
Rₚ_opt
null
leastSquares {n : ℕ} (a : Fin n → ℝ) := optimization (x : ℝ) minimize (∑ i, ((a i - x) ^ 2) : ℝ) @[reducible]
def
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/FittingSphere.lean
leastSquares
null
mean {n : ℕ} (a : Fin n → ℝ) : ℝ := (1 / n) * ∑ i, (a i) /-- It is useful to rewrite the sum of squares in the following way to prove `leastSquares_optimal_eq_mean`, following Marty Cohen's answer in https://math.stackexchange.com/questions/2554243. -/
def
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/FittingSphere.lean
mean
null
leastSquares_alt_objFun {n : ℕ} (hn : 0 < n) (a : Fin n → ℝ) (x : ℝ) : (∑ i, ((a i - x) ^ 2)) = n * ((x - mean a) ^ 2 + (mean (a ^ 2) - (mean a) ^ 2)) := by calc -- 1) Σ (aᵢ - x)² = Σ (aᵢ² - 2aᵢx + x²) _ = ∑ i, ((a i) ^ 2 - 2 * (a i) * x + (x ^ 2)) := by congr; funext i; simp; ring -- 2) ... = Σ aᵢ² - 2xΣ aᵢ + nx² _ = ∑ i, ((a i) ^ 2) - 2 * x * ∑ i, (a i) + n * (x ^ 2) := by rw [sum_add_distrib, sum_sub_distrib, ← sum_mul, ← mul_sum]; simp [sum_const]; ring -- 3) ... = n{a²} - 2xn{a} + nx² _ = n * mean (a ^ 2) - 2 * x * n * mean a + n * (x ^ 2) := by simp [mean]; field_simp; ring -- 4) ... = n((x - {a})² + ({a²} - {a}²)) _ = n * ((x - mean a) ^ 2 + (mean (a ^ 2) - (mean a) ^ 2)) := by simp [mean]; field_simp; ring /-- Key result about least squares: `x* = mean a`. -/
lemma
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/FittingSphere.lean
leastSquares_alt_objFun
/-- It is useful to rewrite the sum of squares in the following way to prove `leastSquares_optimal_eq_mean`, following Marty Cohen's answer in https://math.stackexchange.com/questions/2554243. -/
leastSquares_optimal_eq_mean {n : ℕ} (hn : 0 < n) (a : Fin n → ℝ) (x : ℝ) (h : (leastSquares a).optimal x) : x = mean a := by simp [optimal, feasible, leastSquares] at h replace h : ∀ y, (x - mean a) ^ 2 ≤ (y - mean a) ^ 2 := by intros y have hy := h y have h_rw_x := leastSquares_alt_objFun hn a x have h_rw_y := leastSquares_alt_objFun hn a y simp only [rpow_two] at h_rw_x h_rw_y ⊢ rwa [h_rw_x, h_rw_y, mul_le_mul_left (by positivity), add_le_add_iff_right] at hy have hmean := h (mean a) simp at hmean have h_sq_eq_zero := le_antisymm hmean (sq_nonneg _) rwa [sq_eq_zero_iff, sub_eq_zero] at h_sq_eq_zero
lemma
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/FittingSphere.lean
leastSquares_optimal_eq_mean
/-- Key result about least squares: `x* = mean a`. -/
leastSquaresVec {n : ℕ} (a : Fin n → ℝ) := optimization (x : ℝ) minimize (Vec.sum ((a - Vec.const n x) ^ 2) : ℝ) /-- Same as `leastSquares_optimal_eq_mean` in vector notation. -/
def
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/FittingSphere.lean
leastSquaresVec
null
leastSquaresVec_optimal_eq_mean {n : ℕ} (hn : 0 < n) (a : Fin n → ℝ) (x : ℝ) (h : (leastSquaresVec a).optimal x) : x = mean a := by apply leastSquares_optimal_eq_mean hn a simp [leastSquaresVec, leastSquares, optimal, feasible] at h ⊢ intros y simp only [Vec.sum, Pi.pow_apply, Pi.sub_apply, Vec.const, rpow_two] at h exact h y
lemma
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/FittingSphere.lean
leastSquaresVec_optimal_eq_mean
/-- Same as `leastSquares_optimal_eq_mean` in vector notation. -/
fittingSphere := optimization (c : Fin n → ℝ) (r : ℝ) minimize (∑ i, (‖(x i) - c‖ ^ 2 - r ^ 2) ^ 2 : ℝ) subject to h₁ : 0 ≤ r -- Changes of variables ensuring bijection, which must also add the condition on `E` in the -- equivalence. TODO: Move to `CvxLean` core.
def
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/FittingSphere.lean
fittingSphere
null
ChangeOfVariablesBij {D E} (c : E → D) where c_inv : D → E cond_D : D → Prop cond_E : E → Prop prop_D : ∀ x, cond_D x → c (c_inv x) = x prop_E : ∀ y, cond_E y → c_inv (c y) = y @[equiv]
structure
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/FittingSphere.lean
ChangeOfVariablesBij
null
ChangeOfVariablesBij.toEquivalence {D E R} [Preorder R] {f : D → R} {cs : D → Prop} (c : E → D) (cov : ChangeOfVariablesBij c) (hD : ∀ x, cs x → cov.cond_D x) (hE : ∀ x, cs x → cov.cond_E (cov.c_inv x)) : ⟨f, cs⟩ ≡ ⟨fun y => f (c y), fun y => cs (c y) ∧ cov.cond_E y⟩ := Equivalence.ofStrongEquivalence <| { phi := fun x => cov.c_inv x psi := fun y => c y phi_feasibility := fun x hx => by simp [feasible, cov.prop_D x (hD x hx)]; exact ⟨hx, hE x hx⟩ psi_feasibility := fun y ⟨hy, _⟩ => hy phi_optimality := fun x hx => by simp [cov.prop_D x (hD x hx)] psi_optimality := fun y _ => by simp }
def
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/FittingSphere.lean
ChangeOfVariablesBij.toEquivalence
null
covBij {n} : ChangeOfVariablesBij (fun ((c, t) : (Fin n → ℝ) × ℝ) => (c, sqrt (t + ‖c‖ ^ 2))) := { c_inv := fun (c, r) => (c, r ^ 2 - ‖c‖ ^ 2), cond_D := fun (_, r) => 0 ≤ r, cond_E := fun (c, t) => 0 ≤ t + ‖c‖ ^ 2, prop_D := fun (c, r) h => by simp [sqrt_sq h], prop_E := fun (c, t) h => by simp at h; simp [sq_sqrt h] } equivalence* eqv/fittingSphereT (n m : ℕ) (x : Fin m → Fin n → ℝ) : fittingSphere n m x := by -- Change of variables (bijective) + some clean up. -- TODO: Do this with `change_of_variables` (or a new command `change_of_variables_bij`). equivalence_step => apply ChangeOfVariablesBij.toEquivalence (fun (ct : (Fin n → ℝ) × ℝ) => (ct.1, sqrt (ct.2 + ‖ct.1‖ ^ 2))) covBij · rintro cr h; exact h · rintro ct _; simp [covBij, sq_nonneg] rename_vars [c, t] rename_constrs [h₁, h₂] conv_constr h₁ => dsimp conv_constr h₂ => dsimp [covBij] -- Rewrite objective. rw_obj into (Vec.sum (((Vec.norm x) ^ 2 - 2 * (Matrix.mulVec x c) - Vec.const m t) ^ 2)) => simp [Vec.sum, Vec.norm, Vec.const]; congr; funext i; congr 1; rw [norm_sub_sq (𝕜 := ℝ) (E := Fin n → ℝ), sq_sqrt (rpow_two _ ▸ h₂)] simp [mulVec, inner, dotProduct] -- Remove redundant h₁. remove_constr h₁ => exact sqrt_nonneg _ #print fittingSphereT -- optimization (c : Fin n → ℝ) (t : ℝ) -- minimize Vec.sum ((Vec.norm x ^ 2 - 2 * mulVec x c - Vec.const m t) ^ 2) -- subject to -- h₂ : 0 ≤ t + ‖c‖ ^ 2 -- Next, we proceed to remove the non-convex constraint by arguing that any point that minimizes the -- objective function without the constraint, also satisfies the constraint. We define the problem -- directly, but note that we could also remove the constraint using the `reduction` command.
def
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/FittingSphere.lean
covBij
null
fittingSphereConvex (n m : ℕ) (x : Fin m → Fin n → ℝ) := optimization (c : Fin n → ℝ) (t : ℝ) minimize (Vec.sum ((Vec.norm x ^ 2 - 2 * mulVec x c - Vec.const m t) ^ 2) : ℝ) /-- This tells us that solving the relaxed problem is sufficient (i.e., it is a valid reduction). -/
def
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/FittingSphere.lean
fittingSphereConvex
null
optimal_convex_implies_optimal_t (hm : 0 < m) (c : Fin n → ℝ) (t : ℝ) (h_opt : (fittingSphereConvex n m x).optimal (c, t)) : (fittingSphereT n m x).optimal (c, t) := by simp [fittingSphereT, fittingSphereConvex, optimal, feasible] at h_opt ⊢ constructor -- Feasibility. · let a := Vec.norm x ^ 2 - 2 * mulVec x c have h_ls : optimal (leastSquaresVec a) t := by refine ⟨trivial, ?_⟩ intros y _ simp [objFun, leastSquaresVec] exact h_opt c y -- Apply key result about least squares to `a` and `t`. have h_t_eq := leastSquaresVec_optimal_eq_mean hm a t h_ls have h_c2_eq : ‖c‖ ^ 2 = (1 / m) * ∑ i : Fin m, ‖c‖ ^ 2 := by simp [sum_const] field_simp have h_t_add_c2_eq : t + ‖c‖ ^ 2 = (1 / m) * ∑ i, ‖(x i) - c‖ ^ 2 := by rw [h_t_eq]; dsimp [mean] rw [h_c2_eq, mul_sum, mul_sum, mul_sum, ← sum_add_distrib] congr; funext i; rw [← mul_add] congr; simp [Vec.norm] rw [norm_sub_sq (𝕜 := ℝ) (E := Fin n → ℝ)] simp [a]; congr -- We use the result to establish that `t + ‖c‖ ^ 2` is non-negative. rw [← rpow_two, h_t_add_c2_eq] apply mul_nonneg (by norm_num) apply sum_nonneg intros i _ rw [rpow_two] exact sq_nonneg _ -- Optimality. · intros c' x' _ exact h_opt c' x' /-- We show that we have a reduction via the identity map. -/
lemma
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/FittingSphere.lean
optimal_convex_implies_optimal_t
/-- This tells us that solving the relaxed problem is sufficient (i.e., it is a valid reduction). -/
red (hm : 0 < m) : (fittingSphereT n m x) ≼ (fittingSphereConvex n m x) := { psi := id, psi_optimality := fun (c, t) h_opt => optimal_convex_implies_optimal_t n m x hm c t h_opt } #print fittingSphereConvex -- optimization (c : Fin n → ℝ) (t : ℝ) -- minimize Vec.sum ((Vec.norm x ^ 2 - 2 * mulVec x c - Vec.const m t) ^ 2) -- We proceed to solve the problem on a concrete example. -- https://github.com/cvxgrp/cvxbook_additional_exercises/blob/main/python/sphere_fit_data.py @[optimization_param]
def
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/FittingSphere.lean
red
/-- We show that we have a reduction via the identity map. -/
nₚ := 2 @[optimization_param]
def
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/FittingSphere.lean
nₚ
null
mₚ := 10 @[optimization_param]
def
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/FittingSphere.lean
mₚ
null
xₚ : Fin mₚ → Fin nₚ → ℝ := Matrix.transpose <| ![ ![1.824183228637652032e+00, 1.349093690455489103e+00, 6.966316403935147727e-01, 7.599387854623529392e-01, 2.388321695850912363e+00, 8.651370608981923116e-01, 1.863922545015865406e+00, 7.099743941474848663e-01, 6.005484882320809570e-01, 4.561429569892232472e-01], ![-9.644136284187876385e-01, 1.069547315003422927e+00, 6.733229334437943470e-01, 7.788072961810316164e-01, -9.467465278344706636e-01, -8.591303443863639311e-01, 1.279527420871080956e+00, 5.314829019311283487e-01, 6.975676079749143499e-02, -4.641873429414754559e-01]] -- We use the `solve` command on the data above. solve fittingSphereConvex nₚ mₚ xₚ -- Finally, we recover the solution to the original problem.
def
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/FittingSphere.lean
xₚ
null
sol := eqv.backward_map nₚ mₚ xₚ.float fittingSphereConvex.solution
def
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/FittingSphere.lean
sol
null
cₚ_opt := sol.1
def
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/FittingSphere.lean
cₚ_opt
null
rₚ_opt := sol.2 #eval cₚ_opt -- ![1.664863, 0.031932] #eval rₚ_opt -- 1.159033
def
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/FittingSphere.lean
rₚ_opt
null
hypersonicShapeDesign := optimization (Δx : ℝ) minimize sqrt ((1 / Δx ^ 2) - 1) subject to h₁ : 10e-6 ≤ Δx h₂ : Δx ≤ 1 h₃ : a * (1 / Δx) - (1 - b) * sqrt (1 - Δx ^ 2) ≤ 0 equivalence* eqv₁/hypersonicShapeDesignConvex (a b : ℝ) (ha : 0 ≤ a) (hb₁ : 0 ≤ b) (hb₂ : b < 1) : hypersonicShapeDesign a b := by pre_dcp #print hypersonicShapeDesignConvex -- optimization (Δx : ℝ) -- minimize Δx ^ (-2) - 1 -- subject to -- h₁ : 1 / 100000 ≤ Δx -- h₂ : Δx ≤ 1 -- h₃ : sqrt a ^ 2 / Δx / (1 - b) ≤ sqrt (1 - Δx ^ 2) @[optimization_param]
def
CvxLean
[ "import CvxLean", "import CvxLean.Command.Util.TimeCmd" ]
CvxLean/Examples/HypersonicShapeDesign.lean
hypersonicShapeDesign
null
aₚ : ℝ := 0.05 @[simp high]
def
CvxLean
[ "import CvxLean", "import CvxLean.Command.Util.TimeCmd" ]
CvxLean/Examples/HypersonicShapeDesign.lean
aₚ
null
aₚ_nonneg : 0 ≤ aₚ := by unfold aₚ; norm_num @[optimization_param]
lemma
CvxLean
[ "import CvxLean", "import CvxLean.Command.Util.TimeCmd" ]
CvxLean/Examples/HypersonicShapeDesign.lean
aₚ_nonneg
null
bₚ : ℝ := 0.65
def
CvxLean
[ "import CvxLean", "import CvxLean.Command.Util.TimeCmd" ]
CvxLean/Examples/HypersonicShapeDesign.lean
bₚ
null
bₚ_nonneg : 0 ≤ bₚ := by unfold bₚ; norm_num
lemma
CvxLean
[ "import CvxLean", "import CvxLean.Command.Util.TimeCmd" ]
CvxLean/Examples/HypersonicShapeDesign.lean
bₚ_nonneg
null
bₚ_lt_one : bₚ < 1 := by unfold bₚ; norm_num @[simp high]
lemma
CvxLean
[ "import CvxLean", "import CvxLean.Command.Util.TimeCmd" ]
CvxLean/Examples/HypersonicShapeDesign.lean
bₚ_lt_one
null
one_sub_bₚ_nonneg : 0 ≤ 1 - bₚ := by unfold bₚ; norm_num time_cmd solve hypersonicShapeDesignConvex aₚ bₚ aₚ_nonneg bₚ_nonneg bₚ_lt_one #print hypersonicShapeDesignConvex.conicForm -- Final width of wedge.
lemma
CvxLean
[ "import CvxLean", "import CvxLean.Command.Util.TimeCmd" ]
CvxLean/Examples/HypersonicShapeDesign.lean
one_sub_bₚ_nonneg
null
wₚ_opt := eqv₁.backward_map aₚ.float bₚ.float hypersonicShapeDesignConvex.solution #eval wₚ_opt -- 0.989524 #eval aₚ.float * (1 / wₚ_opt) - (1 - bₚ.float) * Float.sqrt (1 - wₚ_opt ^ 2) ≤ 0 #eval aₚ.float * (1 / wₚ_opt) - (1 - bₚ.float) * Float.sqrt (1 - wₚ_opt ^ 2) ≤ 0.000001 -- Final height of wedge.
def
CvxLean
[ "import CvxLean", "import CvxLean.Command.Util.TimeCmd" ]
CvxLean/Examples/HypersonicShapeDesign.lean
wₚ_opt
null
hₚ_opt := Float.sqrt (1 - wₚ_opt ^ 2) #eval hₚ_opt -- 0.144368 -- Final L/D ratio.
def
CvxLean
[ "import CvxLean", "import CvxLean.Command.Util.TimeCmd" ]
CvxLean/Examples/HypersonicShapeDesign.lean
hₚ_opt
null
ldRatioₚ := 1 / (Float.sqrt ((1 / wₚ_opt ^ 2) - 1)) #eval ldRatioₚ -- 6.854156 -- While the above is good enough, we simplify the problem further by performing a change of -- variables and simplifying appropriately. equivalence* eqv₂/hypersonicShapeDesignSimpler (a b : ℝ) (ha : 0 ≤ a) (hb₁ : 0 ≤ b) (hb₂ : b < 1) : hypersonicShapeDesignConvex a b ha hb₁ hb₂ := by change_of_variables (z) (Δx ↦ sqrt z) conv_constr h₁ => rewrite [le_sqrt' (by norm_num)]; norm_num conv_constr h₂ => rewrite [sqrt_le_iff]; norm_num rw_constr h₃ into (a ^ 2 * z⁻¹ ≤ (1 - b) ^ 2 * (1 - z)) => have hz : 0 ≤ z := by arith have h_one_sub_z : 0 ≤ 1 - z := by arith rw [rpow_two (sqrt a), sq_sqrt ha, rpow_two (sqrt z), sq_sqrt hz] rw [div_le_iff (by arith)] have hlhs : 0 ≤ a / sqrt z := div_nonneg ha (sqrt_nonneg _) have hrhs : 0 ≤ sqrt (1 - z) * (1 - b) := mul_nonneg (sqrt_nonneg _) (by arith) rw [← pow_two_le_pow_two hlhs hrhs] rw [div_rpow ha (sqrt_nonneg _), rpow_two (sqrt z), sq_sqrt hz] rw [mul_rpow (sqrt_nonneg _) (by arith), rpow_two (sqrt (1 - z)), sq_sqrt h_one_sub_z] rw [← mul_one_div, ← inv_eq_one_div, mul_comm (1 - z) _] rename_constrs [h₁, h₂, h₃] rw_obj into (z⁻¹ - 1) => rw [rpow_neg (sqrt_nonneg _), rpow_two (sqrt z), sq_sqrt (by arith)] #print hypersonicShapeDesignSimpler -- optimization (z : ℝ) -- minimize z⁻¹ - 1 -- subject to -- h₁ : 1 / 10000000000 ≤ z -- h₂ : z ≤ 1 -- h₃ : a ^ 2 * z⁻¹ ≤ (1 - b) ^ 2 * (1 - z) time_cmd solve hypersonicShapeDesignSimpler aₚ bₚ aₚ_nonneg bₚ_nonneg bₚ_lt_one #print hypersonicShapeDesignSimpler.conicForm -- Final width of wedge.
def
CvxLean
[ "import CvxLean", "import CvxLean.Command.Util.TimeCmd" ]
CvxLean/Examples/HypersonicShapeDesign.lean
ldRatioₚ
null
wₚ'_opt := eqv₁.backward_map aₚ.float bₚ.float <| eqv₂.backward_map aₚ.float bₚ.float hypersonicShapeDesignSimpler.solution #eval wₚ'_opt -- 0.989524 #eval aₚ.float * (1 / wₚ'_opt) - (1 - bₚ.float) * Float.sqrt (1 - wₚ'_opt ^ 2) ≤ 0 -- Final height of wedge.
def
CvxLean
[ "import CvxLean", "import CvxLean.Command.Util.TimeCmd" ]
CvxLean/Examples/HypersonicShapeDesign.lean
wₚ'_opt
null
hₚ'_opt := Float.sqrt (1 - wₚ'_opt ^ 2) #eval hₚ'_opt -- 0.144371 -- Final L/D ratio.
def
CvxLean
[ "import CvxLean", "import CvxLean.Command.Util.TimeCmd" ]
CvxLean/Examples/HypersonicShapeDesign.lean
hₚ'_opt
null
ldRatioₚ' := 1 / (Float.sqrt ((1 / wₚ'_opt ^ 2) - 1)) #eval ldRatioₚ' -- 6.854031
def
CvxLean
[ "import CvxLean", "import CvxLean.Command.Util.TimeCmd" ]
CvxLean/Examples/HypersonicShapeDesign.lean
ldRatioₚ'
null
trussDesign := optimization (h w r R : ℝ) with A := 2 * π * (R ^ 2 - r ^ 2) minimize 2 * A * sqrt (w ^ 2 + h ^ 2) subject to c_r : 0 < r c_F₁ : F₁ * sqrt (w ^ 2 + h ^ 2) / (2 * h) ≤ σ * A c_F₂ : F₂ * sqrt (w ^ 2 + h ^ 2) / (2 * w) ≤ σ * A c_hmin : hmin ≤ h c_hmax : h ≤ hmax c_wmin : wmin ≤ w c_wmax : w ≤ wmax c_R_lb : 1.1 * r ≤ R c_R_ub : R ≤ Rmax
def
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/TrussDesign.lean
trussDesign
null
hminₚ : ℝ := 1 @[optimization_param]
def
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/TrussDesign.lean
hminₚ
null
hmaxₚ : ℝ := 100 @[simp high]
def
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/TrussDesign.lean
hmaxₚ
null
hminₚ_pos : 0 < hminₚ := by unfold hminₚ; norm_num
lemma
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/TrussDesign.lean
hminₚ_pos
null
hminₚ_le_hmaxₚ : hminₚ ≤ hmaxₚ := by unfold hminₚ hmaxₚ; norm_num @[optimization_param]
lemma
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/TrussDesign.lean
hminₚ_le_hmaxₚ
null
wminₚ : ℝ := 1 @[optimization_param]
def
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/TrussDesign.lean
wminₚ
null
wmaxₚ : ℝ := 100 @[simp high]
def
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/TrussDesign.lean
wmaxₚ
null
wminₚ_pos : 0 < wminₚ := by unfold wminₚ; norm_num
lemma
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/TrussDesign.lean
wminₚ_pos
null
wminₚ_le_wmaxₚ : wminₚ ≤ wmaxₚ := by unfold wminₚ wmaxₚ; norm_num @[optimization_param]
lemma
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/TrussDesign.lean
wminₚ_le_wmaxₚ
null
Rmaxₚ : ℝ := 10 @[simp high]
def
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/TrussDesign.lean
Rmaxₚ
null
Rmaxₚ_pos : 0 < Rmaxₚ := by unfold Rmaxₚ; norm_num @[optimization_param]
lemma
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/TrussDesign.lean
Rmaxₚ_pos
null
σₚ : ℝ := 0.5 @[simp high]
def
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/TrussDesign.lean
σₚ
null
σₚ_pos : 0 < σₚ := by unfold σₚ; norm_num @[optimization_param]
lemma
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/TrussDesign.lean
σₚ_pos
null
F₁ₚ : ℝ := 10 @[simp high]
def
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/TrussDesign.lean
F₁ₚ
null
F₁ₚ_pos : 0 < F₁ₚ := by unfold F₁ₚ; norm_num @[optimization_param]
lemma
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/TrussDesign.lean
F₁ₚ_pos
null
F₂ₚ : ℝ := 20 @[simp high]
def
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/TrussDesign.lean
F₂ₚ
null
F₂ₚ_pos : 0 < F₂ₚ := by unfold F₂ₚ; norm_num solve trussDesignDCP hminₚ hmaxₚ hminₚ_pos hminₚ_le_hmaxₚ wminₚ wmaxₚ wminₚ_pos wminₚ_le_wmaxₚ Rmaxₚ Rmaxₚ_pos σₚ σₚ_pos F₁ₚ F₁ₚ_pos F₂ₚ F₂ₚ_pos -- There are two non-trivial backward maps here, one from `eqv₁` and one from `eqv₂`, so we need to -- apply both of them.
lemma
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/TrussDesign.lean
F₂ₚ_pos
null
eqv₁.backward_mapₚ := eqv₁.backward_map hminₚ.float hmaxₚ.float wminₚ.float wmaxₚ.float Rmaxₚ.float σₚ.float F₁ₚ.float F₂ₚ.float
def
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/TrussDesign.lean
eqv₁.backward_mapₚ
null
eqv₂.backward_mapₚ := eqv₂.backward_map hminₚ.float hmaxₚ.float wminₚ.float wmaxₚ.float Rmaxₚ.float σₚ.float F₁ₚ.float F₂ₚ.float
def
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/TrussDesign.lean
eqv₂.backward_mapₚ
null
sol := eqv₁.backward_mapₚ (eqv₂.backward_mapₚ trussDesignDCP.solution) -- Finally, we obtain the optimal height, width, inner radius, and outer radius.
def
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/TrussDesign.lean
sol
null
hₚ_opt := sol.1
def
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/TrussDesign.lean
hₚ_opt
null
wₚ_opt := sol.2.1
def
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/TrussDesign.lean
wₚ_opt
null
rₚ_opt := sol.2.2.1
def
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/TrussDesign.lean
rₚ_opt
null
Rₚ_opt := sol.2.2.2 -- NOTE: These numbers may differ slighlty depending on the rewrites found by `pre_dcp`. #eval hₚ_opt -- 1.000000 #eval wₚ_opt -- 1.000517 #eval rₚ_opt -- 0.010162 #eval Rₚ_opt -- 2.121443
def
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/TrussDesign.lean
Rₚ_opt
null
valueₚ := let pi := 2 * Float.acos 0; let Aₚ_opt := 2 * pi * (Rₚ_opt ^ 2 - rₚ_opt ^ 2); 2 * Aₚ_opt * Float.sqrt (wₚ_opt ^ 2 + hₚ_opt ^ 2) #eval valueₚ -- 79.999976
def
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/TrussDesign.lean
valueₚ
null
vehSpeedSched [Fact (0 < n)] := optimization (s : Fin n → ℝ) minimize ∑ i, (d i / s i) * F (s i) subject to c_smin : ∀ i, smin i ≤ s i c_smax : ∀ i, s i ≤ smax i c_τmin : ∀ i, τmin i ≤ ∑ j in [[0, i]], d j / s j c_τmax : ∀ i, ∑ j in [[0, i]], d j / s j ≤ τmax i variable {n}
def
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/VehicleSpeedScheduling.lean
vehSpeedSched
null
simp_vec_fraction (h_d_pos : StrongLT 0 d) (s : Fin n → ℝ) (i : Fin n) : d i / (d i / s i) = s i := by have h_di_pos := h_d_pos i; simp at h_di_pos; have h_di_nonzero : d i ≠ 0 := by linarith rw [← div_mul, div_self h_di_nonzero, one_mul]
lemma
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/VehicleSpeedScheduling.lean
simp_vec_fraction
null
fold_partial_sum [hn : Fact (0 < n)] (t : Fin n → ℝ) (i : Fin n) : ∑ j in [[0, i]], t j = Vec.cumsum t i := by simp [Vec.cumsum]; split_ifs · rfl · linarith [hn.out] equivalence* eqv₁/vehSpeedSchedConvex (n : ℕ) (d : Fin n → ℝ) (τmin τmax smin smax : Fin n → ℝ) (F : ℝ → ℝ) (h_n_pos : 0 < n) (h_d_pos : StrongLT 0 d) (h_smin_pos : StrongLT 0 smin) : @vehSpeedSched n d τmin τmax smin smax F ⟨h_n_pos⟩ := by replace h_d_pos : ∀ i, 0 < d i := h_d_pos replace h_smin_pos : ∀ i, 0 < smin i := h_smin_pos haveI : Fact (0 < n) := ⟨h_n_pos⟩ -- Change variables `s ↦ d / t`. -- TODO: This can be done by change of variables by detecting that the variable is a vector. equivalence_step => apply ChangeOfVariables.toEquivalence (fun t => d / t) · rintro s ⟨c_smin, _⟩ i; split_ands <;> linarith [h_smin_pos i, c_smin i, h_d_pos i] rename_vars [t] -- Clean up divisions introduced by the change of variables. conv_obj => simp only [Pi.div_apply, simp_vec_fraction d h_d_pos] conv_constr c_τmin => simp only [Pi.div_apply, simp_vec_fraction d h_d_pos] conv_constr c_τmax => simp only [Pi.div_apply, simp_vec_fraction d h_d_pos] -- Put in matrix form. rw_obj into (Vec.sum (t * (Vec.map F (d / t)))) => simp [Vec.sum]; rfl rw_constr c_smin into (smin ≤ d / t) => rfl rw_constr c_smax into (d / t ≤ smax) => rfl rw_constr c_τmin into (τmin ≤ Vec.cumsum t) => simp [fold_partial_sum t]; rfl rw_constr c_τmax into (Vec.cumsum t ≤ τmax) => simp [fold_partial_sum t]; rfl #print vehSpeedSchedConvex -- optimization (t : Fin n → ℝ) -- minimize Vec.sum (t * Vec.map F (d / t)) -- subject to -- c_smin : smin ≤ d / t -- c_smax : d / t ≤ smax -- c_τmin : τmin ≤ Vec.cumsum t -- c_τmax : Vec.cumsum t ≤ τmax #check eqv₁.backward_map -- The problem is technically in DCP form if `F` is DCP convex. The only issue is that we do not -- have an atom for the perspective function, so the objective function -- `Vec.sum (t * Vec.map F (d / t))` cannot be canonized directly. -- However, if we fix `F`, we can use other atoms. For example, if `F` is quadratic, the problem can -- be canonized. Let `F(s) = a * s^2 + b * s + c` with `0 ≤ a`. equivalence* eqv₂/vehSpeedSchedQuadratic (n : ℕ) (d : Fin n → ℝ) (τmin τmax smin smax : Fin n → ℝ) (a b c : ℝ) (h_n_pos : 0 < n) (h_d_pos : StrongLT 0 d) (h_smin_pos : StrongLT 0 smin) : vehSpeedSchedConvex n d τmin τmax smin smax (fun s => a • s ^ (2 : ℝ) + b • s + c) h_n_pos h_d_pos h_smin_pos := by have t_pos_of_c_smin : ∀ t, smin ≤ d / t → StrongLT 0 t := fun t h i => by have h_di_div_ti_pos := lt_of_lt_of_le (h_smin_pos i) (h i) cases div_pos_iff.mp h_di_div_ti_pos with | inl h_pos => exact h_pos.2 | inr h_neg => have d_pos_i := h_d_pos i; simp at d_pos_i ⊢; linarith [h_neg.1, d_pos_i] -- Add constraint to tell the system that `t` is positive. equivalence_step => apply Equivalence.add_constraint (cs' := fun t => StrongLT 0 t) · rintro t ⟨c_smin, _⟩ i exact t_pos_of_c_smin t c_smin i rename_vars [t] rename_constrs [c_t, c_smin, c_smax, c_τmin, c_τmax] -- Arithmetic simplification in the objective function. rw_obj into (Vec.sum (a • (d ^ (2 : ℝ)) * (1 / t) + b • d + c • t)) => congr; funext i; unfold Vec.map; dsimp have h_ti_pos : 0 < t i := c_t i field_simp; ring -- Rewrite linear constraints. rw_constr c_smin into (smin * t ≤ d) => rw [Vec.le_div_iff c_t] rw_constr c_smax into (d ≤ smax * t) => rw [Vec.div_le_iff c_t] -- Finally, we can apply `dcp`! (or we can call `solve`, as we do below). #print vehSpeedSchedQuadratic -- optimization (t : Fin n → ℝ) -- minimize Vec.sum (a • d ^ 2 * (1 / t) + b • d + c • t) -- subject to -- c_t : StrongLT 0 t -- c_smin : smin * t ≤ d -- c_smax : d ≤ smax * t -- c_τmin : τmin ≤ Vec.cumsum t -- c_τmax : Vec.cumsum t ≤ τmax #check eqv₂.backward_map -- Now, let's solve a concrete instance of the problem: -- https://github.com/cvxgrp/cvxbook_additional_exercises/blob/main/python/veh_speed_sched_data.py @[optimization_param, reducible]
lemma
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/VehicleSpeedScheduling.lean
fold_partial_sum
null
nₚ : ℕ := 10
def
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/VehicleSpeedScheduling.lean
nₚ
null
nₚ_pos : 0 < nₚ := by unfold nₚ; norm_num @[optimization_param, reducible]
lemma
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/VehicleSpeedScheduling.lean
nₚ_pos
null
dₚ : Fin nₚ → ℝ := ![1.9501, 1.2311, 1.6068, 1.4860, 1.8913, 1.7621, 1.4565, 1.0185, 1.8214, 1.4447]
def
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/VehicleSpeedScheduling.lean
dₚ
null
dₚ_pos : StrongLT 0 dₚ := by intro i; fin_cases i <;> (dsimp [dₚ]; norm_num) @[optimization_param, reducible]
lemma
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/VehicleSpeedScheduling.lean
dₚ_pos
null
τminₚ : Fin nₚ → ℝ := ![1.0809, 2.7265, 3.5118, 5.3038, 5.4516, 7.1648, 9.2674, 12.1543, 14.4058, 16.6258] @[optimization_param, reducible]
def
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/VehicleSpeedScheduling.lean
τminₚ
null
τmaxₚ : Fin nₚ → ℝ := ![4.6528, 6.5147, 7.5178, 9.7478, 9.0641, 10.3891, 13.1540, 16.0878, 17.4352, 20.9539] @[optimization_param, reducible]
def
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/VehicleSpeedScheduling.lean
τmaxₚ
null
sminₚ : Fin nₚ → ℝ := ![0.7828, 0.6235, 0.7155, 0.5340, 0.6329, 0.4259, 0.7798, 0.9604, 0.7298, 0.8405] @[optimization_param, reducible]
def
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/VehicleSpeedScheduling.lean
sminₚ
null
smaxₚ : Fin nₚ → ℝ := ![1.9624, 1.6036, 1.6439, 1.5641, 1.7194, 1.9090, 1.3193, 1.3366, 1.9470, 2.8803]
def
CvxLean
[ "import CvxLean" ]
CvxLean/Examples/VehicleSpeedScheduling.lean
smaxₚ
null