Problem trying to get the Gradient and Hessian in Pyomo

252 Views Asked by At

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?

1

There are 1 best solutions below

0
On

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