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

optimize function evaluations caching partial result

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

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

也许

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

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

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

如果你可以将这些函数写成纯函数(这意味着它们总是 return 相同参数的相同值,并且没有副作用),你可以使用 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 < 3.2 上使用 functools32

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