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

标签 python-3.x numpy matplotlib linear-programming

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

5x + 10y <= 10

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

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

我发现的一些方法:

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

    一种更简单的方法可能是让 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$')
    

    enter image description here

    关于python-3.x - 如何在 Numpy/MatplotLib 中可视化线性规划(具有任意不等式)的可行区域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57017444/

    相关文章:

    python - 添加到集合中时,字符串分成单个字符

    python - 将 TFRecords 转换回 JPEG 图像

    python - 为什么 numba 和 numpy 在就地操作上表现不同?

    python - 快速(呃)numpy 花哨的索引和减少?

    python-3.x - 具有自动完成功能的 Kivy TextInput

    multithreading - 从 python3 中的 multiprocess.proccess 更新 tk ProgressBar

    python - 具有嵌套灵活类型(np.void类型)的索引结构numpy数组

    matplotlib - 使用 Python Jupyter Notebook 的弹出图

    python - pyplot twinx() 刻度重叠

    matplotlib - 在 matplotlib 中使用标量可映射的颜色编码