如何在Scipy SLSQP中定义大于但不等于零的约束

2024-09-26 18:04:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图最大化形式为x1/x2的函数。我不希望x2变为零,所以我将约束定义为x2 > 0。但是Scipy-SLSQP方法没有考虑到这一点,而是说'Inequality constraints incompatible。Scipy文档说明所有约束都是非负的,我如何只接受大于零的值

编辑:这是我必须最小化的函数

def f(x): 
    T = x[0]
    mdot = x[1]
    Pin = 1.5 # Input power in watts
    f = -(T**2/(2*mdot*Pin))
    return f

我对x2的约束>;0:

def constraint1(x): ## mdot > 0
    return x[1]
cons1 = {'type':'ineq', 'fun': constraint1}
res = minimize(f,[0.5,0.025],method = 'SLSQP',constraints = cons1,callback=callbackF)

回调函数仅用于在每次迭代时获取x个值

结果是:

Iter    X1          X2         f(X)     
   1    0.520000    0.000000    19484373451061.960938
   2    0.520000    0.000000    19484373451061.960938
Maximum thrust value is 0.5200000003096648
Ideal mass flow rate value is 6.938893903907228e-18
     fun: -19484373451061.96
     jac: array([-7.49398988e+13,  1.30757417e+21])
 message: 'Inequality constraints incompatible'
    nfev: 6
     nit: 2
    njev: 2
  status: 4
 success: False
       x: array([5.2000000e-01, 6.9388939e-18])

正如您所看到的,mdot(x2)立即变为零,我不知道如何修复它


Tags: 函数returnvaluedefpinscipyx2constraints
1条回答
网友
1楼 · 发布于 2024-09-26 18:04:10

如果我们用边界替换约束,我们可以看到:

from scipy.optimize import minimize

def f(x): 
    T = x[0]
    mdot = x[1]
    Pin = 1.5 # Input power in watts
    f = -(T**2/(2*mdot*Pin))
    return f

res = minimize(f,[0.5,0.025],method = 'l-bfgs-b',bounds=[(0,10000),(0.0001,15)])
res

      fun: -333333333333.3333
 hess_inv: <2x2 LbfgsInvHessProduct with dtype=float64>
      jac: array([-6.66687012e+07,  3.33300003e+15])
  message: b'CONVERGENCE: NORM_OF_PROJECTED_GRADIENT_<=_PGTOL'
     nfev: 9
      nit: 2
   status: 0
  success: True
        x: array([1.e+04, 1.e-04])

这与人们所期望的相符(这个问题可以用手工简单地解决)

相关问题 更多 >

    热门问题