sugar.py 22.1 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
# 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/>.
Theo Steininger's avatar
Theo Steininger committed
13
#
14
# Copyright(C) 2013-2020 Max-Planck-Society
Theo Steininger's avatar
Theo Steininger committed
15
#
16
# NIFTy is being developed at the Max-Planck-Institut fuer Astrophysik.
17

18
import sys
19
from time import time
20

21
import numpy as np
22

23
from . import pointwise, utilities
24
from .domain_tuple import DomainTuple
Martin Reinecke's avatar
Martin Reinecke committed
25
from .domains.power_space import PowerSpace
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
26
from .field import Field
27
from .logger import logger
Martin Reinecke's avatar
Martin Reinecke committed
28
29
from .multi_domain import MultiDomain
from .multi_field import MultiField
Philipp Arras's avatar
Philipp Arras committed
30
from .operators.block_diagonal_operator import BlockDiagonalOperator
Martin Reinecke's avatar
Martin Reinecke committed
31
from .operators.diagonal_operator import DiagonalOperator
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
32
from .operators.distributors import PowerDistributor
33
from .operators.operator import Operator
34
from .operators.sampling_enabler import SamplingDtypeSetter
35
from .operators.selection_operators import SliceOperator
36
from .operators.scaling_operator import ScalingOperator
Lukas Platz's avatar
Lukas Platz committed
37
from .plot import Plot
38

Martin Reinecke's avatar
step 1    
Martin Reinecke committed
39
__all__ = ['PS_field', 'power_analyze', 'create_power_operator',
40
41
           'density_estimator', 'create_harmonic_smoothing_operator',
           'from_random', 'full', 'makeField', 'is_fieldlike',
Philipp Arras's avatar
Philipp Arras committed
42
           'is_linearization', 'is_operator', 'makeDomain', 'is_likelihood_energy',
43
           'get_signal_variance', 'makeOp', 'domain_union',
Philipp Arras's avatar
Philipp Arras committed
44
           'get_default_codomain', 'single_plot', 'exec_time',
45
           'calculate_position'] + list(pointwise.ptw_dict.keys())
46

47

48
def PS_field(pspace, func):
Martin Reinecke's avatar
Martin Reinecke committed
49
50
51
52
53
54
55
56
    """Convenience function sampling a power spectrum

    Parameters
    ----------
    pspace : PowerSpace
        space at whose `k_lengths` the power spectrum function is evaluated
    func : function taking and returning a numpy.ndarray(float)
        the power spectrum function
Martin Reinecke's avatar
Martin Reinecke committed
57

Martin Reinecke's avatar
Martin Reinecke committed
58
59
    Returns
    -------
Martin Reinecke's avatar
Martin Reinecke committed
60
61
    Field
        A field defined on (pspace,) containing the computed function values
Martin Reinecke's avatar
Martin Reinecke committed
62
    """
Martin Reinecke's avatar
Martin Reinecke committed
63
64
    if not isinstance(pspace, PowerSpace):
        raise TypeError
Martin Reinecke's avatar
stage 1    
Martin Reinecke committed
65
    data = func(pspace.k_lengths)
66
    return Field(DomainTuple.make(pspace), data)
Martin Reinecke's avatar
Martin Reinecke committed
67

Martin Reinecke's avatar
Martin Reinecke committed
68

69
70
71
72
def get_signal_variance(spec, space):
    """
    Computes how much a field with a given power spectrum will vary in space

73
    This is a small helper function that computes the expected variance
74
75
76
77
78
79
80
81
    of a harmonically transformed sample of this power spectrum.

    Parameters
    ---------
    spec: method
        a method that takes one k-value and returns the power spectrum at that
        location
    space: PowerSpace or any harmonic Domain
Martin Reinecke's avatar
Martin Reinecke committed
82
83
84
85
        If this function is given a harmonic domain, it creates the naturally
        binned PowerSpace to that domain.
        The field, for which the signal variance is then computed, is assumed
        to have this PowerSpace as naturally binned PowerSpace
86
87
88
89
    """
    if space.harmonic:
        space = PowerSpace(space)
    if not isinstance(space, PowerSpace):
Martin Reinecke's avatar
Martin Reinecke committed
90
91
        raise ValueError(
            "space must be either a harmonic space or Power space.")
92
93
94
    field = PS_field(space, spec)
    dist = PowerDistributor(space.harmonic_partner, space)
    k_field = dist(field)
