extra.py 20 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/>.
#
14
# Copyright(C) 2013-2021 Max-Planck-Society
15
#
16
# NIFTy is being developed at the Max-Planck-Institut fuer Astrophysik.
17

Philipp Arras's avatar
Philipp Arras committed
18
19
from itertools import combinations

20
import numpy as np
Philipp Arras's avatar
Philipp Arras committed
21

22
from .domain_tuple import DomainTuple
Martin Reinecke's avatar
fix    
Martin Reinecke committed
23
24
from .field import Field
from .linearization import Linearization
25
from .multi_domain import MultiDomain
26
from .multi_field import MultiField
Philipp Arras's avatar
Philipp Arras committed
27
from .operators.adder import Adder
Philipp Arras's avatar
Philipp Arras committed
28
from .operators.endomorphic_operator import EndomorphicOperator
29
from .operators.energy_operators import EnergyOperator
30
from .operators.linear_operator import LinearOperator
Philipp Arras's avatar
Philipp Arras committed
31
from .operators.operator import Operator
Philipp Arras's avatar
Philipp Arras committed
32
33
from .operators.scaling_operator import ScalingOperator
from .probing import StatCalculator
Philipp Arras's avatar
Philipp Arras committed
34
from .sugar import from_random, full, is_fieldlike, is_operator
35
from .utilities import myassert
36

Philipp Arras's avatar
Philipp Arras committed
37
__all__ = ["check_linear_operator", "check_operator", "assert_allclose", "minisanity"]
38

Philipp Arras's avatar
Philipp Arras committed
39

Philipp Arras's avatar
Philipp Arras committed
40
def check_linear_operator(op, domain_dtype=np.float64, target_dtype=np.float64,
Philipp Arras's avatar
Philipp Arras committed
41
                          atol=1e-12, rtol=1e-12, only_r_linear=False):
Philipp Arras's avatar
Philipp Arras committed
42
    """Checks an operator for algebraic consistency of its capabilities.
Philipp Arras's avatar
Philipp Arras committed
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75

    Checks whether times(), adjoint_times(), inverse_times() and
    adjoint_inverse_times() (if in capability list) is implemented
    consistently. Additionally, it checks whether the operator is linear.

    Parameters
    ----------
    op : LinearOperator
        Operator which shall be checked.
    domain_dtype : dtype
        The data type of the random vectors in the operator's domain. Default
        is `np.float64`.
    target_dtype : dtype
        The data type of the random vectors in the operator's target. Default
        is `np.float64`.
    atol : float
        Absolute tolerance for the check. If rtol is specified,
        then satisfying any tolerance will let the check pass.
        Default: 0.
    rtol : float
        Relative tolerance for the check. If atol is specified,
        then satisfying any tolerance will let the check pass.
        Default: 0.
    only_r_linear: bool
        set to True if the operator is only R-linear, not C-linear.
        This will relax the adjointness test accordingly.
    """
    if not isinstance(op, LinearOperator):
        raise TypeError('This test tests only linear operators.')
    _domain_check_linear(op, domain_dtype)
    _domain_check_linear(op.adjoint, target_dtype)
    _domain_check_linear(op.inverse, target_dtype)
    _domain_check_linear(op.adjoint.inverse, domain_dtype)
Philipp Arras's avatar
Philipp Arras committed
76
77
78
79
    _purity_check(op, from_random(op.domain, dtype=domain_dtype))
    _purity_check(op.adjoint.inverse, from_random(op.domain, dtype=domain_dtype))
    _purity_check(op.adjoint, from_random(op.target, dtype=target_dtype))
    _purity_check(op.inverse, from_random(op.target, dtype=target_dtype))
Philipp Arras's avatar
Philipp Arras committed
80
81
82
83
84
85
86
87
88
89
90
91
    _check_linearity(op, domain_dtype, atol, rtol)
    _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)
    _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)
    _full_implementation(op.adjoint.inverse, domain_dtype, target_dtype, atol,
                         rtol, only_r_linear)
92
93
94
95
    _check_sqrt(op, domain_dtype)
    _check_sqrt(op.adjoint, target_dtype)
    _check_sqrt(op.inverse, target_dtype)
    _check_sqrt(op.adjoint.inverse, domain_dtype)
Philipp Arras's avatar
Philipp Arras committed
96
97


Philipp Arras's avatar
Philipp Arras committed
98
def check_operator(op, loc, tol=1e-12, ntries=100, perf_check=True,
99
                   only_r_differentiable=True, metric_sampling=True):
