在 mystic 中最小化 f(x) 时用 g(x) 约束 f(x)?

constrain f(x) with g(x) when minimizing f(x) in mystic?

嗨,我是 mystic 的新手,所以如果我问以前已经回答过的类似问题,我深表歉意。

假设我有一个输入 x(长度为 n 的列表),以及一个将输入映射到 m 维输出的函数 f(x) space。我还有一个 m 维约束列表,它也取决于输入 x(比如 g(x)),我想确保输出小于 m 维列表的每个元素的约束。我应该如何在 mystic 中指定它?

简化示例:

x = [1,2,3]
output = [6, 12] # with some f(x)
constraints = [5, 10] # with some g(x)

我是 mystic 的作者。我用另一个函数来约束一个函数的输出的最简单方法是使用惩罚(软约束)。

我将展示一个简单的案例,类似于我认为您正在寻找的案例:

"""
2-D input x
1-D output y = f(x)
where y > g(x)

with f(x) = x0^(sin(x0)) + x1^4 + 6x1^3 - 5x1^2 - 40x1 + 35
and g(x) = 7x1 - x0 + 5
in x = [0,10]
"""

让我们找出大于 g 的 f 的最小值。

>>> import numpy as np
>>> import mystic as my
>>> 
>>> def f(x):
...     x0,x1 = x
...     return x0**np.sin(x0) + x1**4 + 6*x1**3 - 5*x1**2 - 40*x1 + 35
... 
>>> def g(x):
...     x0,x1 = x
...     return 7*x1 - x0 + 5
... 
>>> def penalty(x):
...     return g(x) - f(x)
... 
>>> @my.penalty.quadratic_inequality(penalty, k=1e12)
... def p(x):
...     return 0.0
... 
>>> mon = my.monitors.Monitor()
>>> my.solvers.fmin(f, [5,5], bounds=[(0,10)]*2, penalty=p, itermon=mon, disp=1)
Optimization terminated successfully.
         Current function value: 11.898373
         Iterations: 89
         Function evaluations: 175
STOP("CandidateRelativeTolerance with {'xtol': 0.0001, 'ftol': 0.0001}")
array([7.81765653, 2.10228969])
>>> 
>>> my.log_reader(mon)

绘制图表以可视化受约束的求解器轨迹。

>>> fig = my.model_plotter(f, mon, depth=True, scale=1.0, bounds="0:10, 0:10", out=True)
>>> 
>>> from matplotlib import cm
>>> import matplotlib.pyplot as plt
>>> 
>>> x,y = my.scripts._parse_axes("0:10, 0:10", grid=True)
>>> x, y = np.meshgrid(x, y)
>>> z = 0*x
>>> s,t = x.shape
>>> for i in range(s):
...     for j in range(t):
...         xx,yy = x[i,j], y[i,j]
...         z[i,j] = g([xx,yy])
... 
>>> z = np.log(4*z*1.0+1)+2 # scale=1.0
>>> ax = fig.axes[0]
>>> ax.contour(x, y, z, 50, cmap=cm.cool)
<matplotlib.contour.QuadContourSet object at 0x12bc0d0d0>
>>> plt.show()

从上面的图中,你可以看出求解器开始最小化 f (color=jet),然后点击 g (color=cool),并沿着交点追踪直到它达到了最低值。