Martin Reinecke's avatar
Martin Reinecke committed
95
    return k_field.weight(2).s_sum()
96

97

98
99
def _single_power_analyze(field, idx, binbounds):
    power_domain = PowerSpace(field.domain[idx], binbounds)
Martin Reinecke's avatar
Martin Reinecke committed
100
101
    pd = PowerDistributor(field.domain, power_domain, idx)
    return pd.adjoint_times(field.weight(1)).weight(-1)  # divides by bin size
102
103


Martin Reinecke's avatar
Martin Reinecke committed
104
105
# MR FIXME: this function is not well suited for analyzing more than one
# subdomain at once, because it allows only one set of binbounds.
106
107
def power_analyze(field, spaces=None, binbounds=None,
                  keep_phase_information=False):
108
    """Computes the power spectrum for a subspace of `field`.
109

Philipp Arras's avatar
Philipp Arras committed
110
111
112
113
114
115
    Creates a PowerSpace for the space addressed by `spaces` with the
    given binning and computes the power spectrum as a
    :class:`~nifty7.field.Field` over this PowerSpace. This can only
    be done if the subspace to be analyzed is a harmonic space. The
    resulting field has the same units as the square of the initial
    field.
116
117
118

    Parameters
    ----------
Philipp Arras's avatar
Fixups    
Philipp Arras committed
119
    field : Field
120
        The field to be analyzed
Martin Reinecke's avatar
Martin Reinecke committed
121
122
123
    spaces : None or int or tuple of int, optional
        The indices of subdomains for which the power spectrum shall be
        computed.
Martin Reinecke's avatar
Martin Reinecke committed
124
        If None, all subdomains will be converted.
125
        (default : None).
Martin Reinecke's avatar
Martin Reinecke committed
126
    binbounds : None or array-like, optional
127
        Inner bounds of the bins (default : None).
Martin Reinecke's avatar
Martin Reinecke committed
128
129
        if binbounds is None : bins are inferred.
    keep_phase_information : bool, optional
130
        If False, return a real-valued result containing the power spectrum
131
        of `field`.
132
        If True, return a complex-valued result whose real component
133
134
135
        contains the power spectrum computed from the real part of `field`,
        and whose imaginary component contains the power
        spectrum computed from the imaginary part of `field`.
136
137
138
139
140
141
        The absolute value of this result should be identical to the output
        of power_analyze with keep_phase_information=False.
        (default : False).

    Returns
    -------
Philipp Arras's avatar
Fixups    
Philipp Arras committed
142
    Field
143
        The output object. Its domain is a PowerSpace and it contains
Martin Reinecke's avatar
Martin Reinecke committed
144
        the power spectrum of `field`.
145
146
147
148
    """

    for sp in field.domain:
        if not sp.harmonic and not isinstance(sp, PowerSpace):
Martin Reinecke's avatar
Martin Reinecke committed
149
150
            logger.warning("WARNING: Field has a space in `domain` which is "
                           "neither harmonic nor a PowerSpace.")
151

152
    spaces = utilities.parse_spaces(spaces, len(field.domain))
153
154
155
156

    if len(spaces) == 0:
        raise ValueError("No space for analysis specified.")

Martin Reinecke's avatar
Martin Reinecke committed
157
    field_real = not utilities.iscomplextype(field.dtype)
158
159
160
    if (not field_real) and keep_phase_information:
        raise ValueError("cannot keep phase from real-valued input Field")

161
162
163
    if keep_phase_information:
        parts = [field.real*field.real, field.imag*field.imag]
    else:
164
165
166
167
        if field_real:
            parts = [field**2]
        else:
            parts = [field.real*field.real + field.imag*field.imag]
168
169

    for space_index in spaces:
Martin Reinecke's avatar
Martin Reinecke committed
170
        parts = [_single_power_analyze(part, space_index, binbounds)
171
172
173
174
175
                 for part in parts]

    return parts[0] + 1j*parts[1] if keep_phase_information else parts[0]


Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
176
def _create_power_field(domain, power_spectrum):
Philipp Arras's avatar
Philipp Arras committed
177
    if not callable(power_spectrum):  # we have a Field defined on a PowerSpace
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
178
179
180
181
182
183
184
        if not isinstance(power_spectrum, Field):
            raise TypeError("Field object expected")
        if len(power_spectrum.domain) != 1:
            raise ValueError("exactly one domain required")
        if not isinstance(power_spectrum.domain[0], PowerSpace):
            raise TypeError("PowerSpace required")
        power_domain = power_spectrum.domain[0]
