我编写了一个Numpy实现,它使用Cox-de Boor递归算法来计算B样条基函数。我想memoize
给定order
的对象实例,但保留相对于xi
可调用的函数。
换句话说,在实例化对象之后,递归函数应该是" set",但仍然可以在xi
调用。我真的需要这个速度,因为我将多次调用该函数,并且不想重复重建递归函数。
以下是当前的实施:
import numpy as np
#Turn off divide by zero warning because we explicitly check for it
np.seterr(divide='ignore')
class Bspline():
def __init__(self, knot_vector, order):
self.knot_vector = knot_vector
self.p = order
def __basis0(self, xi):
return np.where(np.all([self.knot_vector[:-1] <= xi,
xi < self.knot_vector[1:]],axis=0), 1.0, 0.0)
def __basis(self, xi, p):
if p == 0:
return self.__basis0(xi)
else:
basis_p_minus_1 = self.__basis(xi, p - 1)
first_term_numerator = xi - self.knot_vector[:-p]
first_term_denominator = self.knot_vector[p:] - self.knot_vector[:-p]
second_term_numerator = self.knot_vector[(p + 1):] - xi
second_term_denominator = self.knot_vector[(p + 1):] - self.knot_vector[1:-p]
first_term = np.where(first_term_denominator > 1.0e-12,
first_term_numerator / first_term_denominator, 0)
second_term = np.where(second_term_denominator > 1.0e-12,
second_term_numerator / second_term_denominator, 0)
return first_term[:-1] * basis_p_minus_1[:-1] + second_term * basis_p_minus_1[1:]
def __call__(self, xi):
return self.__basis(xi, self.p)
并用作
knot_vector = np.array([0,0,0,0,0,1,2,2,3,3,3,4,4,4,4,5,5,5,5,5])
basis = Bspline(knot_vector,4)
basis(1.2)
返回在1.2
评估的基函数。但是,我需要多次调用此函数,并且正如现在编写的那样,每次调用都会重构递归函数,这不是必需的,因为递归级别在实例化时设置为4
答案 0 :(得分:3)
在Python3中使用functools.lru_cache
或使用this之类的内容在Python2.7中记忆任何内容都非常容易:
class Bspline(object):
...
# Python2.7
@memoize
# or, Python3*
@functools.lru_cache()
def op(self, args):
return self._internal_op(xi)
答案 1 :(得分:0)
创建一个保存函数结果的字典,然后在再次调用该函数之前检查该值是否在dict中。根据您的设置,类似的东西应该有效。
results = {}
for value in values:
if results.get(value):
answer = results[value]
else:
answer = basis(value)
results[value] = answer
print(answer) # or just display the results dict once you are done