在pyomo中如何从目标函数中提取二阶导数 [英] In pyomo how can one extract the second derivative from the objective function

查看:55
本文介绍了在pyomo中如何从目标函数中提取二阶导数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 pyomo 并且已经定义了一个模型,并带有一个目标函数.模型求解后,目标函数附加了一定的参数.所以如果我有一个多索引变量 [x1, x2, x3],我的二次目标函数会假设看起来像这样:(x1^2 + 13*x2^2 + 10*x3^2) + (2*x1 +......) .

I'm working with pyomo and already have a model defined, with an objective function to go with it. After the model is solved, the objective function has certain parameters attached to it. So if i had a multi index variable [x1, x2, x3], my quadratic objective function would suppose look something like this: (x1^2 + 13*x2^2 + 10*x3^2) + (2*x1 +......) .

我的问题是:鉴于我实际上可以从目标以字符串格式访问这个表达式,有没有办法获得这个函数关于所有变量的二阶导数?

My question is: given that i can actually access this expression in string format from the objective, is there any way to obtain the second derivative of this function with respect to all the variables?

推荐答案

Pyomo 中有两种获取派生信息的方法.

There are two ways to get derivative information in Pyomo.

如果您需要单点数值导数,您可以使用类似gjh_asl_json"工具的工具(https://github.com/ghackebeil/gjh_asl_json),它可以采用 Pyomo 生成的 NL 文件,并生成带有 Jacobian 和 Hessian 信息的 JSON 文件.

If you need numeric derivatives at a single point, you can use a tool like the "gjh_asl_json" tool (https://github.com/ghackebeil/gjh_asl_json) that can take an NL file generated by Pyomo and produces a JSON file with the Jacobian and Hessian information.

如果你想要符号导数,Pyomo 可以直接提供,前提是你还安装了 sympy:

If you want symbolic derivatives, Pyomo can provide those directly, provided you also have sympy installed:

from pyomo.core.base.symbolic import differentiate
from pyomo.core.base.expr import identify_variables
# assuming model.objective is your Objective component
varList = list( identify_variables(model.objective.expr) )
firstDerivs = differentiate(model.objective.expr, wrt_list=varList)
# Note this calculates d^2/dx_i^2; if you want the full Hessian matrix
#   ( \delta^2/{\delta x_i \delta x_j} ) replace "wrt=v" with "wrt_list=varList"
secondDerivs = [ differentiate(firstDerivs[i], wrt=v) for i,v in enumerate(varList) ]

当然,鉴于您的表达式是二次的,符号微分和数值微分都会给您相同的答案.

Of course, given that your expression is quadratic, symbolic and numeric differentiation will both give you the same answer.

这篇关于在pyomo中如何从目标函数中提取二阶导数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