且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

scipy.optimize.minimize(COBYLA和SLSQP)忽略在for循环中启动的约束

更新时间:2022-12-01 13:58:08

我不太了解Python,但我知道如何解决您的问题.在您的第一个代码段中,const函数使用对t本身的引用(因为内部函数与外部共享作用域),因此产生了等同于:

I don't really know Python, but i know how to solve your problem. In your first snippet const function uses reference to t itself (because inner function shares scope with outer), thus producing equivalent of:

cons[0] = {'type':'ineq', 'fun': lambda x: x[t]}
cons[1] = {'type':'ineq', 'fun': lambda x: x[t]} 
cons[2] = {'type':'ineq', 'fun': lambda x: x[t]} 
cons[3] = {'type':'ineq', 'fun': lambda x: x[t]}

这是错误的.这可以通过使用咖喱来解决:

which is wrong. This could be fixed by using curry:

import numpy as np
from scipy.optimize import minimize

def function(x):
    return -1*(18*x[0]+16*x[1]+12*x[2]+11*x[3])

I=np.array((20,50,50,80))
x0=I

cons=[]
steadystate={'type':'eq', 'fun': lambda x: x.sum()-I.sum() }
cons.append(steadystate)

def f(a):
    def g(x):
        return x[a]
    return g

for t in range (4):
    cons.append({'type':'ineq', 'fun': f(t)})

out=minimize(function, x0, method="SLSQP", constraints=cons)
x=out["x"]

在幕后,此方法创建了对t所保存的值的新引用(当您将其作为f的参数传递时),并将该引用存储在g中使用,现在生成了一系列正确的函数.

Under the curtains, this approach creates a new reference to value held by t (when you pass it as argument to f) and stores this reference for use in g, now generating series of correct functions.