Philipp Arras's avatar
Philipp Arras committed
100
    """Performs various checks of the implementation of linear and nonlinear
Philipp Arras's avatar
Philipp Arras committed
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
    operators.

    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.
    perf_check : Boolean
        Do performance check. May be disabled for very unimportant operators.
    only_r_differentiable : Boolean
        Jacobians of C-differentiable operators need to be C-linear.
        Default: True
    metric_sampling: Boolean
        If op is an EnergyOperator, metric_sampling determines whether the
        test shall try to sample from the metric or not.
    """
Reimar Leike's avatar
Reimar Leike committed
124
125
    if not isinstance(op, Operator):
        raise TypeError('This test tests only (nonlinear) operators.')
Philipp Arras's avatar
Philipp Arras committed
126
    _domain_check_nonlinear(op, loc)
Philipp Arras's avatar
Philipp Arras committed
127
    _purity_check(op, loc)
Philipp Arras's avatar
Philipp Arras committed
128
129
    _performance_check(op, loc, bool(perf_check))
    _linearization_value_consistency(op, loc)
130
131
    _jac_vs_finite_differences(op, loc, np.sqrt(tol), ntries,
                               only_r_differentiable)
Philipp Arras's avatar
Philipp Arras committed
132
    _check_nontrivial_constant(op, loc, tol, ntries, only_r_differentiable,
133
                               metric_sampling)
Philipp Arras's avatar
Philipp Arras committed
134
135


136
def assert_allclose(f1, f2, atol=0, rtol=1e-7):
Martin Reinecke's avatar
Martin Reinecke committed
137
    if isinstance(f1, Field):
Martin Reinecke's avatar
stage2    
Martin Reinecke committed
138
        return np.testing.assert_allclose(f1.val, f2.val, atol=atol, rtol=rtol)
Martin Reinecke's avatar
Martin Reinecke committed
139
    for key, val in f1.items():
Philipp Arras's avatar
Philipp Arras committed
140
        assert_allclose(val, f2[key], atol=atol, rtol=rtol)
Martin Reinecke's avatar
Martin Reinecke committed
141
142


Philipp Arras's avatar
Philipp Arras committed
143
144
145
146
147
148
149
def assert_equal(f1, f2):
    if isinstance(f1, Field):
        return np.testing.assert_equal(f1.val, f2.val)
    for key, val in f1.items():
        assert_equal(val, f2[key])


150
151
def _adjoint_implementation(op, domain_dtype, target_dtype, atol, rtol,
                            only_r_linear):
Martin Reinecke's avatar
Martin Reinecke committed
152
153
154
    needed_cap = op.TIMES | op.ADJOINT_TIMES
    if (op.capability & needed_cap) != needed_cap:
        return
155
156
    f1 = from_random(op.domain, "normal", dtype=domain_dtype)
    f2 = from_random(op.target, "normal", dtype=target_dtype)
Martin Reinecke's avatar
Martin Reinecke committed
157
158
    res1 = f1.s_vdot(op.adjoint_times(f2))
    res2 = op.times(f1).s_vdot(f2)
159
160
    if only_r_linear:
        res1, res2 = res1.real, res2.real
Martin Reinecke's avatar
Martin Reinecke committed
161
162
163
164
165
166
167
    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
168
    foo = from_random(op.target, "normal", dtype=target_dtype)
Martin Reinecke's avatar
Martin Reinecke committed
169
    res = op(op.inverse_times(foo))
Philipp Arras's avatar
Philipp Arras committed
170
    assert_allclose(res, foo, atol=atol, rtol=rtol)
Martin Reinecke's avatar
Martin Reinecke committed
171

172
    foo = from_random(op.domain, "normal", dtype=domain_dtype)
Martin Reinecke's avatar
Martin Reinecke committed
173
    res = op.inverse_times(op(foo))
Philipp Arras's avatar
Philipp Arras committed
174
    assert_allclose(res, foo, atol=atol, rtol=rtol)
Martin Reinecke's avatar
Martin Reinecke committed
175
176


177
178
179
180
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
181
182
183
    _inverse_implementation(op, domain_dtype, target_dtype, atol, rtol)


184
def _check_linearity(op, domain_dtype, atol, rtol):
Martin Reinecke's avatar
Martin Reinecke committed
185
186
187
    needed_cap = op.TIMES
    if (op.capability & needed_cap) != needed_cap:
        return
