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

3
import numpy as np
Matevz, Sraml (sraml)'s avatar
Matevz, Sraml (sraml) committed
4
from numpy.testing import assert_equal, assert_almost_equal
Matevz, Sraml (sraml)'s avatar
Matevz, Sraml (sraml) committed
5

6
7
from nifty import Field, DiagonalOperator, RGSpace, HPSpace
from nifty import ConjugateGradient
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
41
42
43
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()

        (position, convergence) = minimizer(A=covariance, x0=starting_point,
                                            b=required_result)
Matevz, Sraml (sraml)'s avatar
Matevz, Sraml (sraml) committed
44

45
46
47
        assert_almost_equal(position.val.get_full_data(),
                            1./covariance_diagonal.val.get_full_data(),
                            decimal=3)