extra.py 11 KB
Newer Older
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/>.
#
Martin Reinecke's avatar
Martin Reinecke committed
14
# Copyright(C) 2013-2020 Max-Planck-Society
15
#
16
# NIFTy is being developed at the Max-Planck-Institut fuer Astrophysik.
17
18

import numpy as np
19
from numpy.testing import assert_
Philipp Arras's avatar
Philipp Arras committed
20

21
from .domain_tuple import DomainTuple
Martin Reinecke's avatar
fix    
Martin Reinecke committed
22
23
from .field import Field
from .linearization import Linearization
24
from .multi_domain import MultiDomain
25
from .multi_field import MultiField
26
from .operators.linear_operator import LinearOperator
Martin Reinecke's avatar
fix    
Martin Reinecke committed
27
from .sugar import from_random
28

Philipp Arras's avatar
Philipp Arras committed
29
30
__all__ = ["consistency_check", "check_jacobian_consistency",
           "assert_allclose"]
31

Philipp Arras's avatar
Philipp Arras committed
32

Philipp Arras's avatar
Philipp Arras committed
33
def assert_allclose(f1, f2, atol, rtol):
Martin Reinecke's avatar
Martin Reinecke committed
34
    if isinstance(f1, Field):
Martin Reinecke's avatar
more    
Martin Reinecke committed
35
36
37
38
        np.testing.assert_allclose(f1.val, f2.val, atol=atol, rtol=rtol)
    else:
        for key, val in f1.items():
            assert_allclose(val, f2[key], atol=atol, rtol=rtol)
Martin Reinecke's avatar
Martin Reinecke committed
39
40


41
42
def _adjoint_implementation(op, domain_dtype, target_dtype, atol, rtol,
                            only_r_linear):
Martin Reinecke's avatar
Martin Reinecke committed
43
44
45
46
47
    needed_cap = op.TIMES | op.ADJOINT_TIMES
    if (op.capability & needed_cap) != needed_cap:
        return
    f1 = from_random("normal", op.domain, dtype=domain_dtype)
    f2 = from_random("normal", op.target, dtype=target_dtype)
Martin Reinecke's avatar
Martin Reinecke committed
48
49
    res1 = f1.s_vdot(op.adjoint_times(f2))
    res2 = op.times(f1).s_vdot(f2)
50
51
    if only_r_linear:
        res1, res2 = res1.real, res2.real
Martin Reinecke's avatar
Martin Reinecke committed
52
53
54
55
56
57
58
59
60
    np.testing.assert_allclose(res1, res2, atol=atol, rtol=rtol)


def _inverse_implementation(op, domain_dtype, target_dtype, atol, rtol):
    needed_cap = op.TIMES | op.INVERSE_TIMES
    if (op.capability & needed_cap) != needed_cap:
        return
    foo = from_random("normal", op.target, dtype=target_dtype)
    res = op(op.inverse_times(foo))
Philipp Arras's avatar
Philipp Arras committed
61
    assert_allclose(res, foo, atol=atol, rtol=rtol)
Martin Reinecke's avatar
Martin Reinecke committed
62
63
64

    foo = from_random("normal", op.domain, dtype=domain_dtype)
    res = op.inverse_times(op(foo))
Philipp Arras's avatar
Philipp Arras committed
65
    assert_allclose(res, foo, atol=atol, rtol=rtol)
Martin Reinecke's avatar
Martin Reinecke committed
66
67


68
69
70
71
def _full_implementation(op, domain_dtype, target_dtype, atol, rtol,
                         only_r_linear):
    _adjoint_implementation(op, domain_dtype, target_dtype, atol, rtol,
                            only_r_linear)
Martin Reinecke's avatar
Martin Reinecke committed
72
73
74
    _inverse_implementation(op, domain_dtype, target_dtype, atol, rtol)


75
def _check_linearity(op, domain_dtype, atol, rtol):
Martin Reinecke's avatar
Martin Reinecke committed
76
77
78
    needed_cap = op.TIMES
    if (op.capability & needed_cap) != needed_cap:
        return
79
80
    fld1 = from_random("normal", op.domain, dtype=domain_dtype)
    fld2 = from_random("normal", op.domain, dtype=domain_dtype)
Martin Reinecke's avatar
Martin Reinecke committed
81
    alpha = np.random.random()  # FIXME: this can break badly with MPI!
