sugar.py 11.4 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-2019 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

20
import numpy as np
21
22
23

from . import dobj, utilities
from .domain_tuple import DomainTuple
Martin Reinecke's avatar
Martin Reinecke committed
24
from .domains.power_space import PowerSpace
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
25
from .field import Field
26
from .logger import logger
Martin Reinecke's avatar
Martin Reinecke committed
27
28
from .multi_domain import MultiDomain
from .multi_field import MultiField
Philipp Arras's avatar
Philipp Arras committed
29
from .operators.block_diagonal_operator import BlockDiagonalOperator
Martin Reinecke's avatar
Martin Reinecke committed
30
from .operators.diagonal_operator import DiagonalOperator
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
31
from .operators.distributors import PowerDistributor
32

Martin Reinecke's avatar
step 1    
Martin Reinecke committed
33
34
__all__ = ['PS_field', 'power_analyze', 'create_power_operator',
           'create_harmonic_smoothing_operator', 'from_random',
35
           'full', 'from_global_data', 'from_local_data',
Jakob Knollmueller's avatar
Jakob Knollmueller committed
36
37
           'makeDomain', 'sqrt', 'exp', 'log', 'tanh', 'sigmoid',
           'sin', 'cos', 'tan', 'sinh', 'cosh',
Martin Reinecke's avatar
Martin Reinecke committed
38
           'absolute', 'one_over', 'clip', 'sinc',
39
40
           'conjugate', 'get_signal_variance', 'makeOp', 'domain_union',
           'get_default_codomain']
41

42

43
def PS_field(pspace, func):
Martin Reinecke's avatar
Martin Reinecke committed
44
45
46
47
48
49
50
51
52
53
54
55
    """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
    Returns
    -------
    Field : a field living on (pspace,) containing the computed function values
    """
Martin Reinecke's avatar
Martin Reinecke committed
56
57
58
    if not isinstance(pspace, PowerSpace):
        raise TypeError
    data = dobj.from_global_data(func(pspace.k_lengths))
59
    return Field(DomainTuple.make(pspace), data)
Martin Reinecke's avatar
Martin Reinecke committed
60

Martin Reinecke's avatar
Martin Reinecke committed
61

62
63
64
65
66
67
68
69
70
71
72
73
74
def get_signal_variance(spec, space):
    """
    Computes how much a field with a given power spectrum will vary in space

    This is a small helper function that computes how the expected variance
    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
75
76
77
78
        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
79
80
81
82
    """
    if space.harmonic:
        space = PowerSpace(space)
    if not isinstance(space, PowerSpace):
Martin Reinecke's avatar
Martin Reinecke committed
83
84
        raise ValueError(
            "space must be either a harmonic space or Power space.")
85
86
87
88
89
    field = PS_field(space, spec)
    dist = PowerDistributor(space.harmonic_partner, space)
    k_field = dist(field)
    return k_field.weight(2).sum()

90

91
92
def _single_power_analyze(field, idx, binbounds):
    power_domain = PowerSpace(field.domain[idx], binbounds)
Martin Reinecke's avatar
Martin Reinecke committed
93
94
    pd = PowerDistributor(field.domain, power_domain, idx)
    return pd.adjoint_times(field.weight(1)).weight(-1)  # divides by bin size
95
96


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

    Creates a PowerSpace for the space addressed by `spaces` with the given
    binning and computes the power spectrum as a Field over this
    PowerSpace. This can only be done if the subspace to  be analyzed is a
Martin Reinecke's avatar
Martin Reinecke committed
106
107
    harmonic space. The resulting field has the same units as the square of the
    initial field.
108
109
110
111
112

    Parameters
    ----------
    field : Field
        The field to be analyzed
Martin Reinecke's avatar
Martin Reinecke committed
113
114
115
    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
116
        If None, all subdomains will be converted.
117
        (default : None).
Martin Reinecke's avatar
Martin Reinecke committed
118
    binbounds : None or array-like, optional
119
        Inner bounds of the bins (default : None).
Martin Reinecke's avatar
Martin Reinecke committed
120
121
        if binbounds is None : bins are inferred.
    keep_phase_information : bool, optional
122
123
124
125
126
127
128
129
130
131
132
133
        If False, return a real-valued result containing the power spectrum
        of the input Field.
        If True, return a complex-valued result whose real component
        contains the power spectrum computed from the real part of the
        input Field, and whose imaginary component contains the power
        spectrum computed from the imaginary part of the input Field.
        The absolute value of this result should be identical to the output
        of power_analyze with keep_phase_information=False.
        (default : False).

    Returns
    -------
Martin Reinecke's avatar
Martin Reinecke committed
134
    Field
135
        The output object. Its domain is a PowerSpace and it contains
Martin Reinecke's avatar
Martin Reinecke committed
136
        the power spectrum of `field`.
137
138
139
140
    """

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

144
    spaces = utilities.parse_spaces(spaces, len(field.domain))
145
146
147
148

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

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

153
154
155
    if keep_phase_information:
        parts = [field.real*field.real, field.imag*field.imag]
    else:
156
157
158
159
        if field_real:
            parts = [field**2]
        else:
            parts = [field.real*field.real + field.imag*field.imag]
160
161

    for space_index in spaces:
Martin Reinecke's avatar
Martin Reinecke committed
162
        parts = [_single_power_analyze(part, space_index, binbounds)
163
164
165
166
167
                 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
168
def _create_power_field(domain, power_spectrum):
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
169
170
171
172
173
174
175
176
    if not callable(power_spectrum):  # we have a Field living on a PowerSpace
        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]
177
        fp = power_spectrum
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
178
179
    else:
        power_domain = PowerSpace(domain)
180
        fp = PS_field(power_domain, power_spectrum)
181

Martin Reinecke's avatar
Martin Reinecke committed
182
    return PowerDistributor(domain, power_domain)(fp)
183

184

185
def create_power_operator(domain, power_spectrum, space=None):
Theo Steininger's avatar
Theo Steininger committed
186
    """ Creates a diagonal operator with the given power spectrum.
