标识网格粒子所属



尺寸为10,000*10,000的方盒中,10,00,000粒子均匀分布。盒子被分成网格,每个网格的大小为100*100。总共有10,000个栅格。在每一个时间步(总共2016步),我想确定一个粒子所属的网格。有没有一种有效的方法在python中实现这个?我的实现如下所示,目前一次运行大约需要83秒。

import numpy as np
import time
start=time.time()
# Size of the layout
Layout = np.array([0,10000])
# Total Number of particles
Population = 1000000
# Array to hold the cell number
cell_number = np.zeros((Population),dtype=np.int32)
# Limits of each cell
boundaries = np.arange(0,10100,step=100)
cell_boundaries = np.dstack((boundaries[0:100],boundaries[1:101]))
# Position of Particles
points = np.random.uniform(0,Layout[1],size = (Population,2))
# Generating a list with the x,y boundaries of each cell in the grid
x = []
limit_list = cell_boundaries
for i in range(0,Layout[1]//100):
    for j in range(0,Layout[1]//100):
        x.append([limit_list[0][i,0],limit_list[0][i,1],limit_list[0][j,0],limit_list[0][j,1]])  
# Identifying the cell to which the particles belong
i=0
for y in (x):
  cell_number[(points[:,1]>y[0])&(points[:,1]<y[1])&(points[:,0]>y[2])&(points[:,0]<y[3])]=i 
  i+=1
print(time.time()-start)

我不确定你的代码。你似乎在全局积累i变量。虽然它应该在每个单元格的基础上累积,对吗?也许是cell_number[???] += 1之类的?

不管怎样,我是从另一个角度看问题的。您可以首先为每个点分配一个单元格id。然后用一种计数器函数对生成的数组进行逆运算。我在PyTorch中实现了以下功能,你很可能会在Numpy中找到相应的实用程序。

从两点坐标到单元格id的转换对应于在坐标上应用floor,然后根据网格的宽度展开它们。

>>> p = torch.from_numpy(points).floor()
>>> p_unfold = p[:, 0]*10000 + p[:, 1]

那么你就可以&;倒&;统计数据,即。根据细胞id找出每个细胞中有多少粒子。这可以使用PyTorch直方图的计数器torch.histc:

来完成。
>>> torch.histc(p_unfold, bins=Population)

最新更新