在两个numpy数组中的所有元素对之间矢量化操作

时间:2017-02-02 11:03:01

标签: python arrays numpy geometry combinations

给定两个数组,其中每一行代表一个圆(x,y,r):

data = {}
data[1] = np.array([[455.108, 97.0478, 0.0122453333],
                    [403.775, 170.558, 0.0138770952],
                    [255.383, 363.815, 0.0179857619]])
data[2] = np.array([[455.103, 97.0473, 0.012041],
                    [210.19, 326.958, 0.0156912857],
                    [455.106, 97.049, 0.0150472381]])

我想拉出所有没有脱节的圈子。这可以通过以下方式完成:

close_data = {}
for row1 in data[1]: #loop over first array
    for row2 in data[2]: #loop over second array
        condition = ((abs(row1[0]-row2[0]) + abs(row1[1]-row2[1])) < (row1[2]+row2[2])) 
        if condition: #circles overlap if true
            if tuple(row1) not in close_data.keys():                           
                close_data[tuple(row1)] = [row1, row2] #pull out close data points
            else:
                close_data[tuple(row1)].append(row2)

for k, v in close_data.iteritems():
    print k, v 
#desired outcome   
#(455.108, 97.047799999999995, 0.012245333299999999)
#[array([  4.55108000e+02,   9.70478000e+01,   1.22453333e-02]), 
# array([  4.55103000e+02,   9.70473000e+01,   1.2040000e-02]), 
# array([  4.55106000e+02,   9.70490000e+01,   1.50472381e-02])]

然而,对于大型数据集,数组上的多个循环效率非常低。是否有可能对计算进行矢量化,以便我获得使用numpy的优势?

2 个答案:

答案 0 :(得分:3)

最困难的一点是实际获取信息的表示。哦,我插了几个方格。如果你真的不想要欧几里德距离,你必须改回来。

import numpy as np

data = {}
data[1] = np.array([[455.108, 97.0478, 0.0122453333],
                    [403.775, 170.558, 0.0138770952],
                    [255.383, 363.815, 0.0179857619]])
data[2] = np.array([[455.103, 97.0473, 0.012041],
                    [210.19, 326.958, 0.0156912857],
                    [455.106, 97.049, 0.0150472381]])

d1 = data[1][:, None, :]
d2 = data[2][None, :, :]
dists2 = ((d1[..., :2] - d2[..., :2])**2).sum(axis = -1)
radss2 = (d1[..., 2] + d2[..., 2])**2

inds1, inds2 = np.where(dists2 <= radss2)

# translate to your representation:

bnds = np.r_[np.searchsorted(inds1, np.arange(3)), len(inds1)]
rows = [data[2][inds2[bnds[i]:bnds[i+1]]] for i in range(3)]
out = dict([(tuple (data[1][i]), rows[i]) for i in range(3) if rows[i].size > 0])

答案 1 :(得分:0)

这是一种纯粹的numpythonic方式(classpreceding-sibling keywordadata[1]):

b