简体   繁体   中英

Problem trying to get the Gradient and Hessian in Pyomo

I got a large-scale problem and I want to know the gradient and the Hessian of the objective function and some constraints. I saw here how to obtain the symbolic derivatives.

But using this simple code:

> from pyomo.environ import * 
> mc = ConcreteModel()
> mc.X1 = Var() 
> mc.X2 = Var()
> mc.objectiv = Objective(expr = mc.X1**3 + mc.X2**2)
> from pyomo.core.base.symbolic import differentiate 
> from > pyomo.core.base.expr import identify_variables
> varList = list( identify_variables(mc.objectiv.expr) )
> firstDerivs = differentiate(mc.objectiv.expr, wrt_list=varList)
> secondDerivs = [ differentiate(firstDerivs[i], wrt=v) for i,v in enumerate(varList) ]

Pyomo gives me:

> firstDerivs 
[<pyomo.core.kernel.expr_coopr3._ProductExpression at 0x2bf06eada20>,  <pyomo.core.kernel.expr_coopr3._ProductExpression at 0x2bf06eada68>]
> secondDerivs
[<pyomo.core.kernel.expr_coopr3._ProductExpression at 0x2bf070b3af8>, 2.0]

How can I get the symbolic equations and evaluate them?

firstDerivs and secondDerivs are iterable, they contain elements, which are your symbolic equations

you can view the equations using this:

[print(item) for item in firstDerivs]
print(30*'-')
[print(item) for item in secondDerivs]

this will print out each first order derivative on its' own line and the second order ones in the same way

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM