我生成了一个python中六边形顶点的xy坐标数组。我想标记对应于它所属的六边形的xy网格。绘制时,顶点看起来像:Vertices
我想要一个以下格式的文本文件: x y Hexagon#
我是Python新手,非常感谢任何帮助。谢谢!
答案 0 :(得分:0)
最简单的方法是计算六边形的质心。因此,我使用以下函数生成多边形质心,而不是生成多边形顶点:calc_polycentroids(startx,starty,endx,endy,a)其中a =由质心形成的十六边形
def calc_polycentroids(startx, starty, endx, endy, a):
# calculate coordinates of the hexagon points
hx=3.*a
hy=a*np.sqrt(3)
origx = startx
origy = starty
# offsets for moving along and up rows
xoffset = hx
yoffset = hy
polygons = []
counter = 0
while starty < endy:
startx = origx
while startx < endx:
p1x = startx + 0.5*a
p1y = starty
p2x = startx + 1.5*a
p2y = starty
p3x = startx + 2.5*a
p3y = starty
p4x = startx
p4y = starty + (a*np.sqrt(3)/2)
p5x = startx + a
p5y = starty + (a*np.sqrt(3)/2)
p6x = startx + 2.*a
p6y = starty + (a*np.sqrt(3)/2)
p7x = startx + 3.*a
p7y = starty + (a*np.sqrt(3)/2)
p8x = startx + 0.5*a
p8y = starty + (a*np.sqrt(3))
p9x = startx + 1.5*a
p9y = starty + (a*np.sqrt(3))
p10x= startx + 2.5*a
p10y= starty + (a*np.sqrt(3))
poly = [
(p1x, p1y),
(p2x, p2y),
(p3x, p3y),
(p4x, p4y),
(p5x, p5y),
(p6x, p6y),
(p7x, p7y),
(p8x, p8y),
(p9x, p9y),
(p10x,p10y),
]
polygons.append(poly)
counter += 1
startx += hx
starty += yoffset
#Truncate points
temp1=np.array(polygons)
temp3=temp1.reshape(temp1.shape[1]*temp1.shape[0],temp1.shape[2])
return temp3`
然后我定义了x-y网格并使用cKDTree来预测最近邻居作为它最接近的质心的索引。
polygons1=calc_polycentroids(0,0,N,N,a)
x=np.linspace(0,N,N+2);
y=np.linspace(0,N,N+2);
points=np.array(np.meshgrid(x,y))
test_points=np.reshape(np.array([np.ravel(points,order='F')]),((N+2)*(N+2),2))#The x-y points to iterate over
voronoi_kdtree = cKDTree(polygons1) #giving centroids of the grains
test_point_dist, test_point_regions = voronoi_kdtree.query(test_points, k=1)
#test_point_regions Now holds an array of shape (n_test, 1)
#with the indices of the points in polygons1 closest to each of your test_points.
因此,如果我绘制等高线图,我得到以下结构:N = 128 Hexagonal lattice