Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ENH: use memoization in MINPACK routines #236

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 5 additions & 1 deletion scipy/optimize/minpack.py
Expand Up @@ -4,7 +4,7 @@
from numpy import atleast_1d, dot, take, triu, shape, eye, \
transpose, zeros, product, greater, array, \
all, where, isscalar, asarray, inf, abs
from optimize import Result
from optimize import Result, MemoizeFun

error = _minpack.error

Expand Down Expand Up @@ -183,6 +183,7 @@ def _root_hybr(func, x0, args=(), jac=None, options=None):
diag = options.get('diag', None)

full_output = True
func = MemoizeFun(func, first_only=True, nskip=1)
x0 = array(x0, ndmin=1)
n = len(x0)
if type(args) != type(()):
Expand All @@ -199,6 +200,7 @@ def _root_hybr(func, x0, args=(), jac=None, options=None):
retval = _minpack._hybrd(func, x0, args, full_output, xtol, maxfev,
ml, mu, epsfcn, factor, diag)
else:
Dfun = MemoizeFun(Dfun, first_only=True, nskip=1)
_check_func('fsolve', 'fprime', Dfun, x0, args, n, (n,n))
if (maxfev == 0):
maxfev = 100*(n + 1)
Expand Down Expand Up @@ -348,6 +350,7 @@ def leastsq(func, x0, args=(), Dfun=None, full_output=0,
params

"""
func = MemoizeFun(func, first_only=True, nskip=1)
x0 = array(x0, ndmin=1)
n = len(x0)
if type(args) != type(()):
Expand All @@ -361,6 +364,7 @@ def leastsq(func, x0, args=(), Dfun=None, full_output=0,
retval = _minpack._lmdif(func, x0, args, full_output, ftol, xtol,
gtol, maxfev, epsfcn, factor, diag)
else:
Dfun = MemoizeFun(Dfun, first_only=True, nskip=1)
if col_deriv:
_check_func('leastsq', 'Dfun', Dfun, x0, args, n, (n,m))
else:
Expand Down
35 changes: 35 additions & 0 deletions scipy/optimize/optimize.py
Expand Up @@ -39,11 +39,46 @@
'pr_loss': 'Desired error not necessarily achieved due '
'to precision loss.'}


class MemoizeFun(object):
""" Decorator that caches the value of the objective function.
If `first_only==True`, only the first point is memoized.
If `nskip > 0`, it is assumed that the function is evaluated `nskip`
times at the first point, so that the memoized values is used. """
def __init__(self, fun, first_only=False, nskip=0):
self.fun = fun
if hasattr(fun, '__name__'):
self.__name__ = fun.__name__
self.first_only = first_only
self.nskip = nskip

def __call__(self, x, *args):
if hasattr(self, 'calls'):
self.calls += 1
else:
self.calls = 0
if self.calls == 0:
self.x = numpy.asarray(x).copy()
self.f = self.fun(x, *args)
return self.f
elif self.calls <= self.nskip:
return self.f
elif self.first_only and self.calls > 1:
return self.fun(x, *args)
elif numpy.any(x != self.x):
self.x = numpy.asarray(x).copy()
self.f = self.fun(x, *args)
return self.f
else:
return self.f

class MemoizeJac(object):
""" Decorator that caches the value gradient of function each time it
is called. """
def __init__(self, fun):
self.fun = fun
if hasattr(fun, '__name__'):
self.__name__ = fun.__name__
self.jac = None
self.x = None

Expand Down