188
189
    fld1 = from_random(op.domain, "normal", dtype=domain_dtype)
    fld2 = from_random(op.domain, "normal", dtype=domain_dtype)
Martin Reinecke's avatar
Martin Reinecke committed
190
    alpha = 0.42
191
192
    val1 = op(alpha*fld1+fld2)
    val2 = alpha*op(fld1)+op(fld2)
Philipp Arras's avatar
Philipp Arras committed
193
    assert_allclose(val1, val2, atol=atol, rtol=rtol)
194
195


Philipp Arras's avatar
Philipp Arras committed
196
197
def _domain_check_linear(op, domain_dtype=None, inp=None):
    _domain_check(op)
198
199
200
201
    needed_cap = op.TIMES
    if (op.capability & needed_cap) != needed_cap:
        return
    if domain_dtype is not None:
202
        inp = from_random(op.domain, "normal", dtype=domain_dtype)
203
204
    elif inp is None:
        raise ValueError('Need to specify either dtype or inp')
205
206
    myassert(inp.domain is op.domain)
    myassert(op(inp).domain is op.target)
207
208


209
def _check_sqrt(op, domain_dtype):
Philipp Arras's avatar
Philipp Arras committed
210
    if not isinstance(op, EndomorphicOperator):
211
212
213
214
215
216
217
        try:
            op.get_sqrt()
            raise RuntimeError("Operator implements get_sqrt() although it is not an endomorphic operator.")
        except AttributeError:
            return
    try:
        sqop = op.get_sqrt()
218
    except (NotImplementedError, ValueError):
219
220
221
222
223
224
225
        return
    fld = from_random(op.domain, dtype=domain_dtype)
    a = op(fld)
    b = (sqop.adjoint @ sqop)(fld)
    return assert_allclose(a, b, rtol=1e-15)


Philipp Arras's avatar
Philipp Arras committed
226
227
def _domain_check_nonlinear(op, loc):
    _domain_check(op)
228
229
    myassert(isinstance(loc, (Field, MultiField)))
    myassert(loc.domain is op.domain)
Philipp Arras's avatar
Philipp Arras committed
230
231
232
    for wm in [False, True]:
        lin = Linearization.make_var(loc, wm)
        reslin = op(lin)
233
234
235
236
237
238
239
240
241
242
        myassert(lin.domain is op.domain)
        myassert(lin.target is op.domain)
        myassert(lin.val.domain is lin.domain)
        myassert(reslin.domain is op.domain)
        myassert(reslin.target is op.target)
        myassert(reslin.val.domain is reslin.target)
        myassert(reslin.target is op.target)
        myassert(reslin.jac.domain is reslin.domain)
        myassert(reslin.jac.target is reslin.target)
        myassert(lin.want_metric == reslin.want_metric)
Philipp Arras's avatar
Philipp Arras committed
243
244
        _domain_check_linear(reslin.jac, inp=loc)
        _domain_check_linear(reslin.jac.adjoint, inp=reslin.jac(loc))
Philipp Arras's avatar
Philipp Arras committed
245
        if reslin.metric is not None:
246
247
            myassert(reslin.metric.domain is reslin.metric.target)
            myassert(reslin.metric.domain is op.domain)
248
249


250
251
252
def _domain_check(op):
    for dd in [op.domain, op.target]:
        if not isinstance(dd, (DomainTuple, MultiDomain)):
Martin Reinecke's avatar
Martin Reinecke committed
253
254
255
            raise TypeError(
                'The domain and the target of an operator need to',
                'be instances of either DomainTuple or MultiDomain.')
256
257


258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
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
273
274
    for wm in [False, True]:
        cop = CountingOp(op.domain)
Philipp Arras's avatar
Philipp Arras committed
275
276
        myop = op @ cop
        myop(pos)
Philipp Arras's avatar
Philipp Arras committed
277
        cond = [cop.count != 1]
278
        lin = myop(Linearization.make_var(pos, wm))
Philipp Arras's avatar
Philipp Arras committed
279
280
281
282
283
        cond.append(cop.count != 2)
        lin.jac(pos)
        cond.append(cop.count != 3)
        lin.jac.adjoint(lin.val)
        cond.append(cop.count != 4)
Philipp Arras's avatar
Philipp Arras committed
284
        if lin.metric is not None:
Philipp Arras's avatar
Philipp Arras committed
285
286
287
288
289
290
291
292
293
            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)
294
295


