test_minimizers.py 1.36 KB
Newer Older
Matevz, Sraml (sraml)'s avatar
Matevz, Sraml (sraml) committed
1
import unittest
2
import numpy as np
Martin Reinecke's avatar
changes  
Martin Reinecke committed
3
from numpy.testing import assert_allclose
Martin Reinecke's avatar
Martin Reinecke committed
4
import nifty2go as ift
Martin Reinecke's avatar
changes  
Martin Reinecke committed
5
from itertools import product
Matevz, Sraml (sraml)'s avatar
Matevz, Sraml (sraml) committed
6
from test.common import expand
Martin Reinecke's avatar
Martin Reinecke committed
7
from nifty2go.dobj import to_ndarray as to_np
Matevz, Sraml (sraml)'s avatar
Matevz, Sraml (sraml) committed
8

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


Martin Reinecke's avatar
changes  
Martin Reinecke committed
14
class Test_Minimizers(unittest.TestCase):
15

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

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

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