如何为differential_evolution添加几个约束?

时间:2017-11-18 18:07:10

标签: python optimization scipy eval differential-evolution

我遇到与this question相同的问题,但不想只为优化问题添加一个但只有几个约束。

所以,例如我希望最大化x1 + 5 * x2,其约束条件是x1x2之和小于5x2小于3(毋庸置疑,实际问题要复杂得多,不能像scipy.optimize.minimize一样投入到这个问题中;它只是用来说明问题......)。

我可以像这样丑陋的黑客:

from scipy.optimize import differential_evolution
import numpy as np

def simple_test(x, more_constraints):

    # check wether all constraints evaluate to True
    if all(map(eval, more_constraints)):

        return -1 * (x[0] + 5 * x[1])

    # if not all constraints evaluate to True, return a positive number
    return 10

bounds = [(0., 5.), (0., 5.)]

additional_constraints = ['x[0] + x[1] <= 5.', 'x[1] <= 3']
result = differential_evolution(simple_test, bounds, args=(additional_constraints, ), tol=1e-6)
print(result.x, result.fun, sum(result.x))

这将打印

[ 1.99999986  3.        ] -16.9999998396 4.99999985882
人们期待的是

是否有更好/更直接的方法来添加几个约束而不是使用相当“危险”的eval

1 个答案:

答案 0 :(得分:2)

一个例子就像这样::

additional_constraints = [lambda(x): x[0] + x[1] <= 5., lambda(x):x[1] <= 3]

def simple_test(x, more_constraints):

    # check wether all constraints evaluate to True
    if all(constraint(x) for constraint in more_constraints):

        return -1 * (x[0] + 5 * x[1])

    # if not all constraints evaluate to True, return a positive number
    return 10