Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/maven/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 解线性不等式_Python_Numpy_Matplotlib_Inequalities - Fatal编程技术网

Python 解线性不等式

Python 解线性不等式,python,numpy,matplotlib,inequalities,Python,Numpy,Matplotlib,Inequalities,我想解一个不等式组,它似乎是你所需要的超集。这应该很容易处理线性不等式 更新 我又在考虑这个问题,我想我会尝试看看没有fillplots可以做什么,只要使用标准库,比如scipy和numpy 在这样一个不等式系统中,每个方程定义了一个半空间。该系统是所有这些半空间的交集,是一个凸集 查找该集合的顶点(例如,绘制顶点)称为。幸运的是,有强大的算法来处理凸包,计算n维的半空间交点(以及做许多其他奇妙的事情)。示例实现是 更幸运的是,我们可以通过scipy.spacial直接访问该库的各个方面,特别是

我想解一个不等式组,它似乎是你所需要的超集。这应该很容易处理线性不等式

更新

我又在考虑这个问题,我想我会尝试看看没有
fillplots
可以做什么,只要使用标准库,比如
scipy
numpy

在这样一个不等式系统中,每个方程定义了一个半空间。该系统是所有这些半空间的交集,是一个凸集

查找该集合的顶点(例如,绘制顶点)称为。幸运的是,有强大的算法来处理凸包,计算n维的半空间交点(以及做许多其他奇妙的事情)。示例实现是

更幸运的是,我们可以通过
scipy.spacial
直接访问该库的各个方面,特别是:和