185
        fp = power_spectrum
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
186
187
    else:
        power_domain = PowerSpace(domain)
188
        fp = PS_field(power_domain, power_spectrum)
189

Martin Reinecke's avatar
Martin Reinecke committed
190
    return PowerDistributor(domain, power_domain)(fp)
191

192

193
def create_power_operator(domain, power_spectrum, space=None):
194
    """Creates a diagonal operator with the given power spectrum.
195

Philipp Arras's avatar
Philipp Arras committed
196
    Constructs a diagonal operator that is defined on the specified domain.
197

198
199
    Parameters
    ----------
Martin Reinecke's avatar
Martin Reinecke committed
200
    domain : Domain, tuple of Domain or DomainTuple
Philipp Arras's avatar
Philipp Arras committed
201
        Domain on which the power operator shall be defined.
Martin Reinecke's avatar
Martin Reinecke committed
202
203
    power_spectrum : callable or Field
        An object that contains the power spectrum as a function of k.
Martin Reinecke's avatar
Martin Reinecke committed
204
    space : int
Martin Reinecke's avatar
Martin Reinecke committed
205
        the domain index on which the power operator will work
Theo Steininger's avatar
Theo Steininger committed
206

207
208
    Returns
    -------
Martin Reinecke's avatar
Martin Reinecke committed
209
210
    DiagonalOperator
        An operator that implements the given power spectrum.
211
    """
Martin Reinecke's avatar
Martin Reinecke committed
212
    domain = DomainTuple.make(domain)
Martin Reinecke's avatar
Martin Reinecke committed
213
    space = utilities.infer_space(domain, space)
Martin Reinecke's avatar
Martin Reinecke committed
214
215
    field = _create_power_field(domain[space], power_spectrum)
    return DiagonalOperator(field, domain, space)
216

217

218
219
220
221
222
223
def density_estimator(domain, pad=1.0, cf_fluctuations=None,
                      cf_azm_uniform=None):
    from .domains.rg_space import RGSpace
    from .library.correlated_fields import CorrelatedFieldMaker
    from .library.special_distributions import UniformOperator

Philipp Frank's avatar
Philipp Frank committed
224
    cf_azm_uniform_sane_default = (1e-4, 1.0)
225
    cf_fluctuations_sane_default = {
Philipp Frank's avatar
Philipp Frank committed
226
        "scale": (0.5, 0.3),
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
        "cutoff": (4.0, 3.0),
        "loglogslope": (-6.0, 3.0)
    }

    domain = DomainTuple.make(domain)
    dom_scaling = 1. + np.broadcast_to(pad, (len(domain.axes), ))
    if cf_fluctuations is None:
        cf_fluctuations = cf_fluctuations_sane_default
    if cf_azm_uniform is None:
        cf_azm_uniform = cf_azm_uniform_sane_default

    domain_padded = []
    for d_scl, d in zip(dom_scaling, domain):
        if not isinstance(d, RGSpace) or d.harmonic:
            te = [f"unexpected domain encountered in `domain`: {domain}"]
            te += "expected a non-harmonic `RGSpace`"
            raise TypeError("\n".join(te))
        shape_padded = tuple((d_scl * np.array(d.shape)).astype(int))
        domain_padded.append(RGSpace(shape_padded, distances=d.distances))
    domain_padded = DomainTuple.make(domain_padded)

    # Set up the signal model
    azm_offset_mean = 0.0  # The zero-mode should be inferred only from the data
    cfmaker = CorrelatedFieldMaker("")
    for i, d in enumerate(domain_padded):
        if isinstance(cf_fluctuations, (list, tuple)):
            cf_fl = cf_fluctuations[i]
        else:
            cf_fl = cf_fluctuations
        cfmaker.add_fluctuations_matern(d, **cf_fl, prefix=f"ax{i}")
    scalar_domain = DomainTuple.scalar_domain()
    uniform = UniformOperator(scalar_domain, *cf_azm_uniform)
    azm = uniform.ducktape("zeromode")
    cfmaker.set_amplitude_total_offset(azm_offset_mean, azm)
    correlated_field = cfmaker.finalize(0).clip(-10., 10.)
    normalized_amplitudes = cfmaker.get_normalized_amplitudes()

    domain_shape = tuple(d.shape for d in domain)
    slc = SliceOperator(correlated_field.target, domain_shape)
    signal = (slc @ correlated_field).exp()

    model_operators = {
        "correlated_field": correlated_field,
        "select_subset": slc,
        "amplitude_total_offset": azm,
        "normalized_amplitudes": normalized_amplitudes
    }

    return signal, model_operators


