首页 > 解决方案 > 如何在列表中生成圆的坐标

问题描述

我正在尝试模拟粒子扩散,我需要生成它们的起始坐标。他们需要以列表中坐标 [x,y] 的圆圈开始。例如,当粒子以正方形开始模拟时,坐标数组如下所示:

[[2, 2], [2, 3], [3, 2], [3, 3]]

我也试图让粒子的起始位置大致在网格的中心。例如,上面的坐标是 5x5 网格中的起始位置

有没有人有任何建议如何在一个圆圈中生成坐标(不仅仅是圆周上的坐标,填写)

要生成正方形中的点,我使用以下代码:

类网格():

def __init__(self, x, y):
    
    self.grid = np.zeros((x,y))
    self.list_of_atoms=[]
    self.x = x
    self.y = y
    
def initiate_atoms_in_square(self,quantity):
    """initiate a square of atoms roughly in the centre of the grid space """
    self.side_length = int(math.sqrt(quantity))
    self.start = int(self.x/2 + ((self.x**2)/2))
    lower_x = int(self.x/2)
    upper_x = int(self.x/2+self.side_length)
    lower_y = int(self.y/2)
    upper_y = int(self.y/2+self.side_length)
      
    coords=[]
    for i in range(lower_x,upper_x):
        for j in range(lower_y,upper_y):
            coords.append([i,j])
          

标签: pythongeometrycoordinatesnested-lists

解决方案


这是一个解决方案,它计算距中心点的平方距离数组,然后获取最近的 n 点的索引——通过对本身是索引元组的(squared_distance, indices)元组列表进行排序(由 返回)——并设置数组值在这些点为 1。(有一些显式循环,因此可能存在更有效的解决方案。)indicesnp.ndindexself.grid

请注意,我已将网格放置为(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)]

推荐阅读