在Python中高效生成点阵

8 投票
4 回答
14889 浏览
提问于 2025-04-16 18:24

帮我让代码更快:我的Python代码需要生成一个二维点阵,这些点要在一个边界矩形内。我拼凑了一些代码(如下所示)来生成这个点阵。然而,这个函数被调用的次数非常多,已经成为我应用程序的一个严重瓶颈。

我相信有更快的方法来实现这个,可能是用numpy数组而不是列表。有没有更快、更优雅的方法建议?

函数的描述: 我有两个二维向量,v1和v2。这些向量定义了一个点阵。在我的情况下,这两个向量定义的点阵几乎是六边形的,但并不是完全的六边形。我想生成这个点阵中所有在某个边界矩形内的二维点。在我的例子中,矩形的一个角在(0, 0),其他角在正坐标上。

示例: 如果我边界矩形的远角在(3, 3),而我的点阵向量是:

v1 = (1.2, 0.1)
v2 = (0.2, 1.1)

我希望我的函数返回这些点:

(1.2, 0.1) #v1
(2.4, 0.2) #2*v1
(0.2, 1.1) #v2
(0.4, 2.2) #2*v2
(1.4, 1.2) #v1 + v2
(2.6, 1.3) #2*v1 + v2
(1.6, 2.3) #v1 + 2*v2
(2.8, 2.4) #2*v1 + 2*v2

我不太关心边缘情况;例如,函数返回(0, 0)也没关系。

我目前的慢方法

import numpy, pylab

def generate_lattice( #Help me speed up this function, please!
    image_shape, lattice_vectors, center_pix='image', edge_buffer=2):

    ##Preprocessing. Not much of a bottleneck:
    if center_pix == 'image':
        center_pix = numpy.array(image_shape) // 2
    else: ##Express the center pixel in terms of the lattice vectors
        center_pix = numpy.array(center_pix) - (numpy.array(image_shape) // 2)
        lattice_components = numpy.linalg.solve(
            numpy.vstack(lattice_vectors[:2]).T,
            center_pix)
        lattice_components -= lattice_components // 1
        center_pix = (lattice_vectors[0] * lattice_components[0] +
                      lattice_vectors[1] * lattice_components[1] +
                      numpy.array(image_shape)//2)
    num_vectors = int( ##Estimate how many lattice points we need
        max(image_shape) / numpy.sqrt(lattice_vectors[0]**2).sum())
    lattice_points = []
    lower_bounds = numpy.array((edge_buffer, edge_buffer))
    upper_bounds = numpy.array(image_shape) - edge_buffer

    ##SLOW LOOP HERE. 'num_vectors' is often quite large.
    for i in range(-num_vectors, num_vectors):
        for j in range(-num_vectors, num_vectors):
            lp = i * lattice_vectors[0] + j * lattice_vectors[1] + center_pix
            if all(lower_bounds < lp) and all(lp < upper_bounds):
                lattice_points.append(lp)
    return lattice_points


##Test the function and display the output.
##No optimization needed past this point.
lattice_vectors = [
    numpy.array([-40., -1.]),
    numpy.array([ 18., -37.])]
image_shape = (1000, 1000)
spots = generate_lattice(image_shape, lattice_vectors)

fig=pylab.figure()
pylab.plot([p[1] for p in spots], [p[0] for p in spots], '.')
pylab.axis('equal')
fig.show()

4 个回答

3

也许你可以用这个来替代这两个for循环。

i,j = numpy.mgrid[-num_vectors:num_vectors, -num_vectors:num_vectors]
numel = num_vectors ** 2;
i = i.reshape(numel, 1)
j = j.reshape(numel, 1)
lp = i * lattice_vectors[0] + j * lattice_vectors[1] + center_pix
valid = numpy.all(lower_bounds < lp, 1) and numpy.all(lp < upper_bounds, 1)
lattice_points = lp[valid]

可能有一些小错误,但你明白我的意思了。

编辑

我对“numpy.all(lower_bounds..)”做了一些修改,以确保维度是正确的。

6

因为 lower_boundsupper_bounds 只是两个元素的数组,所以用 numpy 可能不是最合适的选择。试着用下面的基本 Python 方法来替代:

if all(lower_bounds < lp) and all(lp < upper_bounds):

用简单的 Python 方法来处理:

if lower1 < lp and lower2 < lp and lp < upper1 and lp < upper2:

根据 timeit 的测试,第二种方法要快得多:

>>> timeit.timeit('all(lower < lp)', 'import numpy\nlp=4\nlower = numpy.array((1,5))') 
3.7948939800262451
>>> timeit.timeit('lower1 < 4 and lower2 < 4', 'lp = 4\nlower1, lower2 = 1,5') 
0.074192047119140625

根据我的经验,只要你不需要处理多维数据,也不需要双精度浮点数,通常使用基本的 Python 数据类型和结构会更快,而不是使用 numpy,因为在这种情况下它有点过于复杂了——你可以看看 这个问题


另一个小改进是可以只计算一次 range(-num_vectors, num_vectors),然后重复使用。此外,你可能想用一个 产品迭代器 来代替嵌套的 for 循环——不过我觉得这些改动对性能的影响不会很大。

6

如果你想把整个东西变成向量形式,首先生成一个方形的网格,然后对它进行剪切。接着,把那些超出你设定范围的边缘部分剪掉。

这是我想到的办法。虽然还有很多可以改进的地方,但这就是基本的思路。

def generate_lattice(image_shape, lattice_vectors) :
    center_pix = numpy.array(image_shape) // 2
    # Get the lower limit on the cell size.
    dx_cell = max(abs(lattice_vectors[0][0]), abs(lattice_vectors[1][0]))
    dy_cell = max(abs(lattice_vectors[0][1]), abs(lattice_vectors[1][1]))
    # Get an over estimate of how many cells across and up.
    nx = image_shape[0]//dx_cell
    ny = image_shape[1]//dy_cell
    # Generate a square lattice, with too many points.
    # Here I generate a factor of 4 more points than I need, which ensures 
    # coverage for highly sheared lattices.  If your lattice is not highly
    # sheared, than you can generate fewer points.
    x_sq = np.arange(-nx, nx, dtype=float)
    y_sq = np.arange(-ny, nx, dtype=float)
    x_sq.shape = x_sq.shape + (1,)
    y_sq.shape = (1,) + y_sq.shape
    # Now shear the whole thing using the lattice vectors
    x_lattice = lattice_vectors[0][0]*x_sq + lattice_vectors[1][0]*y_sq
    y_lattice = lattice_vectors[0][1]*x_sq + lattice_vectors[1][1]*y_sq
    # Trim to fit in box.
    mask = ((x_lattice < image_shape[0]/2.0)
             & (x_lattice > -image_shape[0]/2.0))
    mask = mask & ((y_lattice < image_shape[1]/2.0)
                    & (y_lattice > -image_shape[1]/2.0))
    x_lattice = x_lattice[mask]
    y_lattice = y_lattice[mask]
    # Translate to the centre pix.
    x_lattice += center_pix[0]
    y_lattice += center_pix[1]
    # Make output compatible with original version.
    out = np.empty((len(x_lattice), 2), dtype=float)
    out[:, 0] = y_lattice
    out[:, 1] = x_lattice
    return out

撰写回答