笔记
单击此处 下载完整的示例代码
勾勒优化的解空间#
在说明优化问题的解空间时,等值线图特别方便。不仅可以axes.Axes.contour
用来表示目标函数的形貌,还可以用来生成约束函数的边界曲线。可以绘制约束线
TickedStroke
来区分约束边界的有效边和无效边。
axes.Axes.contour
在轮廓左侧生成具有较大值的曲线。角度参数在前面测量为零,向左增加值。因此,当
TickedStroke
用于说明典型优化问题中的约束时,角度应设置在 0 到 180 度之间。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import patheffects
fig, ax = plt.subplots(figsize=(6, 6))
nx = 101
ny = 105
# Set up survey vectors
xvec = np.linspace(0.001, 4.0, nx)
yvec = np.linspace(0.001, 4.0, ny)
# Set up survey matrices. Design disk loading and gear ratio.
x1, x2 = np.meshgrid(xvec, yvec)
# Evaluate some stuff to plot
obj = x1**2 + x2**2 - 2*x1 - 2*x2 + 2
g1 = -(3*x1 + x2 - 5.5)
g2 = -(x1 + 2*x2 - 4.5)
g3 = 0.8 + x1**-3 - x2
cntr = ax.contour(x1, x2, obj, [0.01, 0.1, 0.5, 1, 2, 4, 8, 16],
colors='black')
ax.clabel(cntr, fmt="%2.1f", use_clabeltext=True)
cg1 = ax.contour(x1, x2, g1, [0], colors='sandybrown')
plt.setp(cg1.collections,
path_effects=[patheffects.withTickedStroke(angle=135)])
cg2 = ax.contour(x1, x2, g2, [0], colors='orangered')
plt.setp(cg2.collections,
path_effects=[patheffects.withTickedStroke(angle=60, length=2)])
cg3 = ax.contour(x1, x2, g3, [0], colors='mediumblue')
plt.setp(cg3.collections,
path_effects=[patheffects.withTickedStroke(spacing=7)])
ax.set_xlim(0, 4)
ax.set_ylim(0, 4)
plt.show()