如何在 Numpy/MatplotLib 中可视化线性规划(具有任意不等式)的可行区域?

Art*_*uro 4 numpy matplotlib linear-programming python-3.x

我需要为线性规划问题实现一个求解器。所有的限制都是 <= 的,例如

5x + 10y <= 10

可以有任意数量的这些限制。此外,x>=0 y>=0 隐式。

我需要找到最优解(最大值)并在 matplotlib 中显示可行区域。我通过实施单纯形方法找到了最佳解决方案,但我不知道如何绘制图形。

我发现的一些方法:

  1. 此链接从每个函数中找到 y 点的最小值,并使用 plt.fillBetween() 绘制区域。但是当我改变方程的顺序时它不起作用。我不确定要最小化哪些 y 值()。所以我不能将它用于任意限制。
  2. 找到每对限制的解决方案并绘制一个多边形。效率不高。

Ste*_*ios 8

一种更简单的方法可能是让 matplotlib 自己计算可行区域(您只提供约束),然后简单地将“约束”线叠加在顶部。

# plot the feasible region
d = np.linspace(-2,16,300)
x,y = np.meshgrid(d,d)
plt.imshow( ((y>=2) & (2*y<=25-x) & (4*y>=2*x-8) & (y<=2*x-5)).astype(int) , 
                extent=(x.min(),x.max(),y.min(),y.max()),origin="lower", cmap="Greys", alpha = 0.3);


# plot the lines defining the constraints
x = np.linspace(0, 16, 2000)
# y >= 2
y1 = (x*0) + 2
# 2y <= 25 - x
y2 = (25-x)/2.0
# 4y >= 2x - 8 
y3 = (2*x-8)/4.0
# y <= 2x - 5 
y4 = 2 * x -5

# Make plot
plt.plot(x, 2*np.ones_like(y1))
plt.plot(x, y2, label=r'$2y\leq25-x$')
plt.plot(x, y3, label=r'$4y\geq 2x - 8$')
plt.plot(x, y4, label=r'$y\leq 2x-5$')
plt.xlim(0,16)
plt.ylim(0,11)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.xlabel(r'$x$')
plt.ylabel(r'$y$')
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明