帮助我更快地编写代码:我的python代码需要生成位于边界矩形内的点的二维点阵。我将一些代码(如下所示)汇集在一起生成此格。然而,这个函数被多次调用,并且已经成为我应用程序中的一个严重瓶颈。高效地生成python中点的点阵
我相信有一个更快的方法来做到这一点,可能涉及numpy数组而不是列表。任何建议更快,更优雅的方式来做到这一点?
功能描述: 我有两个2D矢量,v1和v2。这些载体define a lattice。就我而言,我的矢量定义了一个几乎但不完全是六角形的格子。我想生成一些边界矩形中的这个点阵上的所有二维点的集合。在我的情况下,矩形的其中一个角位于(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()
难道是更好地为您做'lattice_components = numpy.modf(lattice_components)[0]'? (不问你的问题,但出于好奇,它会明显更快/更慢?) – JAB 2011-05-26 17:02:48
不知道modf,好建议。我认为在这个函数中花费的大部分时间都在双重嵌套for循环中,但我会进行基准测试以确保。 – Andrew 2011-05-26 17:18:10
请写一个这个函数做什么的总结。 – 2011-05-26 19:39:37