优化函数评估缓存部分结果

时间:2015-08-10 23:06:03

标签: python caching scipy scikits root-framework

假设我有一个复杂的数学函数,有许多输入参数P = [p1, ..., pn]。假设我可以将函数分解为块,例如:

f(P) = f1(p1, p2) * f2(p2, ... pn)

也许

f2(p2, ..., pn) = p2 * f3(p4) + f4(p5, ..., pn)

假设我必须为f的许多值评估P,例如我想找到f的最小值。假设我已经计算了f(P),我需要计算f(P'),其中P'等于Pp1除外。在这种情况下,我不必重新计算f2, f3, f4,而只需f1

是否有一个库可以帮助我实现这种缓存系统?我知道RooFit,但它面向统计模型,由块组成。我正在寻找更通用的东西。 scipy / scikits和类似的是首选,但c ++库也可以。这种技术有名吗?

1 个答案:

答案 0 :(得分:4)

如果你可以将这些函数写成纯函数(这意味着它们总是为相同的参数返回相同的值,并且没有副作用),你可以使用memoization,这是一种保存函数调用结果的方法

try:
    from functools import lru_cache  # Python 3.2+
except ImportError:  # Python 2
    # Python 2 and Python 3.0-3.1
    # Requires the third-party functools32 package
    from functools32 import lru_cache

@lru_cache(maxsize=None)
def f(arg):
    # expensive operations
    return result

x = f('arg that will take 10 seconds')  # takes 10 seconds
y = f('arg that will take 10 seconds')  # virtually instant

为了说明,或者如果您不想在Python上使用functools32< 3.2:

def memoize(func):
    memo = {}

    def wrapper(*args):
        if args not in memo:            
            memo[args] = func(*args)
        return memo[args]

    return helper

@memoize
def f(arg):
    # expensive operations
    return result

x = f('arg that will take 10 seconds')  # takes 10 seconds
y = f('arg that will take 10 seconds')  # virtually instant