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)
似乎fillplots是您所需内容的超集。这应该很容易处理线性不等式
更新
我又在考虑这个问题,我想我会尝试看看没有
fillplots
可以做些什么,只使用标准库,比如scipy
和numpy
在这样一个不等式系统中,每个方程定义了一个半空间。该系统是所有这些半空间的交集,是一个凸集
查找该集合的顶点(例如,绘制它们)称为Vertex enumeration problem。幸运的是,在n维度上,有强大的算法来处理凸包、计算半空间交点(以及做许多其他奇妙的事情)。一个示例实现是Qhull library
更幸运的是,我们可以通过} 和^{}
scipy.spacial
直接访问该库的各个方面,特别是:^{在以下方面:
interior_point
,它是HalfspaceIntersection
所需要的李>Inf
、nan
),我们使用定义边界框(由调用方提供,也用作打印边界)的约束来扩充原始系统Ax <= b
李>HalfspaceIntersection
返回的顺序,在2D中,壳的顶点保证为逆时针顺序)李>我们开始:
测试
(您的原始系统):
产生开放集的修改系统:
有一个优秀的库pypoman,它可以解决顶点枚举问题,并可以帮助解决您的问题,但不幸的是,它只输出集合的顶点,而不输出可视化。顶点可能无序,如果没有其他操作,可视化将不正确。为了克服这个问题,您可以使用这个站点https://habr.com/ru/post/144921/(Graham scan或algo Jarvis)的算法
下面是一个示例代码:
我还在为我的硕士论文编写一个intvalpy库(还没有文档,只有githab上的示例)。功能行也可以帮助您。它解决了系统A x>;=b和输出有序顶点并可视化集合
对于您的问题,代码如下所示:
相关问题 更多 >
编程相关推荐