Philipp Arras's avatar
Philipp Arras committed
296
297
298
299
300
301
302
303
def _purity_check(op, pos):
    if isinstance(op, LinearOperator) and (op.capability & op.TIMES) != op.TIMES:
        return
    res0 = op(pos)
    res1 = op(pos)
    assert_equal(res0, res1)


Martin Reinecke's avatar
Martin Reinecke committed
304
def _get_acceptable_location(op, loc, lin):
Martin Reinecke's avatar
Martin Reinecke committed
305
    if not np.isfinite(lin.val.s_sum()):
Martin Reinecke's avatar
Martin Reinecke committed
306
        raise ValueError('Initial value must be finite')
307
308
    direction = from_random(loc.domain, dtype=loc.dtype)
    dirder = lin.jac(direction)
Martin Reinecke's avatar
Martin Reinecke committed
309
    if dirder.norm() == 0:
310
        direction = direction * (lin.val.norm() * 1e-5)
Martin Reinecke's avatar
Martin Reinecke committed
311
    else:
312
        direction = direction * (lin.val.norm() * 1e-5 / dirder.norm())
Martin Reinecke's avatar
Martin Reinecke committed
313
314
315
    # Find a step length that leads to a "reasonable" location
    for i in range(50):
        try:
316
            loc2 = loc + direction
317
            lin2 = op(Linearization.make_var(loc2, lin.want_metric))
Martin Reinecke's avatar
Martin Reinecke committed
318
            if np.isfinite(lin2.val.s_sum()) and abs(lin2.val.s_sum()) < 1e20:
Martin Reinecke's avatar
Martin Reinecke committed
319
320
321
                break
        except FloatingPointError:
            pass
322
        direction = direction * 0.5
Martin Reinecke's avatar
Martin Reinecke committed
323
324
325
326
    else:
        raise ValueError("could not find a reasonable initial step")
    return loc2, lin2

Martin Reinecke's avatar
Martin Reinecke committed
327

328
329
330
331
332
333
334
335
def _linearization_value_consistency(op, loc):
    for wm in [False, True]:
        lin = Linearization.make_var(loc, wm)
        fld0 = op(loc)
        fld1 = op(lin).val
        assert_allclose(fld0, fld1, 0, 1e-7)


Philipp Arras's avatar
Philipp Arras committed
336
def _check_nontrivial_constant(op, loc, tol, ntries, only_r_differentiable,
337
                               metric_sampling):
Philipp Arras's avatar
Philipp Arras committed
338
    if isinstance(op.domain, DomainTuple):
339
        return
Philipp Arras's avatar
Philipp Arras committed
340
    keys = op.domain.keys()
341
    combis = []
342
    if len(keys) > 4:
343
        from .logger import logger
344
        logger.warning('Operator domain has more than 4 keys.')
345
        logger.warning('Check derivatives only with one constant key at a time.')
346
        combis = [[kk] for kk in keys]
347
348
349
    else:
        for ll in range(1, len(keys)):
            combis.extend(list(combinations(keys, ll)))
350
351
352
353
354
355
356
    for cstkeys in combis:
        varkeys = set(keys) - set(cstkeys)
        cstloc = loc.extract_by_keys(cstkeys)
        varloc = loc.extract_by_keys(varkeys)

        val0 = op(loc)
        _, op0 = op.simplify_for_constant_input(cstloc)
357
        myassert(op0.domain is varloc.domain)
358
359
360
361
362
363
364
365
        val1 = op0(varloc)
        assert_equal(val0, val1)

        lin = Linearization.make_partial_var(loc, cstkeys, want_metric=True)
        lin0 = Linearization.make_var(varloc, want_metric=True)
        oplin0 = op0(lin0)
        oplin = op(lin)

366
        myassert(oplin.jac.target is oplin0.jac.target)
367
        rndinp = from_random(oplin.jac.target, dtype=oplin.val.dtype)
368
369
        assert_allclose(oplin.jac.adjoint(rndinp).extract(varloc.domain),
                        oplin0.jac.adjoint(rndinp), 1e-13, 1e-13)
370
371
372
        foo = oplin.jac.adjoint(rndinp).extract(cstloc.domain)
        assert_equal(foo, 0*foo)

373
374
        if isinstance(op, EnergyOperator) and metric_sampling:
            oplin.metric.draw_sample()
375

376
377
        # _jac_vs_finite_differences(op0, varloc, np.sqrt(tol), ntries,
        #                            only_r_differentiable)
Philipp Arras's avatar
Philipp Arras committed
378
379
380


