test_minimizers.py 1.3 KB
Newer Older
Matevz, Sraml (sraml)'s avatar
Matevz, Sraml (sraml) committed
1 2
import unittest

3
import numpy as np
Martin Reinecke's avatar
changes  
Martin Reinecke committed
4
from numpy.testing import assert_allclose
Matevz, Sraml (sraml)'s avatar
Matevz, Sraml (sraml) committed
5

Martin Reinecke's avatar
Martin Reinecke committed
6
import nifty2go as ift
Matevz, Sraml (sraml)'s avatar
Matevz, Sraml (sraml) committed
7

Martin Reinecke's avatar
changes  
Martin Reinecke committed
8
from itertools import product
Matevz, Sraml (sraml)'s avatar
Matevz, Sraml (sraml) committed
9 10
from test.common import expand

Martin Reinecke's avatar
changes  
Martin Reinecke committed
11 12
spaces = [ift.RGSpace([1024], distances=0.123), ift.HPSpace(32)]
minimizers = [ift.SteepestDescent, ift.RelaxedNewton, ift.VL_BFGS,
13
              ift.ConjugateGradient, ift.NonlinearCG]
14 15


Martin Reinecke's avatar
changes  
Martin Reinecke committed
16
class Test_Minimizers(unittest.TestCase):
17

Martin Reinecke's avatar
changes  
Martin Reinecke committed
18
    @expand(product(minimizers, spaces))
19
    def test_quadratic_minimization(self, minimizer_class, space):
20
        np.random.seed(42)
Martin Reinecke's avatar
changes  
Martin Reinecke committed
21 22 23
        starting_point = ift.Field.from_random('normal', domain=space)*10
        covariance_diagonal = ift.Field.from_random(
                                  'uniform', domain=space) + 0.5
24
        covariance = ift.DiagonalOperator(covariance_diagonal.weight(-1))
Martin Reinecke's avatar
changes  
Martin Reinecke committed
25
        required_result = ift.Field(space, val=1.)
26

27
        IC = ift.GradientNormController(tol_abs_gradnorm=1e-5)
Martin Reinecke's avatar
changes  
Martin Reinecke committed
28 29 30
        minimizer = minimizer_class(controller=IC)
        energy = ift.QuadraticEnergy(A=covariance, b=required_result,
                                     position=starting_point)
31

Martin Reinecke's avatar
Martin Reinecke committed
32
        (energy, convergence) = minimizer(energy)
Martin Reinecke's avatar
changes  
Martin Reinecke committed
33
        assert convergence == IC.CONVERGED
Martin Reinecke's avatar
Martin Reinecke committed
34 35
        assert_allclose(energy.position.val,
                        1./covariance_diagonal.val,
Martin Reinecke's avatar
changes  
Martin Reinecke committed
36
                        rtol=1e-3, atol=1e-3)