278
def create_harmonic_smoothing_operator(domain, space, sigma):
Martin Reinecke's avatar
Martin Reinecke committed
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
    """Creates an operator which smoothes a subspace of a harmonic domain.

    Parameters
    ----------
    domain: DomainTuple
        The total domain and target of the operator
    space : int
        the index of the subspace on which the operator acts.
        This must be a harmonic space
    sigma : float
        The sigma of the Gaussian smoothing kernel

    Returns
    -------
    DiagonalOperator
        The requested smoothing operator
    """
296
297
298
    kfunc = domain[space].get_fft_smoothing_kernel_function(sigma)
    return DiagonalOperator(kfunc(domain[space].get_k_length_array()), domain,
                            space)
Martin Reinecke's avatar
step 1    
Martin Reinecke committed
299
300
301


def full(domain, val):
Martin Reinecke's avatar
Martin Reinecke committed
302
303
304
305
306
307
308
309
310
311
312
    """Convenience function creating Fields/MultiFields with uniform values.

    Parameters
    ----------
    domain : Domainoid
        the intended domain of the output field
    val : scalar value
        the uniform value to be placed into all entries of the result

    Returns
    -------
Martin Reinecke's avatar
Martin Reinecke committed
313
314
    Field or MultiField
        The newly created uniform field
Martin Reinecke's avatar
Martin Reinecke committed
315
    """
Martin Reinecke's avatar
step 1    
Martin Reinecke committed
316
317
318
319
320
    if isinstance(domain, (dict, MultiDomain)):
        return MultiField.full(domain, val)
    return Field.full(domain, val)


321
def from_random(domain, random_type='normal', dtype=np.float64, **kwargs):
Martin Reinecke's avatar
Martin Reinecke committed
322
323
324
325
326
327
    """Convenience function creating Fields/MultiFields with random values.

    Parameters
    ----------
    domain : Domainoid
        the intended domain of the output field
328
329
    random_type : 'pm1', 'normal', or 'uniform'
            The random distribution to use.
Martin Reinecke's avatar
Martin Reinecke committed
330
331
    dtype : type
        data type of the output field (e.g. numpy.float64)
332
333
        If the datatype is complex, each real an imaginary part have
        variance 1.
Martin Reinecke's avatar
Martin Reinecke committed
334
335
336
337
338
    **kwargs : additional parameters for the random distribution
        ('mean' and 'std' for 'normal', 'low' and 'high' for 'uniform')

    Returns
    -------
Martin Reinecke's avatar
Martin Reinecke committed
339
340
    Field or MultiField
        The newly created random field
341
342
343

    Notes
    -----
Martin Reinecke's avatar
Martin Reinecke committed
344
345
346
347
    When called with a multi-domain, the individual fields will be drawn in
    alphabetical order of the multi-domain's domain keys. As a consequence,
    renaming these keys may cause the multi-field to be filled with different
    random numbers, even for the same initial RNG state.
Martin Reinecke's avatar
Martin Reinecke committed
348
    """
Martin Reinecke's avatar
step 1    
Martin Reinecke committed
349
    if isinstance(domain, (dict, MultiDomain)):
350
351
        return MultiField.from_random(domain, random_type, dtype, **kwargs)
    return Field.from_random(domain, random_type, dtype, **kwargs)
Martin Reinecke's avatar
step 1    
Martin Reinecke committed
352
353


Martin Reinecke's avatar
Martin Reinecke committed
354
def makeField(domain, arr):
Martin Reinecke's avatar
Martin Reinecke committed
355
356
357
358
359
360
361
362
363
364
365
366
    """Convenience function creating Fields/MultiFields from Numpy arrays or
    dicts of Numpy arrays.

    Parameters
    ----------
    domain : Domainoid
        the intended domain of the output field
    arr : Numpy array if `domain` corresponds to a `DomainTuple`,
          dictionary of Numpy arrays if `domain` corresponds to a `MultiDomain`

    Returns
    -------
Martin Reinecke's avatar
Martin Reinecke committed
367
368
    Field or MultiField
        The newly created random field
Martin Reinecke's avatar
Martin Reinecke committed
369
    """
