我需要实现一个线性规划问题的求解器。所有限制都是 <= ones such as
5x + 10y <= 10
这些限制可以是任意数量的。另外,x>=0 y>=0 隐含地。
我需要找到最优解(max)并在 matplotlib 中显示可行区域。我通过实现单纯形法找到了最佳解决方案,但我不知道如何绘制图形。
我发现的一些方法:
一种更简单的方法可能是让 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$')
我创建了一个 Jupyter 笔记本示例,其中包含从
ipywidgets
导入的 UI 滑块,允许用户尝试各种“假设”场景。 https://github.com/jbonfardeci/linear-optimization/blob/main/example.ipynb