82
83
    val1 = op(alpha*fld1+fld2)
    val2 = alpha*op(fld1)+op(fld2)
Philipp Arras's avatar
Philipp Arras committed
84
    assert_allclose(val1, val2, atol=atol, rtol=rtol)
85
86


Philipp Arras's avatar
Philipp Arras committed
87
def _actual_domain_check_linear(op, domain_dtype=None, inp=None):
88
89
90
91
92
93
94
95
96
97
98
    needed_cap = op.TIMES
    if (op.capability & needed_cap) != needed_cap:
        return
    if domain_dtype is not None:
        inp = from_random("normal", op.domain, dtype=domain_dtype)
    elif inp is None:
        raise ValueError('Need to specify either dtype or inp')
    assert_(inp.domain is op.domain)
    assert_(op(inp).domain is op.target)


Philipp Arras's avatar
Philipp Arras committed
99
def _actual_domain_check_nonlinear(op, loc):
100
101
    assert isinstance(loc, (Field, MultiField))
    assert_(loc.domain is op.domain)
Philipp Arras's avatar
Philipp Arras committed
102
103
104
105
106
    for wm in [False, True]:
        lin = Linearization.make_var(loc, wm)
        reslin = op(lin)
        assert_(lin.domain is op.domain)
        assert_(lin.target is op.domain)
Martin Reinecke's avatar
more    
Martin Reinecke committed
107
        assert_(lin.fld.domain is lin.domain)
Philipp Arras's avatar
Philipp Arras committed
108
109
        assert_(reslin.domain is op.domain)
        assert_(reslin.target is op.target)
Martin Reinecke's avatar
more    
Martin Reinecke committed
110
        assert_(reslin.fld.domain is reslin.target)
Philipp Arras's avatar
Philipp Arras committed
111
112
113
        assert_(reslin.target is op.target)
        assert_(reslin.jac.domain is reslin.domain)
        assert_(reslin.jac.target is reslin.target)
Philipp Arras's avatar
Philipp Arras committed
114
        assert_(lin.want_metric == reslin.want_metric)
Philipp Arras's avatar
Philipp Arras committed
115
116
        _actual_domain_check_linear(reslin.jac, inp=loc)
        _actual_domain_check_linear(reslin.jac.adjoint, inp=reslin.jac(loc))
Philipp Arras's avatar
Philipp Arras committed
117
        if reslin.metric is not None:
Philipp Arras's avatar
Philipp Arras committed
118
119
            assert_(reslin.metric.domain is reslin.metric.target)
            assert_(reslin.metric.domain is op.domain)
120
121


122
123
124
def _domain_check(op):
    for dd in [op.domain, op.target]:
        if not isinstance(dd, (DomainTuple, MultiDomain)):
Martin Reinecke's avatar
Martin Reinecke committed
125
126
127
            raise TypeError(
                'The domain and the target of an operator need to',
                'be instances of either DomainTuple or MultiDomain.')
128
129


130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
def _performance_check(op, pos, raise_on_fail):
    class CountingOp(LinearOperator):
        def __init__(self, domain):
            from .sugar import makeDomain
            self._domain = self._target = makeDomain(domain)
            self._capability = self.TIMES | self.ADJOINT_TIMES
            self._count = 0

        def apply(self, x, mode):
            self._count += 1
            return x

        @property
        def count(self):
            return self._count
Philipp Arras's avatar
Philipp Arras committed
145
146
    for wm in [False, True]:
        cop = CountingOp(op.domain)
Philipp Arras's avatar
Philipp Arras committed
147
148
        myop = op @ cop
        myop(pos)
Philipp Arras's avatar
Philipp Arras committed
149
        cond = [cop.count != 1]
Philipp Arras's avatar
Philipp Arras committed
150
        lin = myop(2*Linearization.make_var(pos, wm))
Philipp Arras's avatar
Philipp Arras committed
151
152
153
        cond.append(cop.count != 2)
        lin.jac(pos)
        cond.append(cop.count != 3)
Martin Reinecke's avatar
more    
Martin Reinecke committed
154
        lin.jac.adjoint(lin.fld)
Philipp Arras's avatar
Philipp Arras committed
155
        cond.append(cop.count != 4)
Philipp Arras's avatar
Philipp Arras committed
156
        if lin.metric is not None:
