我希望在使用Python Gekko时,在优化过程的每一次迭代中获得变量的值.

例如,文档(https://gekko.readthedocs.io/en/latest/quick_start.html#example)中的以下代码解决了问题HS71:

from gekko import GEKKO
import numpy as np

m = GEKKO(remote=False)
x = m.Array(m.Var, 4, value=1, lb=1, ub=5)
x1, x2, x3, x4 = x                     # rename variables
x2.value = 5; x3.value = 5             # change guess
m.Equation(np.prod(x) >= 25)           # prod>=25
m.Equation(m.sum([xi**2 for xi in x]) == 40)  # sum=40
m.Minimize(x1*x4*(x1 + x2 + x3) + x3)  # objective
m.solve()
print(x, m.options.OBJFCNVAL)

控制台中显示的输出如下:

 ----------------------------------------------------------------
 APMonitor, Version 1.0.0
 APMonitor Optimization Suite
 ----------------------------------------------------------------
 
 
 --------- APM Model Size ------------
 Each time step contains
   Objects      :  1
   Constants    :  0
   Variables    :  10
   Intermediates:  0
   Connections  :  5
   Equations    :  7
   Residuals    :  7
 
 Number of state variables:    10
 Number of total equations: -  7
 Number of slack variables: -  1
 ---------------------------------------
 Degrees of freedom       :    2
 
 **********************************************
 Steady State Optimization with Interior Point Solver
 **********************************************
  
  
 Info: Exact Hessian
******************************************************************************
This program contains Ipopt, a library for large-scale nonlinear optimization.
 Ipopt is released as open source code under the Eclipse Public License (EPL).
         For more information visit http://projects.coin-or.org/Ipopt
******************************************************************************
This is Ipopt version 3.10.2, running with linear solver mumps.
Number of nonzeros in equality constraint Jacobian...:       19
Number of nonzeros in inequality constraint Jacobian.:        0
Number of nonzeros in Lagrangian Hessian.............:       10
Total number of variables............................:       10
                     variables with only lower bounds:        1
                variables with lower and upper bounds:        4
                     variables with only upper bounds:        0
Total number of equality constraints.................:        7
Total number of inequality constraints...............:        0
        inequality constraints with only lower bounds:        0
   inequality constraints with lower and upper bounds:        0
        inequality constraints with only upper bounds:        0
iter    objective    inf_pr   inf_du lg(mu)  ||d||  lg(rg) alpha_du alpha_pr  ls
   0 1.6109693e+001 4.00e+001 5.24e-001   0.0 0.00e+000    -  0.00e+000 0.00e+000   0
   1 1.6896037e+001 7.28e-001 7.82e-001  -0.9 4.00e+001    -  1.00e+000 1.00e+000h  1
   2 1.7121828e+001 1.66e-001 6.51e-001  -1.1 2.15e+000    -  8.23e-001 1.00e+000h  1
   3 1.6954231e+001 1.60e-001 6.46e-002  -2.1 6.34e-001    -  1.00e+000 1.00e+000h  1
   4 1.7008327e+001 1.68e-002 1.22e-002  -2.9 3.39e-001    -  9.94e-001 1.00e+000h  1
   5 1.7013921e+001 3.15e-004 1.47e-004  -4.6 3.56e-002    -  1.00e+000 1.00e+000h  1
   6 1.7014017e+001 2.51e-007 4.50e-007 -10.5 5.56e-004    -  9.99e-001 1.00e+000h  1
Number of Iterations....: 6
                                   (scaled)                 (unscaled)
Objective...............:  1.7014017181012623e+001   1.7014017181012623e+001
Dual infeasibility......:  4.5045555432827566e-007   4.5045555432827566e-007
Constraint violation....:  2.5086595754315365e-007   2.5086595754315365e-007
Complementarity.........:  4.8294565936715572e-008   4.8294565936715572e-008
Overall NLP error.......:  4.5045555432827566e-007   4.5045555432827566e-007
Number of objective function evaluations             = 7
Number of objective gradient evaluations             = 7
Number of equality constraint evaluations            = 7
Number of inequality constraint evaluations          = 0
Number of equality constraint Jacobian evaluations   = 7
Number of inequality constraint Jacobian evaluations = 0
Number of Lagrangian Hessian evaluations             = 6
Total CPU secs in IPOPT (w/o function evaluations)   =      0.014
Total CPU secs in NLP function evaluations           =      0.000
EXIT: Optimal Solution Found.
 The solution was found.
 The final value of the objective function is  17.014017181012623
 
 ---------------------------------------------------
 Solver         :  IPOPT (v3.12)
 Solution time  :  0.021100000000000008 sec
 Objective      :  17.014017181012623
 Successful solution
 ---------------------------------------------------
 
[[1.0000000339] [4.7429996271] [3.8211500196] [1.3794082228]] 17.014017181

这包括目标函数在每次迭代时的值,但我还希望在每次迭代时获得变量(x)的值.

推荐答案

解算器没有对Python的回调.获取每次迭代的值的一种方法是多次调用求解器,限制为max_iter(最大迭代次数),并报告值,直到求解器成功为止.使用debug=0不会对不成功的解决方案引发异常.

from gekko import GEKKO
import numpy as np

max_iter = 0
while True:
    m = GEKKO(remote=False)
    x = m.Array(m.Var, 4, value=1, lb=1, ub=5)
    x1, x2, x3, x4 = x                     # rename variables
    x2.value = 5; x3.value = 5             # change guess
    m.Equation(np.prod(x) >= 25)           # prod>=25
    m.Equation(m.sum([xi**2 for xi in x]) == 40)  # sum=40
    m.Minimize(x1*x4*(x1 + x2 + x3) + x3)  # objective
    m.options.MAX_ITER = max_iter
    m.solve(disp=False,debug=0)
    print(max_iter,x, m.options.OBJFCNVAL)
    if m.options.APPSTATUS==1:
        # break loop with successful solution
        break
    else:
        # increment maximum iterations
        max_iter += 1

以下是迭代数、变量值x和目标函数值的迭代摘要.目标函数可能会变得更差(更高),因为方程还不满足,解可能不可行.

0 [[1.00999999] [4.960000049] [4.960000049] [1.00999999]] 16.109692918
1 [[1.1256700056] [4.4664784656] [4.2706611878] [1.1371887857]] 16.896036995
2 [[1.1003048073] [4.6596383632] [3.9630056459] [1.2300025937]] 17.121828401
3 [[1.0211678027] [4.7139849665] [3.8710712025] [1.3337143994]] 16.954231463
4 [[1.0027660895] [4.740529129] [3.8261434464] [1.3737295983]] 17.008327097
5 [[1.0000616664] [4.7429670916] [3.8212258627] [1.3792900699]] 17.013920783
6 [[1.0000000339] [4.7429996271] [3.8211500196] [1.3794082228]] 17.014017181

如果您有一个不想多次重新定义的大型模型,那么只需将m.solve()函数与m.options.COLDSTART=1一起循环即可.

from gekko import GEKKO
import numpy as np

m = GEKKO(remote=False)
x = m.Array(m.Var, 4, value=1, lb=1, ub=5)
x1, x2, x3, x4 = x                     # rename variables
x2.value = 5; x3.value = 5             # change guess
m.Equation(np.prod(x) >= 25)           # prod>=25
m.Equation(m.sum([xi**2 for xi in x]) == 40)  # sum=40
m.Minimize(x1*x4*(x1 + x2 + x3) + x3)  # objective

max_iter = 0
while True:
    m.options.MAX_ITER = max_iter
    m.options.COLDSTART=1
    m.solve(disp=False,debug=0)
    print(max_iter,x, m.options.OBJFCNVAL)
    if m.options.APPSTATUS==1:
        # break loop with successful solution
        break
    else:
        # increment maximum iterations
        max_iter += 1

Python相关问答推荐

如何判断LazyFrame是否为空?

在两极中实施频率编码

Tkinter -控制调色板的位置

绘制系列时如何反转轴?

无法导入已安装的模块

这家einsum运营在做什么?E = NP.einsum(aj,kl-il,A,B)

在编写要Excel的数据透视框架时修复标题行

Python panda拆分列保持连续多行

比较两个二元组列表,NP.isin

线性模型PanelOLS和statmodels OLS之间的区别

在Python中管理打开对话框

为什么抓取的HTML与浏览器判断的元素不同?

不允许访问非IPM文件夹

python中的解释会在后台调用函数吗?

如何从需要点击/切换的网页中提取表格?

如何使用两个关键函数来排序一个多索引框架?

使用Openpyxl从Excel中的折线图更改图表样式

当单元测试失败时,是否有一个惯例会抛出许多类似的错误消息?

BeautifulSoup:超过24个字符(从a到z)的迭代失败:降低了首次深入了解数据集的复杂性:

根据客户端是否正在传输响应来更改基于Flask的API的行为