Martin Reinecke's avatar
step 1    
Martin Reinecke committed
370
    if isinstance(domain, (dict, MultiDomain)):
Martin Reinecke's avatar
Martin Reinecke committed
371
372
        return MultiField.from_raw(domain, arr)
    return Field.from_raw(domain, arr)
Martin Reinecke's avatar
step 1    
Martin Reinecke committed
373
374
375


def makeDomain(domain):
Martin Reinecke's avatar
Martin Reinecke committed
376
377
378
379
    """Convenience function creating DomainTuples/MultiDomains Domainoids.

    Parameters
    ----------
Martin Reinecke's avatar
Martin Reinecke committed
380
    domain : Domainoid (can be DomainTuple, MultiDomain, dict, Domain or list of Domains)
Martin Reinecke's avatar
Martin Reinecke committed
381
382
383
384
        the description of the requested (multi-)domain

    Returns
    -------
Martin Reinecke's avatar
Martin Reinecke committed
385
386
    DomainTuple or MultiDomain
        The newly created domain object
Martin Reinecke's avatar
Martin Reinecke committed
387
    """
Martin Reinecke's avatar
fixes    
Martin Reinecke committed
388
    if isinstance(domain, (MultiDomain, dict)):
Martin Reinecke's avatar
step 1    
Martin Reinecke committed
389
390
        return MultiDomain.make(domain)
    return DomainTuple.make(domain)
391
392


393
def makeOp(input, dom=None):
Martin Reinecke's avatar
Martin Reinecke committed
394
395
396
397
398
399
    """Converts a Field or MultiField to a diagonal operator.

    Parameters
    ----------
    input : None, Field or MultiField
        - if None, None is returned.
400
401
        - if Field on scalar-domain, a ScalingOperator with the coefficient
            given by the Field is returned.
Martin Reinecke's avatar
Martin Reinecke committed
402
403
404
405
406
        - if Field, a DiagonalOperator with the coefficients given by this
            Field is returned.
        - if MultiField, a BlockDiagonalOperator with entries given by this
            MultiField is returned.

407
408
409
    dom : DomainTuple or MultiDomain
        if `input` is a scalar, this is used as the operator's domain

Martin Reinecke's avatar
Martin Reinecke committed
410
411
412
413
    Notes
    -----
    No volume factors are applied.
    """
Martin Reinecke's avatar
Martin Reinecke committed
414
415
    if input is None:
        return None
416
    if np.isscalar(input):
Rouven Lemmerz's avatar
Typo    
Rouven Lemmerz committed
417
        if not isinstance(dom, (DomainTuple, MultiDomain)):
418
            raise TypeError("need proper `dom` argument")
419
        return ScalingOperator(dom, input)
420
421
422
    if dom is not None:
        if not dom == input.domain:
            raise ValueError("domain mismatch")
423
    if input.domain is DomainTuple.scalar_domain():
424
        return ScalingOperator(input.domain, input.val[()])
Martin Reinecke's avatar
Martin Reinecke committed
425
426
427
    if isinstance(input, Field):
        return DiagonalOperator(input)
    if isinstance(input, MultiField):
Martin Reinecke's avatar
Martin Reinecke committed
428
        return BlockDiagonalOperator(
Martin Reinecke's avatar
fix    
Martin Reinecke committed
429
            input.domain, {key: makeOp(val) for key, val in input.items()})
Martin Reinecke's avatar
Martin Reinecke committed
430
431
    raise NotImplementedError

Martin Reinecke's avatar
more    
Martin Reinecke committed
432
433

def domain_union(domains):
Martin Reinecke's avatar
Martin Reinecke committed
434
435
436
437
438
439
440
441
    """Computes the union of multiple DomainTuples/MultiDomains.

    Parameters
    ----------
    domains : list of DomainTuple or MultiDomain
        - if DomainTuple, all entries must be equal
        - if MultiDomain, there must not be any conflicting components
    """
Martin Reinecke's avatar
more    
Martin Reinecke committed
442
    if isinstance(domains[0], DomainTuple):
Martin Reinecke's avatar
Martin Reinecke committed
443
        if any(dom != domains[0] for dom in domains[1:]):
Martin Reinecke's avatar
more    
Martin Reinecke committed
444
445
446
447
            raise ValueError("domain mismatch")
        return domains[0]
    return MultiDomain.union(domains)

