这是一个解决方案,它计算距中心点的平方距离数组,然后获取最近 n 个点的索引——通过对(squared_distance, indices) 元组列表进行排序,其中indices 本身就是一个索引元组(由 np.ndindex) 返回——并在这些点将 self.grid 数组值设置为 1。 (有一些显式循环,因此可能存在更有效的解决方案。)
请注意,我已将网格设置为 (y, x),以便 y 与行相关,因为反过来更容易混淆。
它还在self.list_of_atoms 中创建索引列表。 (列表的每个元素都是一个索引元组。)
import numpy as np
class Grid():
def __init__(self, x, y):
self.grid = np.zeros((y,x), dtype=np.int)
self.list_of_atoms=[]
self.x = x
self.y = y
def initiate_atoms_in_circle(self, quantity, centrex=None, centrey=None):
if centrex == None:
centrex = self.x / 2
if centrey == None:
centrey = self.y / 2
xvals, yvals = np.meshgrid(np.arange(self.x), np.arange(self.y))
dist2 = (xvals - centrex) ** 2 + (yvals - centrey) ** 2
dist2_and_pos = [(dist2[indices], indices) for indices in np.ndindex(dist2.shape)]
dist2_and_pos.sort()
for _, indices in dist2_and_pos[:quantity]:
self.grid[indices] = 1
self.list_of_atoms.append(indices)
self.list_of_atoms.sort()
g = Grid(20, 15)
g.initiate_atoms_in_circle(100)
print(g.grid)
print("Total atoms:", np.sum(g.grid))
print("Length of indices list:", len(g.list_of_atoms))
print("Start of indices list:", g.list_of_atoms[:5])
这给出了:
[[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0]
[0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 0 0 0 0 0]
[0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0]
[0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0]
[0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0]
[0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0]
[0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0]
[0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 0 0 0 0 0]
[0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 0 0 0 0 0]
[0 0 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]]
Total atoms: 100
Length of indices list: 100
Start of indices list: [(2, 9), (2, 10), (2, 11), (3, 7), (3, 8)]