def _jac_vs_finite_differences(op, loc, tol, ntries, only_r_differentiable):
Martin Reinecke's avatar
Martin Reinecke committed
381
    for _ in range(ntries):
382
        lin = op(Linearization.make_var(loc))
Martin Reinecke's avatar
Martin Reinecke committed
383
        loc2, lin2 = _get_acceptable_location(op, loc, lin)
384
        direction = loc2 - loc
Martin Reinecke's avatar
Martin Reinecke committed
385
        locnext = loc2
386
        dirnorm = direction.norm()
Martin Reinecke's avatar
Martin Reinecke committed
387
        hist = []
Martin Reinecke's avatar
Martin Reinecke committed
388
        for i in range(50):
389
            locmid = loc + 0.5 * direction
390
            linmid = op(Linearization.make_var(locmid))
391
392
            dirder = linmid.jac(direction)
            numgrad = (lin2.val - lin.val)
Martin Reinecke's avatar
Martin Reinecke committed
393
            xtol = tol * dirder.norm() / np.sqrt(dirder.size)
394
395
396
            hist.append((numgrad - dirder).norm())
            # print(len(hist),hist[-1])
            if (abs(numgrad - dirder) <= xtol).s_all():
Martin Reinecke's avatar
Martin Reinecke committed
397
                break
398
            direction = direction * 0.5
Martin Reinecke's avatar
Martin Reinecke committed
399
            dirnorm *= 0.5
Martin Reinecke's avatar
Martin Reinecke committed
400
            loc2, lin2 = locmid, linmid
Martin Reinecke's avatar
Martin Reinecke committed
401
        else:
Martin Reinecke's avatar
Martin Reinecke committed
402
            print(hist)
Martin Reinecke's avatar
Martin Reinecke committed
403
404
            raise ValueError("gradient and value seem inconsistent")
        loc = locnext
Philipp Arras's avatar
Philipp Arras committed
405
406
        check_linear_operator(linmid.jac, domain_dtype=loc.dtype,
                              target_dtype=dirder.dtype,
407
408
                              only_r_linear=only_r_differentiable,
                              atol=tol**2, rtol=tol**2)
Philipp Arras's avatar
Philipp Arras committed
409
410


Philipp Arras's avatar
Philipp Arras committed
411
def minisanity(data, metric_at_pos, modeldata_operator, mean, samples=None):
Philipp Arras's avatar
Philipp Arras committed
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
    """Log information about the current fit quality and prior compatibility.

    Log a table with fitting information for the likelihood and the prior.
    Assume that the variables in `energy.position.domain` are standard-normal
    distributed a priori. The table contains the reduced chi^2 value, the mean
    and the number of degrees of freedom for every key of a `MultiDomain`. If
    the domain is a `DomainTuple`, the displayed key is `<None>`.

    If everything is consistent the reduced chi^2 values should be close to one
    and the mean of the data residuals close to zero. If the reduced chi^2 value
    in latent space is significantly bigger than one and only one degree of
    freedom is present, the mean column gives an indication in which direction
    to change the respective hyper parameters.

    Ignore all NaN entries in the target of `modeldata_operator` and in `data`.
    Print reduced chi-square values above 2 and 5 in orange and red,
    respectively.

    Parameters
    ----------
    data : Field or MultiField
        Data which is subtracted from the output of `model_data`.

Philipp Arras's avatar
Philipp Arras committed
435
436
437
438
    metric_at_pos : function
        Function which takes a `Field` or `MultiField` in the domain of `mean`
        and returns an endomorphic operator which applies the inverse of the
        noise covariance in the domain of `data`.
Philipp Arras's avatar
Philipp Arras committed
439
440

    model_data : Operator
Philipp Arras's avatar
Philipp Arras committed
441
442
443
444
445
        Operator which generates model data.

    mean : Field or MultiField
        Mean of input of `model_data`.

Philipp Arras's avatar
Philipp Arras committed
446
    samples : iterable of Field or MultiField, optional
Philipp Arras's avatar
Philipp Arras committed
447
448
449
450
451
452
        Residual samples around `mean`. Default: no samples.

    Note
    ----
    For computing the reduced chi^2 values and the normalized residuals, the
    metric at `mean` is used.
Philipp Arras's avatar
Philipp Arras committed
453
454

    """
Philipp Arras's avatar
Philipp Arras committed
455
    from .logger import logger