187

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

190
191
    Parameters
    ----------
Martin Reinecke's avatar
Martin Reinecke committed
192
    domain : Domain, tuple of Domain or DomainTuple
Philipp Arras's avatar
Philipp Arras committed
193
        Domain on which the power operator shall be defined.
Martin Reinecke's avatar
Martin Reinecke committed
194
195
    power_spectrum : callable or Field
        An object that contains the power spectrum as a function of k.
Martin Reinecke's avatar
Martin Reinecke committed
196
    space : int
Martin Reinecke's avatar
Martin Reinecke committed
197
        the domain index on which the power operator will work
Theo Steininger's avatar
Theo Steininger committed
198

199
200
    Returns
    -------
Martin Reinecke's avatar
Martin Reinecke committed
201
202
    DiagonalOperator
        An operator that implements the given power spectrum.
203
    """
Martin Reinecke's avatar
Martin Reinecke committed
204
    domain = DomainTuple.make(domain)
Martin Reinecke's avatar
Martin Reinecke committed
205
    space = utilities.infer_space(domain, space)
Martin Reinecke's avatar
Martin Reinecke committed
206
207
    field = _create_power_field(domain[space], power_spectrum)
    return DiagonalOperator(field, domain, space)
208

209

210
211
212
213
def create_harmonic_smoothing_operator(domain, space, sigma):
    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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240


def full(domain, val):
    if isinstance(domain, (dict, MultiDomain)):
        return MultiField.full(domain, val)
    return Field.full(domain, val)


def from_random(random_type, domain, dtype=np.float64, **kwargs):
    if isinstance(domain, (dict, MultiDomain)):
        return MultiField.from_random(random_type, domain, dtype, **kwargs)
    return Field.from_random(random_type, domain, dtype, **kwargs)


def from_global_data(domain, arr, sum_up=False):
    if isinstance(domain, (dict, MultiDomain)):
        return MultiField.from_global_data(domain, arr, sum_up)
    return Field.from_global_data(domain, arr, sum_up)


def from_local_data(domain, arr):
    if isinstance(domain, (dict, MultiDomain)):
        return MultiField.from_local_data(domain, arr)
    return Field.from_local_data(domain, arr)


def makeDomain(domain):
Martin Reinecke's avatar
fixes    
Martin Reinecke committed
241
    if isinstance(domain, (MultiDomain, dict)):
Martin Reinecke's avatar
step 1    
Martin Reinecke committed
242
243
        return MultiDomain.make(domain)
    return DomainTuple.make(domain)
244
245


246
def makeOp(input):
Martin Reinecke's avatar
Martin Reinecke committed
247
248
    if input is None:
        return None
Martin Reinecke's avatar
Martin Reinecke committed
249
250
251
    if isinstance(input, Field):
        return DiagonalOperator(input)
    if isinstance(input, MultiField):
Martin Reinecke's avatar
Martin Reinecke committed
252
        return BlockDiagonalOperator(
Martin Reinecke's avatar
Martin Reinecke committed
253
            input.domain, tuple(makeOp(val) for val in input.values()))
Martin Reinecke's avatar
Martin Reinecke committed
254
255
    raise NotImplementedError

Martin Reinecke's avatar
more    
Martin Reinecke committed
256
257
258

def domain_union(domains):
    if isinstance(domains[0], DomainTuple):
Martin Reinecke's avatar
Martin Reinecke committed
259
        if any(dom != domains[0] for dom in domains[1:]):
Martin Reinecke's avatar
more    
Martin Reinecke committed
260
261
262
263
            raise ValueError("domain mismatch")
        return domains[0]
    return MultiDomain.union(domains)

Martin Reinecke's avatar
more    
Martin Reinecke committed
264

265
266
# Arithmetic functions working on Fields

267

268
269
_current_module = sys.modules[__name__]

Jakob Knollmueller's avatar
Jakob Knollmueller committed
270
271
for f in ["sqrt", "exp", "log", "tanh", "sigmoid",
          "conjugate", 'sin', 'cos', 'tan', 'sinh', 'cosh',
Martin Reinecke's avatar
Martin Reinecke committed
272
          'absolute', 'one_over', 'sinc']:
273
    def func(f):
274
        def func2(x):
Martin Reinecke's avatar
Martin Reinecke committed
275
            from .linearization import Linearization
Martin Reinecke's avatar
Martin Reinecke committed
276
277
            from .operators.operator import Operator
            if isinstance(x, (Field, MultiField, Linearization, Operator)):
Martin Reinecke's avatar
Martin Reinecke committed
278
                return getattr(x, f)()
279
            else:
280
                return getattr(np, f)(x)
281
282
        return func2
    setattr(_current_module, f, func(f))
283

Martin Reinecke's avatar
Martin Reinecke committed
284
285
286
287
288

def clip(a, a_min=None, a_max=None):
    return a.clip(a_min, a_max)


289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
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
    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)
    if not isinstance(domainoid[space], RGSpace):
        raise TypeError("can only codomain RGSpaces")
    ret = [dom for dom in domainoid]
    ret[space] = domainoid[space].get_default_codomain()
    return DomainTuple.make(ret)