在以下方面:

  • 我们找到了一个合适的可行点,即
    半空间相交所需的
    内点

  • 为了避免凸集打开时出现警告(以及结果中的
    Inf
    nan
    ),我们扩充了原始系统
    Ax有一个优秀的库pypoman,它解决了顶点枚举问题,可以帮助您解决问题,但不幸的是它只输出集合的顶点,不是视觉化。顶点可能无序,如果没有其他操作,可视化将不正确。为了克服这个问题,您可以使用这个站点的算法(Graham scan或algo Jarvis)

    下面是一个示例代码:

    import pypoman
    import cdd
    import matplotlib.pyplot as plt
    
    
    def grahamscan(A):
        def rotate(A,B,C):
            return (B[0]-A[0])*(C[1]-B[1])-(B[1]-A[1])*(C[0]-B[0])
    
        n = len(A) 
        if len(A) == 0:
            return A
    
        P = np.arange(n)
        for i in range(1,n):
            if A[P[i]][0]<A[P[0]][0]: 
                P[i], P[0] = P[0], P[i] 
        for i in range(2,n): 
            j = i
            while j>1 and (rotate(A[P[0]],A[P[j-1]],A[P[j]])<0):
                P[j], P[j-1] = P[j-1], P[j]
                j -= 1
        S = [P[0],P[1]] 
        for i in range(2,n):
            while rotate(A[S[-2]],A[S[-1]],A[P[i]])<0:
                del S[-1] 
            S.append(P[i])
        return S
    
    def compute_poly_vertices(A, b):
        b = b.reshape((b.shape[0], 1))
        mat = cdd.Matrix(np.hstack([b, -A]), number_type='float')
        mat.rep_type = cdd.RepType.INEQUALITY
        P = cdd.Polyhedron(mat)
        g = P.get_generators()
        V = np.array(g)
        vertices = []
        for i in range(V.shape[0]):
            if V[i, 0] != 1: continue
            if i not in g.lin_set:
                vertices.append(V[i, 1:])
        return vertices
    
    
    A = np.array([[-1, 1],
                  [0, 1],
                  [0.5, 1],
                  [1.5, 1],
                  [-1, 0],
                  [0, -1]])
    b = np.array([1, 2, 3, 6, 0, 0])
    
    vertices = np.array(compute_poly_vertices(A, b))
    print(vertices)
    vertices = np.array(vertices[grahamscan(vertices)])
    
    x, y = vertices[:, 0], vertices[:, 1]
    
    fig=plt.figure(figsize=(15,15))
    ax = fig.add_subplot(111, title="Solution")
    
    ax.fill(x, y, linestyle = '-', linewidth = 1, color='gray', alpha=0.5)
    ax.scatter(x, y, s=10, color='black', alpha=1)
    

    我对我最初的答案做了很多扩展。。。看看,嗯。。。不完全是我想要的,因为在片场上仍然有很多线要建,但已经有了进展!)谢谢你说的“台词”是什么意思?您可以只绘制凸包,而这只是红色多边形,没有与不等式对应的线。换句话说,如果您不想可视化这些线,可以删除
    plot\u不等式的最后两行。我把它们标出来是为了演示,我会想办法的。你的回答真的帮了我大忙,谢谢!!!)我修改了代码:只需使用
    plot\u凸集()。你在哪里使用了皮波曼图书馆?你的函数lineqs(-A,-b)也给出了正确的结果,我从库本身获取了compute_poly_顶点函数,并对其进行了一些修改。你可以在GitHub上查找,在那里很容易找到。我希望你的问题解决了
    
    import matplotlib.pyplot as plt
    
    import numpy as np
    from scipy.spatial import HalfspaceIntersection, ConvexHull
    from scipy.optimize import linprog
    
    def feasible_point(A, b):
        # finds the center of the largest sphere fitting in the convex hull
        norm_vector = np.linalg.norm(A, axis=1)
        A_ = np.hstack((A, norm_vector[:, None]))
        b_ = b[:, None]
        c = np.zeros((A.shape[1] + 1,))
        c[-1] = -1
        res = linprog(c, A_ub=A_, b_ub=b[:, None], bounds=(None, None))
        return res.x[:-1]
    
    def hs_intersection(A, b):
        interior_point = feasible_point(A, b)
        halfspaces = np.hstack((A, -b[:, None]))
        hs = HalfspaceIntersection(halfspaces, interior_point)
        return hs
    
    def plt_halfspace(a, b, bbox, ax):
        if a[1] == 0:
            ax.axvline(b / a[0])
        else:
            x = np.linspace(bbox[0][0], bbox[0][1], 100)
            ax.plot(x, (b - a[0]*x) / a[1])
    
    def add_bbox(A, b, xrange, yrange):
        A = np.vstack((A, [
            [-1,  0],
            [ 1,  0],
            [ 0, -1],
            [ 0,  1],
        ]))
        b = np.hstack((b, [-xrange[0], xrange[1], -yrange[0], yrange[1]]))
        return A, b
    
    def solve_convex_set(A, b, bbox, ax=None):
        A_, b_ = add_bbox(A, b, *bbox)
        interior_point = feasible_point(A_, b_)
        hs = hs_intersection(A_, b_)
        points = hs.intersections
        hull = ConvexHull(points)
        return points[hull.vertices], interior_point, hs
    
    def plot_convex_set(A, b, bbox, ax=None):
        # solve and plot just the convex set (no lines for the inequations)
        points, interior_point, hs = solve_convex_set(A, b, bbox, ax=ax)
        if ax is None:
            _, ax = plt.subplots()
        ax.set_aspect('equal')
        ax.set_xlim(bbox[0])
        ax.set_ylim(bbox[1])
        ax.fill(points[:, 0], points[:, 1], 'r')
        return points, interior_point, hs
    
    def plot_inequalities(A, b, bbox, ax=None):
        # solve and plot the convex set,
        # the inequation lines, and
        # the interior point that was used for the halfspace intersections
        points, interior_point, hs = plot_convex_set(A, b, bbox, ax=ax)
        ax.plot(*interior_point, 'o')
        for a_k, b_k in zip(A, b):
            plt_halfspace(a_k, b_k, bbox, ax)
        return points, interior_point, hs
    
    plt.rcParams['figure.figsize'] = (6, 3)
    
    A = np.array([[-1, 1],
              [0, 1],
              [0.5, 1],
              [1.5, 1],
              [-1, 0],
              [0, -1]])
    b = np.array([1, 2, 3, 6, 0, 0])
    
    bbox = [(-1, 5), (-1, 4)]
    fig, ax = plt.subplots(ncols=2)
    plot_convex_set(A, b, bbox, ax=ax[0])
    plot_inequalities(A, b, bbox, ax=ax[1]);
    
    A = np.array([
        [-1, 1],
        [0, 1],
        [-1, 0],
        [0, -1],
    ])
    b = np.array([1, 2, 0, 0])
    
    fig, ax = plt.subplots(ncols=2)
    plot_convex_set(A, b, bbox, ax=ax[0])
    plot_inequalities(A, b, bbox, ax=ax[1]);
    
    import pypoman
    import cdd
    import matplotlib.pyplot as plt
    
    
    def grahamscan(A):
        def rotate(A,B,C):
            return (B[0]-A[0])*(C[1]-B[1])-(B[1]-A[1])*(C[0]-B[0])
    
        n = len(A) 
        if len(A) == 0:
            return A
    
        P = np.arange(n)
        for i in range(1,n):
            if A[P[i]][0]<A[P[0]][0]: 
                P[i], P[0] = P[0], P[i] 
        for i in range(2,n): 
            j = i
            while j>1 and (rotate(A[P[0]],A[P[j-1]],A[P[j]])<0):
                P[j], P[j-1] = P[j-1], P[j]
                j -= 1
        S = [P[0],P[1]] 
        for i in range(2,n):
            while rotate(A[S[-2]],A[S[-1]],A[P[i]])<0:
                del S[-1] 
            S.append(P[i])
        return S
    
    def compute_poly_vertices(A, b):
        b = b.reshape((b.shape[0], 1))
        mat = cdd.Matrix(np.hstack([b, -A]), number_type='float')
        mat.rep_type = cdd.RepType.INEQUALITY
        P = cdd.Polyhedron(mat)
        g = P.get_generators()
        V = np.array(g)
        vertices = []
        for i in range(V.shape[0]):
            if V[i, 0] != 1: continue
            if i not in g.lin_set:
                vertices.append(V[i, 1:])
        return vertices
    
    
    A = np.array([[-1, 1],
                  [0, 1],
                  [0.5, 1],
                  [1.5, 1],
                  [-1, 0],
                  [0, -1]])
    b = np.array([1, 2, 3, 6, 0, 0])
    
    vertices = np.array(compute_poly_vertices(A, b))
    print(vertices)
    vertices = np.array(vertices[grahamscan(vertices)])
    
    x, y = vertices[:, 0], vertices[:, 1]
    
    fig=plt.figure(figsize=(15,15))
    ax = fig.add_subplot(111, title="Solution")
    
    ax.fill(x, y, linestyle = '-', linewidth = 1, color='gray', alpha=0.5)
    ax.scatter(x, y, s=10, color='black', alpha=1)
    
    from intvalpy import lineqs
    import numpy as np
    
    A = np.array([[-1, 1],
                  [0, 1],
                  [0.5, 1],
                  [1.5, 1],
                  [-1, 0],
                  [0, -1]])
    b = np.array([1, 2, 3, 6, 0, 0])
    
    lineqs(-A, -b)