固定比率确实简化了问题,因为现在有一个线性程序。
你想找到 x1, y1, x2, y2 以最大化 x2 - x1 受限于 (x2 - x1) h = w (y2 - y1) 其中纵横比为 w:h,并且对于每个线性定义凸多边形的不等式,每个点 (x1, y1), (x1, y2), (x2, y1), (x2, y2) 都满足。
例如,考虑这个凸多边形:
四点矩形的线性规划(x_1, y_1), (x_1, y_2), (x_2, y_2) , (x_2, y_1), 纵横比 r = w / h 和上面的多边形内接如下:
理论上,低维线性规划有专门的算法,可以在线性时间内运行。在实践中,您可以使用求解器。如果你想自己编写代码,那么你可以使用单纯形法,但梯度下降更简单。
首先让我们摆脱等式约束和一个变量,通过在 x1 = (x - wz), y1 = (y - hz) 的多边形点约束条件下最大化变量 x, y, z 上的 z, x2 = (x + wz), y2 = (y + hz)。其次,让我们用这些约束换取一个客观的术语。通常,多边形内的点约束看起来像(到半平面的有符号距离)≤ 0。相反,我们将对目标应用惩罚项。设 α > 0 为参数。新项是 -exp(α (到半平面的有符号距离))。如果有符号距离是负数(点在半平面内),那么随着 α 趋于无穷大,惩罚将变为零。如果有符号距离为正,则惩罚为负无穷大。如果我们使α足够大,那么变换后问题的最优解将是近似可行的。
这就是它在 Python 中的样子。我不是持续优化专家,所以请谨慎购买。
# Aspect ratio.
w = 3
h = 2
# Represented as intersection of half-spaces a*x + b*y - c <= 0 given below as
# (a, b, c). For robustness, these should be scaled so that a**2 + b**2 == 1,
# but it's not strictly necessary.
polygon = [(1, 1, 20), (1, -2, 30), (-2, 1, 40)]
# Initial solution -- take the centroid of three hull points. Cheat by just
# using (0, 0) here.
x, y, z = (0, 0, 0)
from math import exp
# Play with these.
alpha = 10
rate = 0.02
for epoch in range(5):
for iteration in range(10 ** epoch, 10 ** (epoch + 1)):
# Compute the gradient of the objective function. Absent penalties, we
# only care about how big the rectangle is, not where.
dx, dy, dz = (0, 0, 1)
# Loop through the polygon boundaries, applying penalties.
for a, b, c in polygon:
for u in [-w, w]:
for v in [-h, h]:
term = -exp(alpha * (a * (x + u * z) + b * (y + v * z) - c))
dx += alpha * a * term
dy += alpha * b * term
dz += alpha * (a * u + b * v) * term
x += rate * dx
y += rate * dy
z += rate * dz
print(x, y, z)