Philipp Arras's avatar
Philipp Arras committed
456
    if not (
Philipp Arras's avatar
Philipp Arras committed
457
        is_operator(modeldata_operator)
Philipp Arras's avatar
Philipp Arras committed
458
        and is_fieldlike(data)
Philipp Arras's avatar
Philipp Arras committed
459
        and is_fieldlike(mean)
Philipp Arras's avatar
Philipp Arras committed
460
461
462
    ):
        raise TypeError
    keylen = 18
Philipp Arras's avatar
Philipp Arras committed
463
    for dom in [data.domain, mean.domain]:
Philipp Arras's avatar
Philipp Arras committed
464
465
466
        if isinstance(dom, MultiDomain):
            keylen = max([max(map(len, dom.keys())), keylen])
    keylen = min([keylen, 42])
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
    op0 = metric_at_pos(mean).get_sqrt() @ Adder(data, neg=True) @ modeldata_operator
    op1 = ScalingOperator(mean.domain, 1)
    if not isinstance(op0.target, MultiDomain):
        op0 = op0.ducktape_left("<None>")
    if not isinstance(op1.target, MultiDomain):
        op1 = op1.ducktape_left("<None>")
    s = [full(mean.domain, 0.0)] if samples is None else samples
    xop = op0, op1
    xkeys = op0.target.keys(), op1.target.keys()
    xredchisq, xscmean, xndof = 2*[None], 2*[None], 2*[None]
    for aa in [0, 1]:
        xredchisq[aa] = {kk: StatCalculator() for kk in xkeys[aa]}
        xscmean[aa] = {kk: StatCalculator() for kk in xkeys[aa]}
        xndof[aa] = {}
    for ii, ss in enumerate(s):
        for aa in [0, 1]:
            rr = xop[aa].force(mean.unite(ss))
            for kk in xkeys[aa]:
                xredchisq[aa][kk].add(np.nansum(abs(rr[kk].val) ** 2) / rr[kk].size)
                xscmean[aa][kk].add(np.nanmean(rr[kk].val))
                xndof[aa][kk] = rr[kk].size - np.sum(np.isnan(rr[kk].val))

    s0 = _tableentries(xredchisq[0], xscmean[0], xndof[0], keylen)
    s1 = _tableentries(xredchisq[1], xscmean[1], xndof[1], keylen)
Philipp Arras's avatar
Philipp Arras committed
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513

    f = logger.info
    n = 38 + keylen
    f(n * "=")
    f(
        (keylen + 2) * " "
        + "{:>11}".format("reduced χ²")
        + "{:>14}".format("mean")
        + "{:>11}".format("# dof")
    )
    f(n * "-")
    f("Data residuals\n" + s0)
    f("Latent space\n" + s1)
    f(n * "=")


class _bcolors:
    WARNING = "\033[33m"
    FAIL = "\033[31m"
    ENDC = "\033[0m"
    BOLD = "\033[1m"


514
def _tableentries(redchisq, scmean, ndof, keylen):
Philipp Arras's avatar
Philipp Arras committed
515
516
517
518
519
520
521
522
523
524
525
    out = ""
    for kk in redchisq.keys():
        if len(kk) > keylen:
            out += "  " + kk[: keylen - 1] + "…"
        else:
            out += "  " + kk.ljust(keylen)
        foo = f"{redchisq[kk].mean:.1f}"
        try:
            foo += f" ± {np.sqrt(redchisq[kk].var):.1f}"
        except RuntimeError:
            pass
526
        if redchisq[kk].mean > 5 or redchisq[kk].mean < 1/5:
Philipp Arras's avatar
Philipp Arras committed
527
            out += _bcolors.FAIL + _bcolors.BOLD + f"{foo:>11}" + _bcolors.ENDC
528
        elif redchisq[kk].mean > 2 or redchisq[kk].mean < 1/2:
Philipp Arras's avatar
Philipp Arras committed
529
530
531
532
            out += _bcolors.WARNING + _bcolors.BOLD + f"{foo:>11}" + _bcolors.ENDC
        else:
            out += f"{foo:>11}"

533
        foo = f"{scmean[kk].mean:.1f}"
Philipp Arras's avatar
Philipp Arras committed
534
        try:
535
            foo += f" ± {np.sqrt(scmean[kk].var):.1f}"
Philipp Arras's avatar
Philipp Arras committed
536
537
538
539
540
541
        except RuntimeError:
            pass
        out += f"{foo:>14}"
        out += f"{ndof[kk]:>11}"
        out += "\n"
    return out[:-1]