test_minimizers.py 1.31 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
changes  
Martin Reinecke committed
6
import nifty 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
13
spaces = [ift.RGSpace([1024], distances=0.123), ift.HPSpace(32)]
minimizers = [ift.SteepestDescent, ift.RelaxedNewton, ift.VL_BFGS,
              ift.ConjugateGradient]
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
19
    @expand(product(minimizers, spaces))
    def test_minimization(self, minimizer_class, space):
20
        np.random.seed(42)
Martin Reinecke's avatar
changes  
Martin Reinecke committed
21
22
23
24
25
        starting_point = ift.Field.from_random('normal', domain=space)*10
        covariance_diagonal = ift.Field.from_random(
                                  'uniform', domain=space) + 0.5
        covariance = ift.DiagonalOperator(space, diagonal=covariance_diagonal)
        required_result = ift.Field(space, val=1.)
26

Martin Reinecke's avatar
changes  
Martin Reinecke committed
27
28
29
30
        IC = ift.DefaultIterationController(tol_gradnorm=1e-5)
        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
        assert_allclose(energy.position.val.get_full_data(),
Martin Reinecke's avatar
changes  
Martin Reinecke committed
35
36
                        1./covariance_diagonal.val.get_full_data(),
                        rtol=1e-3, atol=1e-3)