test_minimizers.py 6.41 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.

Matevz, Sraml (sraml)'s avatar
Matevz, Sraml (sraml) committed
19
import unittest
20
import numpy as np
Martin Reinecke's avatar
Martin Reinecke committed
21
from numpy.testing import assert_allclose, assert_equal
Martin Reinecke's avatar
Martin Reinecke committed
22
import nifty4 as ift
Martin Reinecke's avatar
changes  
Martin Reinecke committed
23
from itertools import product
Matevz, Sraml (sraml)'s avatar
Matevz, Sraml (sraml) committed
24
from test.common import expand
Martin Reinecke's avatar
Martin Reinecke committed
25
from nose.plugins.skip import SkipTest
Matevz, Sraml (sraml)'s avatar
Matevz, Sraml (sraml) committed
26

Martin Reinecke's avatar
changes  
Martin Reinecke committed
27 28
spaces = [ift.RGSpace([1024], distances=0.123), ift.HPSpace(32)]
minimizers = [ift.SteepestDescent, ift.RelaxedNewton, ift.VL_BFGS,
Martin Reinecke's avatar
Martin Reinecke committed
29 30
              ift.ConjugateGradient, ift.NonlinearCG,
              ift.NewtonCG, ift.L_BFGS_B]
31

Martin Reinecke's avatar
Martin Reinecke committed
32 33 34
minimizers2 = [ift.RelaxedNewton, ift.VL_BFGS, ift.NonlinearCG,
               ift.NewtonCG, ift.L_BFGS_B]

35 36 37
minimizers3 = [ift.SteepestDescent, ift.RelaxedNewton, ift.VL_BFGS,
               ift.NonlinearCG, ift.NewtonCG, ift.L_BFGS_B]

38

Martin Reinecke's avatar
changes  
Martin Reinecke committed
39
class Test_Minimizers(unittest.TestCase):
40

Martin Reinecke's avatar
changes  
Martin Reinecke committed
41
    @expand(product(minimizers, spaces))
42
    def test_quadratic_minimization(self, minimizer_class, space):
43
        np.random.seed(42)
Martin Reinecke's avatar
changes  
Martin Reinecke committed
44 45 46
        starting_point = ift.Field.from_random('normal', domain=space)*10
        covariance_diagonal = ift.Field.from_random(
                                  'uniform', domain=space) + 0.5
47
        covariance = ift.DiagonalOperator(covariance_diagonal)
48
        required_result = ift.Field.ones(space, dtype=np.float64)
49

50 51
        IC = ift.GradientNormController(tol_abs_gradnorm=1e-5,
                                        iteration_limit=1000)
Martin Reinecke's avatar
Martin Reinecke committed
52 53 54 55
        try:
            minimizer = minimizer_class(controller=IC)
            energy = ift.QuadraticEnergy(A=covariance, b=required_result,
                                         position=starting_point)
56

Martin Reinecke's avatar
Martin Reinecke committed
57 58 59 60 61
            (energy, convergence) = minimizer(energy)
        except NotImplementedError:
            raise SkipTest

        assert_equal(convergence, IC.CONVERGED)
Martin Reinecke's avatar
Martin Reinecke committed
62 63
        assert_allclose(energy.position.to_global_data(),
                        1./covariance_diagonal.to_global_data(),
Martin Reinecke's avatar
changes  
Martin Reinecke committed
64
                        rtol=1e-3, atol=1e-3)
Martin Reinecke's avatar
Martin Reinecke committed
65

Martin Reinecke's avatar
Martin Reinecke committed
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
    @expand(product(minimizers2))
    def test_rosenbrock(self, minimizer_class):
        try:
            from scipy.optimize import rosen, rosen_der, rosen_hess_prod
        except ImportError:
            raise SkipTest
        np.random.seed(42)
        space = ift.UnstructuredDomain((2,))
        starting_point = ift.Field.from_random('normal', domain=space)*10

        class RBEnergy(ift.Energy):
            def __init__(self, position):
                super(RBEnergy, self).__init__(position)

            @property
            def value(self):
                return rosen(self._position.to_global_data().copy())

            @property
            def gradient(self):
                inp = self._position.to_global_data().copy()
                out = ift.Field.from_global_data(space, rosen_der(inp))
                return out

            @property
            def curvature(self):
                class RBCurv(ift.EndomorphicOperator):
                    def __init__(self, loc):
                        self._loc = loc.to_global_data().copy()

                    @property
                    def domain(self):
                        return space

                    @property
                    def capability(self):
                        return self.TIMES

                    def apply(self, x, mode):
                        self._check_input(x, mode)
                        inp = x.to_global_data().copy()
                        out = ift.Field.from_global_data(
                            space, rosen_hess_prod(self._loc.copy(), inp))
                        return out
Martin Reinecke's avatar
Martin Reinecke committed
110

Martin Reinecke's avatar
Martin Reinecke committed
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
                t1 = ift.GradientNormController(tol_abs_gradnorm=1e-5,
                                                iteration_limit=1000)
                t2 = ift.ConjugateGradient(controller=t1)
                return ift.InversionEnabler(RBCurv(self._position),
                                            inverter=t2)

        IC = ift.GradientNormController(tol_abs_gradnorm=1e-5,
                                        iteration_limit=10000)
        try:
            minimizer = minimizer_class(controller=IC)
            energy = RBEnergy(position=starting_point)

            (energy, convergence) = minimizer(energy)
        except NotImplementedError:
            raise SkipTest

        assert_equal(convergence, IC.CONVERGED)
        assert_allclose(energy.position.to_global_data(), 1.,
                        rtol=1e-3, atol=1e-3)
130 131

    @expand(product(minimizers3))
Martin Reinecke's avatar
Martin Reinecke committed
132
    def DISABLEDtest_nonlinear(self, minimizer_class):
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
        space = ift.UnstructuredDomain((1,))
        starting_point = ift.Field(space, val=5.)

        class ExpEnergy(ift.Energy):
            def __init__(self, position):
                super(ExpEnergy, self).__init__(position)

            @property
            def value(self):
                x = self.position.to_global_data()[0]
                return -np.exp(-(x**2))

            @property
            def gradient(self):
                x = self.position.to_global_data()[0]
                return ift.Field(self.position.domain, val=2*x*np.exp(-(x**2)))

            @property
            def curvature(self):
                x = self.position.to_global_data()[0]
                v = (2 - 4*x*x)*np.exp(-x**2)
                return ift.DiagonalOperator(
                    ift.Field(self.position.domain, val=v))

        IC = ift.GradientNormController(tol_abs_gradnorm=1e-10,
                                        iteration_limit=10000)
        try:
            minimizer = minimizer_class(controller=IC)
            energy = ExpEnergy(position=starting_point)

            (energy, convergence) = minimizer(energy)
        except NotImplementedError:
            raise SkipTest

        assert_equal(convergence, IC.CONVERGED)
        assert_allclose(energy.position.to_global_data(), 0.,
                        atol=1e-3)