test_kl.py 3.68 KB
Newer Older
Philipp Arras's avatar
Philipp Arras committed
1
2
3
4
5
6
7
8
9
10
11
12
13
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
Philipp Arras's avatar
Philipp Arras committed
14
# Copyright(C) 2013-2020 Max-Planck-Society
Philipp Arras's avatar
Philipp Arras committed
15
16
17
#
# NIFTy is being developed at the Max-Planck-Institut fuer Astrophysik.

Philipp Arras's avatar
Philipp Arras committed
18
import numpy as np
Philipp Arras's avatar
Philipp Arras committed
19
20
import pytest
from mpi4py import MPI
Philipp Arras's avatar
Philipp Arras committed
21
from numpy.testing import assert_, assert_equal, assert_raises
Philipp Arras's avatar
Philipp Arras committed
22

Martin Reinecke's avatar
Martin Reinecke committed
23
import nifty7 as ift
Philipp Arras's avatar
Philipp Arras committed
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

from ..common import setup_function, teardown_function

comm = MPI.COMM_WORLD
ntask = comm.Get_size()
rank = comm.Get_rank()
master = (rank == 0)
mpi = ntask > 1

pmp = pytest.mark.parametrize
pms = pytest.mark.skipif


@pms(ntask != 2, reason="requires exactly two mpi tasks")
@pmp('constants', ([], ['a'], ['b'], ['a', 'b']))
@pmp('point_estimates', ([], ['a'], ['b'], ['a', 'b']))
@pmp('mirror_samples', (False, True))
@pmp('mode', (0, 1))
Philipp Arras's avatar
Philipp Arras committed
42
43
@pmp('mf', (False, True))
def test_kl(constants, point_estimates, mirror_samples, mode, mf):
Philipp Arras's avatar
Philipp Arras committed
44
45
    if not mf and (len(point_estimates) != 0 or len(constants) != 0):
        return
Philipp Arras's avatar
Philipp Arras committed
46
    dom = ift.RGSpace((12,), (2.12))
Philipp Arras's avatar
Philipp Arras committed
47
48
49
    op = ift.HarmonicSmoothingOperator(dom, 3)
    if mf:
        op = ift.ducktape(dom, None, 'a')*(op.ducktape('b'))
Philipp Arras's avatar
Philipp Arras committed
50
    lh = ift.GaussianEnergy(domain=op.target, sampling_dtype=np.float64) @ op
Philipp Arras's avatar
Philipp Arras committed
51
52
    ic = ift.GradientNormController(iteration_limit=5)
    h = ift.StandardHamiltonian(lh, ic_samp=ic)
53
    mean0 = ift.from_random(h.domain, 'normal')
Philipp Arras's avatar
Philipp Arras committed
54
55
56
57
58
59
60
    nsamps = 2
    args = {'constants': constants,
            'point_estimates': point_estimates,
            'mirror_samples': mirror_samples,
            'n_samples': 2,
            'mean': mean0,
            'hamiltonian': h}
Philipp Arras's avatar
Philipp Arras committed
61
62
    if isinstance(mean0, ift.MultiField) and set(point_estimates) == set(mean0.keys()):
        with assert_raises(RuntimeError):
63
            ift.MetricGaussianKL.make(**args, comm=comm)
Philipp Arras's avatar
Philipp Arras committed
64
        return
Philipp Arras's avatar
Philipp Arras committed
65
    if mode == 0:
66
        kl0 = ift.MetricGaussianKL.make(**args, comm=comm)
Philipp Arras's avatar
Philipp Arras committed
67
        locsamp = kl0._local_samples
68
69
70
71
        if isinstance(mean0, ift.MultiField):
            _, tmph = h.simplify_for_constant_input(mean0.extract_by_keys(constants))
        else:
            tmph = h
72
        kl1 = ift.MetricGaussianKL(mean0.extract(tmph.domain), tmph, 2, mirror_samples, comm, locsamp, False, True)
Philipp Arras's avatar
Philipp Arras committed
73
    elif mode == 1:
74
        kl0 = ift.MetricGaussianKL.make(**args)
Philipp Arras's avatar
Philipp Arras committed
75
76
77
78
        samples = kl0._local_samples
        ii = len(samples)//2
        slc = slice(None, ii) if rank == 0 else slice(ii, None)
        locsamp = samples[slc]
79
80
81
82
        if isinstance(mean0, ift.MultiField):
            _, tmph = h.simplify_for_constant_input(mean0.extract_by_keys(constants))
        else:
            tmph = h
83
        kl1 = ift.MetricGaussianKL(mean0.extract(tmph.domain), tmph, 2, mirror_samples, comm, locsamp, False, True)
Philipp Arras's avatar
Philipp Arras committed
84

Philipp Arras's avatar
Philipp Arras committed
85
86
87
88
89
    # Test number of samples
    expected_nsamps = 2*nsamps if mirror_samples else nsamps
    assert_(len(tuple(kl0.samples)) == expected_nsamps)
    assert_(len(tuple(kl1.samples)) == expected_nsamps)

Philipp Arras's avatar
Philipp Arras committed
90
    # Test value
Philipp Arras's avatar
Philipp Arras committed
91
    assert_equal(kl0.value, kl1.value)
Philipp Arras's avatar
Philipp Arras committed
92
93

    # Test gradient
Philipp Arras's avatar
Philipp Arras committed
94
    if mf:
95
        for kk in kl0.gradient.domain.keys():
Philipp Arras's avatar
Philipp Arras committed
96
97
98
99
100
            res0 = kl0.gradient[kk].val
            res1 = kl1.gradient[kk].val
            assert_equal(res0, res1)
    else:
        assert_equal(kl0.gradient.val, kl1.gradient.val)