Martin Reinecke's avatar
more    
Martin Reinecke committed
448

449
450
451
452
453
454
455
456
457
458
# Pointwise functions

_current_module = sys.modules[__name__]

for f in pointwise.ptw_dict.keys():
    def func(f):
        def func2(x, *args, **kwargs):
           return x.ptw(f, *args, **kwargs)
        return func2
    setattr(_current_module, f, func(f))
Martin Reinecke's avatar
Martin Reinecke committed
459
460


461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
def get_default_codomain(domainoid, space=None):
    """For `RGSpace`, returns the harmonic partner domain.
    For `DomainTuple`, returns a copy of the object in which the domain
    indexed by `space` is substituted by its harmonic partner domain.
    In this case, if `space` is None, it is set to 0 if the `DomainTuple`
    contains exactly one domain.

    Parameters
    ----------
    domain: `RGSpace` or `DomainTuple`
        Domain for which to constuct the default harmonic partner
    space: int
        Optional index of the subdomain to be replaced by its default
        codomain. `domain[space]` must be of class `RGSpace`.
    """
    from .domains.rg_space import RGSpace
477
478
479
    from .domains.hp_space import HPSpace
    from .domains.gl_space import GLSpace
    from .domains.lm_space import LMSpace
480
481
482
483
484
485
    if isinstance(domainoid, RGSpace):
        return domainoid.get_default_codomain()
    if not isinstance(domainoid, DomainTuple):
        raise TypeError(
            'Works only on RGSpaces and DomainTuples containing those')
    space = utilities.infer_space(domainoid, space)
486
487
    if not isinstance(domainoid[space], (RGSpace, HPSpace, GLSpace, LMSpace)):
        raise TypeError("can only codomain structrued spaces")
488
489
490
    ret = [dom for dom in domainoid]
    ret[space] = domainoid[space].get_default_codomain()
    return DomainTuple.make(ret)
Lukas Platz's avatar
Lukas Platz committed
491
492
493
494
495
496
497
498
499
500
501


def single_plot(field, **kwargs):
    """Creates a single plot using `Plot`.
    Keyword arguments are passed to both `Plot.add` and `Plot.output`.
    """
    p = Plot()
    p.add(field, **kwargs)
    if 'title' in kwargs:
        del(kwargs['title'])
    p.output(**kwargs)
502
503
504
505


def exec_time(obj, want_metric=True):
    """Times the execution time of an operator or an energy."""
Philipp Arras's avatar
Philipp Arras committed
506
507
508
    from .linearization import Linearization
    from .minimization.energy import Energy
    from .operators.energy_operators import EnergyOperator
509
510
511
    if isinstance(obj, Energy):
        t0 = time()
        obj.at(0.99*obj.position)
512
        logger.info('Energy.at(): {}'.format(time() - t0))
513
514
515

        t0 = time()
        obj.value
516
        logger.info('Energy.value: {}'.format(time() - t0))
517
518
        t0 = time()
        obj.gradient
519
        logger.info('Energy.gradient: {}'.format(time() - t0))
520
521
        t0 = time()
        obj.metric
522
        logger.info('Energy.metric: {}'.format(time() - t0))
523
524
525

        t0 = time()
        obj.apply_metric(obj.position)
526
        logger.info('Energy.apply_metric: {}'.format(time() - t0))
527
528
529

        t0 = time()
        obj.metric(obj.position)
530
        logger.info('Energy.metric(position): {}'.format(time() - t0))
531
532
    elif isinstance(obj, Operator):
        want_metric = bool(want_metric)
533
        pos = from_random(obj.domain, 'normal')
534
535
        t0 = time()
        obj(pos)
536
        logger.info('Operator call with field: {}'.format(time() - t0))
537
538
539
540

        lin = Linearization.make_var(pos, want_metric=want_metric)
        t0 = time()
        res = obj(lin)
541
        logger.info('Operator call with linearization: {}'.format(time() - t0))
542

543
        if obj.target is DomainTuple.scalar_domain():
544
545
            t0 = time()
            res.gradient
546
            logger.info('Gradient evaluation: {}'.format(time() - t0))
547
548
549
550

            if want_metric:
                t0 = time()
                res.metric(pos)
551
                logger.info('Metric apply: {}'.format(time() - t0))
552
553
    else:
        raise TypeError
Philipp Arras's avatar
Philipp Arras committed
554
555
556
557


def calculate_position(operator, output):
    """Finds approximate preimage of an operator for a given output."""