Philipp Arras's avatar
Philipp Arras committed
157
158
159
160
161
162
163
164
165
            lin.metric(pos)
            cond.append(cop.count != 6)
        if any(cond):
            s = 'The operator has a performance problem (want_metric={}).'.format(wm)
            from .logger import logger
            logger.error(s)
            logger.info(cond)
            if raise_on_fail:
                raise RuntimeError(s)
166
167


Martin Reinecke's avatar
Martin Reinecke committed
168
def consistency_check(op, domain_dtype=np.float64, target_dtype=np.float64,
169
                      atol=0, rtol=1e-7, only_r_linear=False):
Reimar H Leike's avatar
Reimar H Leike committed
170
171
172
173
    """
    Checks an operator for algebraic consistency of its capabilities.

    Checks whether times(), adjoint_times(), inverse_times() and
Philipp Arras's avatar
Philipp Arras committed
174
    adjoint_inverse_times() (if in capability list) is implemented
Reimar H Leike's avatar
Reimar H Leike committed
175
    consistently. Additionally, it checks whether the operator is linear.
Philipp Arras's avatar
Philipp Arras committed
176
177
178
179
180

    Parameters
    ----------
    op : LinearOperator
        Operator which shall be checked.
Reimar H Leike's avatar
Reimar H Leike committed
181
    domain_dtype : dtype
Philipp Arras's avatar
Philipp Arras committed
182
183
        The data type of the random vectors in the operator's domain. Default
        is `np.float64`.
Reimar H Leike's avatar
Reimar H Leike committed
184
    target_dtype : dtype
Philipp Arras's avatar
Philipp Arras committed
185
186
187
        The data type of the random vectors in the operator's target. Default
        is `np.float64`.
    atol : float
Martin Reinecke's avatar
Martin Reinecke committed
188
189
        Absolute tolerance for the check. If rtol is specified,
        then satisfying any tolerance will let the check pass.
Reimar H Leike's avatar
Reimar H Leike committed
190
        Default: 0.
Philipp Arras's avatar
Philipp Arras committed
191
    rtol : float
Martin Reinecke's avatar
Martin Reinecke committed
192
193
        Relative tolerance for the check. If atol is specified,
        then satisfying any tolerance will let the check pass.
Reimar H Leike's avatar
Reimar H Leike committed
194
        Default: 0.
195
196
197
    only_r_linear: bool
        set to True if the operator is only R-linear, not C-linear.
        This will relax the adjointness test accordingly.
Philipp Arras's avatar
Philipp Arras committed
198
    """
199
200
    if not isinstance(op, LinearOperator):
        raise TypeError('This test tests only linear operators.')
201
    _domain_check(op)
Philipp Arras's avatar
Philipp Arras committed
202
203
204
205
    _actual_domain_check_linear(op, domain_dtype)
    _actual_domain_check_linear(op.adjoint, target_dtype)
    _actual_domain_check_linear(op.inverse, target_dtype)
    _actual_domain_check_linear(op.adjoint.inverse, domain_dtype)
206
    _check_linearity(op, domain_dtype, atol, rtol)
Martin Reinecke's avatar
Martin Reinecke committed
207
208
209
    _check_linearity(op.adjoint, target_dtype, atol, rtol)
    _check_linearity(op.inverse, target_dtype, atol, rtol)
    _check_linearity(op.adjoint.inverse, domain_dtype, atol, rtol)
210
211
212
213
214
215
    _full_implementation(op, domain_dtype, target_dtype, atol, rtol,
                         only_r_linear)
    _full_implementation(op.adjoint, target_dtype, domain_dtype, atol, rtol,
                         only_r_linear)
    _full_implementation(op.inverse, target_dtype, domain_dtype, atol, rtol,
                         only_r_linear)
Martin Reinecke's avatar
Martin Reinecke committed
216
    _full_implementation(op.adjoint.inverse, domain_dtype, target_dtype, atol,
217
                         rtol, only_r_linear)
Martin Reinecke's avatar
Martin Reinecke committed
218
219


Martin Reinecke's avatar
Martin Reinecke committed
220
def _get_acceptable_location(op, loc, lin):
Martin Reinecke's avatar
more    
Martin Reinecke committed
221
    if not np.isfinite(lin.fld.s_sum()):
Martin Reinecke's avatar
Martin Reinecke committed
222
223
224
225
        raise ValueError('Initial value must be finite')
    dir = from_random("normal", loc.domain)
    dirder = lin.jac(dir)
    if dirder.norm() == 0:
