【问题标题】:find all points in the grid找到网格中的所有点
【发布时间】:2022-08-18 22:17:43
【问题描述】:

我有 100 万个随机点(float x, float y),它们在一个矩形区域内。现在我想把矩形分成很多个小矩形,可以得到每个小矩形的中心点坐标,比如[(0.5,0.5),(0.5,1.5)]。问题是如何快速知道每个随机点属于哪个小矩形!! 这是我的代码:

## generate the center point of each small rectangle. 
def gen_center_coor(row = None, col = None,bias = None):
    spatial = np.zeros((row*col,2))
    a,b=np.meshgrid(np.arange(row),np.arange(col),indexing = \'ij\')
    spatial[:,0], spatial[:,1] = a.reshape(-1),b.reshape(-1) 
    spatial += bias
    return spatial
centerdot = gen_center_coor(row =320, col = 320,bias = 0.5)


## generate the number of points per small rectangle (randomnums) 
## and random points (randdot) 

randomnums = np.random.randint(low=5,high=15,size=320 * 320)
randrow = np.random.uniform(low=-0.5, high=0.5, size=sum(randomnums))
randcol = np.random.uniform(low=-0.5, high=0.5, size=sum(randomnums))
randdot_row = np.repeat(centerdot[:, 0], randomnums) + randrow
randdot_col = np.repeat(centerdot[:, 1], randomnums) + randcol
randdot = np.hstack((randdot_row.reshape(-1,1), randdot_col.reshape(-1, 1)))

## in fact, randomnums: just to verify your code
## you only have the randdot
##  here is my main function, but it is too slow for me 
for i in range(100):
    gdnet = np.repeat(centerdot[i],randdot.shape[0]).reshape(randdot.shape[0],2)
    np.where(np.abs(randdot - gdnet).max(-1)<0.5)[0]
  • 您的矩形是否与 X/Y 轴对齐?另外,小矩形的大小都一样吗?

标签: python numpy numba


【解决方案1】:

有三个假设:

  1. 矩形与 X/Y 轴对齐。如果不是,您可以先对点坐标应用旋转。
  2. 大矩形的范围从 (0, 0) 到 (Lx, Ly) - 如果不是,请再次转换您的数据,以便它这样做。
  3. 所有小矩形的大小都相同 - 换句话说,您将大矩形分割成一个统一的网格。

    我知道的最快的方法是:

    import numpy as np
    # prep some mock data first
    N = 10_000_000
    Lx = 1
    Ly = 1
    points_x = np.random.uniform(0, Lx, N)
    points_y = np.random.uniform(0, Ly, N)
    
    N_grid = 1000    # splitting into 1000 uniform rectangles
    
    # and now for the main dish:
    
    dx = Lx / N_grid  # grid size
    dy = Ly / N_grid
    
    points_x_indices = (points_x / dx).astype(int)
    points_y_indices = (points_y / dy).astype(int)
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-29
    • 2021-01-30
    • 2013-05-28
    • 2012-03-19
    • 1970-01-01
    相关资源
    最近更新 更多