Philipp Arras's avatar
Philipp Arras committed
558
559
    from .minimization.descent_minimizers import NewtonCG
    from .minimization.iteration_controllers import GradientNormController
Philipp Frank's avatar
Philipp Frank committed
560
    from .minimization.kl_energies import MetricGaussianKL
Philipp Arras's avatar
Philipp Arras committed
561
562
    from .operators.scaling_operator import ScalingOperator
    from .operators.energy_operators import GaussianEnergy, StandardHamiltonian
Philipp Arras's avatar
Philipp Arras committed
563
564
565
566
    if not isinstance(operator, Operator):
        raise TypeError
    if output.domain != operator.target:
        raise TypeError
567
    if isinstance(output, MultiField):
568
        cov = 1e-3*max([np.max(np.abs(vv)) for vv in output.val.values()])**2
Philipp Arras's avatar
Philipp Arras committed
569
570
571
572
573
        invcov = ScalingOperator(output.domain, cov).inverse
        dtype = list(set([ff.dtype for ff in output.values()]))
        if len(dtype) != 1:
            raise ValueError('Only MultiFields with one dtype supported.')
        dtype = dtype[0]
574
    else:
575
        cov = 1e-3*np.max(np.abs(output.val))**2
Philipp Arras's avatar
Philipp Arras committed
576
        dtype = output.dtype
577
    invcov = ScalingOperator(output.domain, cov).inverse
578
579
580
    invcov = SamplingDtypeSetter(invcov, output.dtype)
    invcov = SamplingDtypeSetter(invcov, output.dtype)
    d = output + invcov.draw_sample(from_inverse=True)
Philipp Arras's avatar
Philipp Arras committed
581
    lh = GaussianEnergy(d, invcov) @ operator
Philipp Arras's avatar
Philipp Arras committed
582
583
    H = StandardHamiltonian(
        lh, ic_samp=GradientNormController(iteration_limit=200))
584
    pos = 0.1*from_random(operator.domain)
Philipp Arras's avatar
Philipp Arras committed
585
    minimizer = NewtonCG(GradientNormController(iteration_limit=10, name='findpos'))
Philipp Arras's avatar
Philipp Arras committed
586
    for ii in range(3):
Philipp Arras's avatar
Philipp Arras committed
587
        logger.info(f'Start iteration {ii+1}/3')
Philipp Frank's avatar
Philipp Frank committed
588
        kl = MetricGaussianKL(pos, H, 3, True)
Philipp Arras's avatar
Philipp Arras committed
589
590
591
        kl, _ = minimizer(kl)
        pos = kl.position
    return pos
592
593


Philipp Arras's avatar
Philipp Arras committed
594
595
def is_likelihood_energy(obj):
    """Checks if object behaves like a likelihood energy.
Philipp Frank's avatar
Philipp Frank committed
596
597
598
599
    """
    return isinstance(obj, Operator) and obj.get_transformation() is not None


600
def is_operator(obj):
Philipp Frank's avatar
Philipp Frank committed
601
    """Checks if object is operator-like.
602
603
604

    Note
    ----
Philipp Arras's avatar
Philipp Arras committed
605
606
    A simple `isinstance(obj, ift.Operator)` does not give the expected result
    because, e.g., :class:`~nifty7.field.Field` inherits from
607
608
    :class:`~nifty7.operators.operator.Operator`.
    """
Philipp Arras's avatar
Philipp Arras committed
609
    return isinstance(obj, Operator) and obj.val is None
610
611
612


def is_linearization(obj):
Philipp Frank's avatar
Philipp Frank committed
613
    """Checks if object is linearization-like."""
Philipp Arras's avatar
Philipp Arras committed
614
    return isinstance(obj, Operator) and obj.jac is not None
615
616
617


def is_fieldlike(obj):
Philipp Frank's avatar
Philipp Frank committed
618
    """Checks if object is field-like.
619
620
621

    Note
    ----
Philipp Arras's avatar
Philipp Arras committed
622
623
624
625
626
    A simple `isinstance(obj, ift.Field)` does not give the expected result
    because users might have implemented another class which behaves field-like
    but is not an instance of :class:`~nifty7.field.Field`. Also note that
    instances of :class:`~nifty7.linearization.Linearization` behave
    field-like.
627
    """
Philipp Arras's avatar
Philipp Arras committed
628
    return isinstance(obj, Operator) and obj.val is not None