如何在python中加速N维区间树?
考虑以下问题:给定一组n个区间和一组m个浮点数,为每个浮点数确定包含浮点数的区间子集 这个问题已经通过构造一个(或称为范围树或段树)来解决。已经完成了一维情况的实现,例如python的。通常,这些实现考虑了一个或几个浮点数,即上面的一个小“m”。 在我的问题设置中,n和m都是非常大的数字(来自解决图像处理问题)。此外,我需要考虑N维的间隔(称为长方体当n=3时,因为我用有限元法对人脑进行建模)。我在python中实现了一个简单的N维区间树,但它在循环中运行,一次只能获取一个浮点数。有人能帮助提高执行效率吗?您可以自由更改数据结构如何在python中加速N维区间树?,python,performance,numpy,vectorization,finite-element-analysis,Python,Performance,Numpy,Vectorization,Finite Element Analysis,考虑以下问题:给定一组n个区间和一组m个浮点数,为每个浮点数确定包含浮点数的区间子集 这个问题已经通过构造一个(或称为范围树或段树)来解决。已经完成了一维情况的实现,例如python的。通常,这些实现考虑了一个或几个浮点数,即上面的一个小“m”。 在我的问题设置中,n和m都是非常大的数字(来自解决图像处理问题)。此外,我需要考虑N维的间隔(称为长方体当n=3时,因为我用有限元法对人脑进行建模)。我在python中实现了一个简单的N维区间树,但它在循环中运行,一次只能获取一个浮点数。有人能帮助提高
import sys
import time
import numpy as np
# find the index of a satisfying x > a in one dimension
def find_index_smaller(a, x):
idx = np.argsort(a)
ss = np.searchsorted(a, x, sorter=idx)
res = idx[0:ss]
return res
# find the index of a satisfying x < a in one dimension
def find_index_larger(a, x):
return find_index_smaller(-a, -x)
# find the index of a satisfing amin < x < amax in one dimension
def find_intv_at(amin, amax, x):
idx = find_index_smaller(amin, x)
idx2 = find_index_larger(amax[idx], x)
res = idx[idx2]
return res
# find the index of a satisfying amin < x < amax in N dimensions
def find_intv_at_nd(amin, amax, x):
dim = amin.shape[0]
res = np.arange(amin.shape[-1])
for i in range(dim):
idx = find_intv_at(amin[i, res], amax[i, res], x[i])
res = res[idx]
return res
我的想法是:
任何贡献都将不胜感激。您是否尝试过使用oct树或kd树?@Sopel我没有发现oct树的N-D实现。对于scipy kd树,它是找到最近的邻居。但是,您只需要N=3就可以了?您也可以反过来查询kd树,即查找给定长方体中包含的点。如果您不想使用自己的解决方案,也可以使用切比雪夫度量进行欺骗。@Sopel我认为我们不能在这里使用kd树,因为我需要找到包含特定点的所有间隔。顺便说一下,kd-tree并不总是给出准确的解决方案,所以我不想使用它。
def demo1():
print ("By default, we do a correctness test")
n_intv = 2
n_point = 2
# generate the test data
point = np.random.rand(3, n_point)
intv_min = np.random.rand(3, n_intv)
intv_max = intv_min + np.random.rand(3, n_intv)*8
print ("point ")
print (point)
print ("intv_min")
print (intv_min)
print ("intv_max")
print (intv_max)
print ("===Indexes of intervals that contain the point===")
for i in range(n_point):
print (find_intv_at_nd(intv_min,intv_max, point[:, i]))
def demo2():
print ("Performance:")
n_points=100
n_intv = 1000000
# generate the test data
points = np.random.rand(n_points, 3)*512
intv_min = np.random.rand(3, n_intv)*512
intv_max = intv_min + np.random.rand(3, n_intv)*8
print ("point.shape = "+str(points.shape))
print ("intv_min.shape = "+str(intv_min.shape))
print ("intv_max.shape = "+str(intv_max.shape))
starttime = time.time()
for point in points:
tmp = find_intv_at_nd(intv_min, intv_max, point)
print("it took this long to run {} points, with {} interva: {}".format(n_points, n_intv, time.time()-starttime))