test_minimizers.py 1.8 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
Martin Reinecke committed
4
from numpy.testing import assert_equal, assert_allclose
Matevz, Sraml (sraml)'s avatar
Matevz, Sraml (sraml) committed
5

6
from nifty import Field, DiagonalOperator, RGSpace, HPSpace
Martin Reinecke's avatar
Martin Reinecke committed
7
from nifty import ConjugateGradient, QuadraticEnergy
Matevz, Sraml (sraml)'s avatar
Matevz, Sraml (sraml) committed
8 9 10

from test.common import expand

11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
spaces = [RGSpace([1024, 1024], distances=0.123), HPSpace(32)]


class Test_ConjugateGradient(unittest.TestCase):

    def test_interface(self):
        iteration_limit = 100
        convergence_level = 4
        convergence_tolerance = 1E-6
        callback = lambda z: z
        minimizer = ConjugateGradient(
                                iteration_limit=iteration_limit,
                                convergence_tolerance=convergence_tolerance,
                                convergence_level=convergence_level,
                                callback=callback)

        assert_equal(minimizer.iteration_limit, iteration_limit)
        assert_equal(minimizer.convergence_level, convergence_level)
        assert_equal(minimizer.convergence_tolerance, convergence_tolerance)
        assert(minimizer.callback is callback)

    @expand([[space] for space in spaces])
    def test_minimization(self, space):
        np.random.seed(42)
        starting_point = Field.from_random('normal', domain=space)*10
        covariance_diagonal = Field.from_random('uniform', domain=space) + 0.5
        covariance = DiagonalOperator(space, diagonal=covariance_diagonal)
        required_result = Field(space, val=1.)

        minimizer = ConjugateGradient()
Martin Reinecke's avatar
Martin Reinecke committed
41 42
        energy = QuadraticEnergy(A=covariance, b=required_result,
                                 position=starting_point)
43

Martin Reinecke's avatar
Martin Reinecke committed
44
        (energy, convergence) = minimizer(energy)
Matevz, Sraml (sraml)'s avatar
Matevz, Sraml (sraml) committed
45

Martin Reinecke's avatar
Martin Reinecke committed
46
        assert_allclose(energy.position.val.get_full_data(),
47
                            1./covariance_diagonal.val.get_full_data(),
Martin Reinecke's avatar
Martin Reinecke committed
48
                            rtol=1e-3)