Martin Reinecke's avatar
more    
Martin Reinecke committed
226
        dir = dir * (lin.fld.norm()*1e-5)
Martin Reinecke's avatar
Martin Reinecke committed
227
    else:
Martin Reinecke's avatar
more    
Martin Reinecke committed
228
        dir = dir * (lin.fld.norm()*1e-5/dirder.norm())
Martin Reinecke's avatar
Martin Reinecke committed
229
230
231
232
    # Find a step length that leads to a "reasonable" location
    for i in range(50):
        try:
            loc2 = loc+dir
233
            lin2 = op(Linearization.make_var(loc2, lin.want_metric))
Martin Reinecke's avatar
more    
Martin Reinecke committed
234
            if np.isfinite(lin2.fld.s_sum()) and abs(lin2.fld.s_sum()) < 1e20:
Martin Reinecke's avatar
Martin Reinecke committed
235
236
237
238
239
240
241
242
                break
        except FloatingPointError:
            pass
        dir = dir*0.5
    else:
        raise ValueError("could not find a reasonable initial step")
    return loc2, lin2

Martin Reinecke's avatar
Martin Reinecke committed
243

244
245
246
247
def _linearization_value_consistency(op, loc):
    for wm in [False, True]:
        lin = Linearization.make_var(loc, wm)
        fld0 = op(loc)
Martin Reinecke's avatar
more    
Martin Reinecke committed
248
        fld1 = op(lin).fld
249
250
251
252
        assert_allclose(fld0, fld1, 0, 1e-7)


def check_jacobian_consistency(op, loc, tol=1e-8, ntries=100, perf_check=True):
Martin Reinecke's avatar
Martin Reinecke committed
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
    """
    Checks the Jacobian of an operator against its finite difference
    approximation.

    Computes the Jacobian with finite differences and compares it to the
    implemented Jacobian.

    Parameters
    ----------
    op : Operator
        Operator which shall be checked.
    loc : Field or MultiField
        An Field or MultiField instance which has the same domain
        as op. The location at which the gradient is checked
    tol : float
        Tolerance for the check.
269
270
    perf_check : Boolean
        Do performance check. May be disabled for very unimportant operators.
Martin Reinecke's avatar
Martin Reinecke committed
271
    """
272
    _domain_check(op)
273
    _actual_domain_check_nonlinear(op, loc)
274
275
    _performance_check(op, loc, bool(perf_check))
    _linearization_value_consistency(op, loc)
Martin Reinecke's avatar
Martin Reinecke committed
276
    for _ in range(ntries):
277
        lin = op(Linearization.make_var(loc))
Martin Reinecke's avatar
Martin Reinecke committed
278
        loc2, lin2 = _get_acceptable_location(op, loc, lin)
Martin Reinecke's avatar
Martin Reinecke committed
279
        dir = loc2-loc
Martin Reinecke's avatar
Martin Reinecke committed
280
281
        locnext = loc2
        dirnorm = dir.norm()
Martin Reinecke's avatar
Martin Reinecke committed
282
        hist = []
Martin Reinecke's avatar
Martin Reinecke committed
283
284
        for i in range(50):
            locmid = loc + 0.5*dir
285
            linmid = op(Linearization.make_var(locmid))
Martin Reinecke's avatar
Martin Reinecke committed
286
            dirder = linmid.jac(dir)
Martin Reinecke's avatar
more    
Martin Reinecke committed
287
            numgrad = (lin2.fld-lin.fld)
Martin Reinecke's avatar
Martin Reinecke committed
288
            xtol = tol * dirder.norm() / np.sqrt(dirder.size)
Martin Reinecke's avatar
Martin Reinecke committed
289
290
            hist.append((numgrad-dirder).norm())
#            print(len(hist),hist[-1])
Martin Reinecke's avatar
Martin Reinecke committed
291
            if (abs(numgrad-dirder) <= xtol).s_all():
Martin Reinecke's avatar
Martin Reinecke committed
292
293
294
                break
            dir = dir*0.5
            dirnorm *= 0.5
Martin Reinecke's avatar
Martin Reinecke committed
295
            loc2, lin2 = locmid, linmid
Martin Reinecke's avatar
Martin Reinecke committed
296
        else:
Martin Reinecke's avatar
Martin Reinecke committed
297
            print(hist)
Martin Reinecke's avatar
Martin Reinecke committed
298
299
            raise ValueError("gradient and value seem inconsistent")
        loc = locnext