为什么scipy.minimize忽略了我的约束?

时间:2016-11-22 22:54:48

标签: python numpy scipy

我有一个约束优化问题,我试图使用scipy.optimize.minimize来解决。

基本上,我将一个参数 f 拟合到具有约束的ODE系统: f > 0和

˚F * 1000℃; 500

我在下面写了一个MWE。在这个简单的情况下,很明显0 < f <0.5,但在我的实际问题中,a-priori上限并不明显,因此不等式约束。

from __future__ import division
import numpy as np
from scipy.integrate import odeint
from scipy.optimize import minimize

def myeqs(y,t,beta, gamma,N):
    dy0 = -(beta/N)*y[0]*y[1]
    dy1 = (beta/N)*y[0]*y[1] - gamma*y[1]
    dy2 = gamma*y[1]

    return [dy0,dy1,dy2]

def runModel(f, extraParams):
    [beta, gamma, N, initCond, time]= extraParams
    S0 = (1-f)*initCond[0]
    I0 = initCond[1]
    R0 = f*initCond[0]
    tspan = np.linspace(time[0], time[1], int(time[1] - time[0]))
    sol = odeint(myeqs, [S0,I0,R0], tspan, args=(beta, gamma, N))
    return sol

y0 = [1000, 1, 0]
extraParams = [0.5, 0.25, 1000, y0, [0,150]]


def computeSimple(f, extraParams):
   sol = runModel(f, extraParams)
   return np.abs((sol[-1,2] - sol[0,2]))


def c1(f):
    return f*1000.0 - 500.0


cons = ({'type': 'ineq', 'fun': c1})

#cons = ({'type': 'ineq',
 #  'fun': lambda x: x[0]*1000 - 500}, )

res = minimize(computeSimple, 0.2, args=(extraParams, ), method='SLSQP',       bounds=((0,1.5), ), constraints=cons)
print res.x

print c1(res.x)

如果你运行它,你会看到res.x始终是边界的上限,无论约束如何...... 我的错误在哪里? 提前谢谢

1 个答案:

答案 0 :(得分:2)

你的约束落后了。这个约束:

def c1(f):
    return f*1000.0 - 500.0

f限制为至少 0.5,而不是最多0.5