scipy_minimizer.py 3.83 KB
Newer Older
Martin Reinecke's avatar
Martin Reinecke committed
1
2
3
4
5
6
7
8
9
10
11
12
13
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
Martin Reinecke's avatar
Martin Reinecke committed
14
# Copyright(C) 2013-2018 Max-Planck-Society
Martin Reinecke's avatar
Martin Reinecke committed
15
16
17
18
#
# NIFTy is being developed at the Max-Planck-Institut fuer Astrophysik
# and financially supported by the Studienstiftung des deutschen Volkes.

Martin Reinecke's avatar
stage 1    
Martin Reinecke committed
19
from __future__ import division
Martin Reinecke's avatar
Martin Reinecke committed
20
21
22
from .minimizer import Minimizer
from ..field import Field
from .. import dobj
Martin Reinecke's avatar
Martin Reinecke committed
23
from ..logger import logger
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
from .iteration_controller import IterationController


class _MinHelper(object):
    def __init__(self, energy):
        self._energy = energy
        self._domain = energy.position.domain

    def _update(self, x):
        pos = Field(self._domain, x.reshape(self._domain.shape))
        if (pos.val != self._energy.position.val).any():
            self._energy = self._energy.at(pos.locked_copy())

    def fun(self, x):
        self._update(x)
        return self._energy.value

    def jac(self, x):
        self._update(x)
        return self._energy.gradient.val.flatten()

    def hessp(self, x, p):
        self._update(x)
        vec = Field(self._domain, p.reshape(self._domain.shape))
        res = self._energy.curvature(vec)
        return res.val.flatten()
Martin Reinecke's avatar
Martin Reinecke committed
50
51
52
53
54
55
56
57
58
59
60
61
62


class ScipyMinimizer(Minimizer):
    """Scipy-based minimizer

    Parameters
    ----------
    method     : str
        The selected Scipy minimization method.
    options    : dictionary
        A set of custom options for the selected minimizer.
    """

63
    def __init__(self, method, options, need_hessp, bounds):
Martin Reinecke's avatar
Martin Reinecke committed
64
65
66
67
68
69
        super(ScipyMinimizer, self).__init__()
        if not dobj.is_numpy():
            raise NotImplementedError
        self._method = method
        self._options = options
        self._need_hessp = need_hessp
70
        self._bounds = bounds
Martin Reinecke's avatar
Martin Reinecke committed
71
72
73

    def __call__(self, energy):
        import scipy.optimize as opt
74
75
76
77
78
79
80
81
        hlp = _MinHelper(energy)
        energy = None  # drop handle, since we don't need it any more
        bounds = None
        if self._bounds is not None:
            if len(self._bounds) == 2:
                lo = self._bounds[0]
                hi = self._bounds[1]
                bounds = [(lo, hi)]*hlp._energy.position.size
Martin Reinecke's avatar
Martin Reinecke committed
82
            else:
83
84
85
86
87
88
                raise ValueError("unrecognized bounds")

        x = hlp._energy.position.val.flatten()
        hessp = hlp.hessp if self._need_hessp else None
        r = opt.minimize(hlp.fun, x, method=self._method, jac=hlp.jac,
                         hessp=hessp, options=self._options, bounds=bounds)
Martin Reinecke's avatar
Martin Reinecke committed
89
        if not r.success:
Martin Reinecke's avatar
Martin Reinecke committed
90
            logger.error("Problem in Scipy minimization:", r.message)
91
92
            return hlp._energy, IterationController.ERROR
        return hlp._energy, IterationController.CONVERGED
Martin Reinecke's avatar
Martin Reinecke committed
93
94


95
def NewtonCG(xtol, maxiter, disp=False):
Martin Reinecke's avatar
Martin Reinecke committed
96
97
98
99
100
101
    """Returns a ScipyMinimizer object carrying out the Newton-CG algorithm.

    See Also
    --------
    ScipyMinimizer
    """
Martin Reinecke's avatar
fix    
Martin Reinecke committed
102
    options = {"xtol": xtol, "maxiter": maxiter, "disp": disp}
103
    return ScipyMinimizer("Newton-CG", options, True, None)
Martin Reinecke's avatar
Martin Reinecke committed
104
105


106
def L_BFGS_B(ftol, gtol, maxiter, maxcor=10, disp=False, bounds=None):
Martin Reinecke's avatar
Martin Reinecke committed
107
108
109
110
111
112
    """Returns a ScipyMinimizer object carrying out the L-BFGS-B algorithm.

    See Also
    --------
    ScipyMinimizer
    """
113
    options = {"ftol": ftol, "gtol": gtol, "maxiter": maxiter,
Martin Reinecke's avatar
fix    
Martin Reinecke committed
114
               "maxcor": maxcor, "disp": disp}
115
    return ScipyMinimizer("L-BFGS-B", options, False, bounds)