sugar.py 9.78 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
#
Martin Reinecke's avatar
Martin Reinecke committed
14
# Copyright(C) 2013-2018 Max-Planck-Society
Theo Steininger's avatar
Theo Steininger committed
15
16
17
#
# NIFTy is being developed at the Max-Planck-Institut fuer Astrophysik
# and financially supported by the Studienstiftung des deutschen Volkes.
18

19
import sys
20
import numpy as np
Martin Reinecke's avatar
Martin Reinecke committed
21
from .domains.power_space import PowerSpace
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
22
from .field import Field
Martin Reinecke's avatar
fix    
Martin Reinecke committed
23
24
from .multi.multi_field import MultiField
from .multi.multi_domain import MultiDomain
Martin Reinecke's avatar
Martin Reinecke committed
25
from .operators.diagonal_operator import DiagonalOperator
Martin Reinecke's avatar
Martin Reinecke committed
26
from .operators.power_distributor import PowerDistributor
Martin Reinecke's avatar
Martin Reinecke committed
27
28
from .domain_tuple import DomainTuple
from . import dobj, utilities
Martin Reinecke's avatar
Martin Reinecke committed
29
from .logger import logger
30

Martin Reinecke's avatar
step 1    
Martin Reinecke committed
31
32
33
__all__ = ['PS_field', 'power_analyze', 'create_power_operator',
           'create_harmonic_smoothing_operator', 'from_random',
           'full', 'empty', 'from_global_data', 'from_local_data',
Martin Reinecke's avatar
Martin Reinecke committed
34
           'makeDomain', 'sqrt', 'exp', 'log', 'tanh', 'conjugate',
35
36
           'get_signal_variance']

37

38
def PS_field(pspace, func):
Martin Reinecke's avatar
Martin Reinecke committed
39
40
41
    if not isinstance(pspace, PowerSpace):
        raise TypeError
    data = dobj.from_global_data(func(pspace.k_lengths))
42
    return Field(pspace, val=data)
Martin Reinecke's avatar
Martin Reinecke committed
43

Martin Reinecke's avatar
Martin Reinecke committed
44

45
46
47
48
49
50
51
52
53
54
55
56
57
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
58
59
60
61
        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
62
63
64
65
    """
    if space.harmonic:
        space = PowerSpace(space)
    if not isinstance(space, PowerSpace):
Martin Reinecke's avatar
Martin Reinecke committed
66
67
        raise ValueError(
            "space must be either a harmonic space or Power space.")
68
69
70
71
72
    field = PS_field(space, spec)
    dist = PowerDistributor(space.harmonic_partner, space)
    k_field = dist(field)
    return k_field.weight(2).sum()

73

74
75
def _single_power_analyze(field, idx, binbounds):
    power_domain = PowerSpace(field.domain[idx], binbounds)
Martin Reinecke's avatar
Martin Reinecke committed
76
77
    pd = PowerDistributor(field.domain, power_domain, idx)
    return pd.adjoint_times(field.weight(1)).weight(-1)  # divides by bin size
78
79


Martin Reinecke's avatar
Martin Reinecke committed
80
81
# MR FIXME: this function is not well suited for analyzing more than one
# subdomain at once, because it allows only one set of binbounds.
82
83
def power_analyze(field, spaces=None, binbounds=None,
                  keep_phase_information=False):
Martin Reinecke's avatar
Martin Reinecke committed
84
    """ Computes the power spectrum for a subspace of `field`.
85
86
87
88

    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
89
90
    harmonic space. The resulting field has the same units as the square of the
    initial field.
91
92
93
94
95

    Parameters
    ----------
    field : Field
        The field to be analyzed
Martin Reinecke's avatar
Martin Reinecke committed
96
97
98
    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
99
        If None, all subdomains will be converted.
100
        (default : None).
Martin Reinecke's avatar
Martin Reinecke committed
101
    binbounds : None or array-like, optional
102
        Inner bounds of the bins (default : None).
Martin Reinecke's avatar
Martin Reinecke committed
103
104
        if binbounds is None : bins are inferred.
    keep_phase_information : bool, optional
105
106
107
108
109
110
111
112
113
114
115
116
        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
117
    Field
118
        The output object. Its domain is a PowerSpace and it contains
Martin Reinecke's avatar
Martin Reinecke committed
119
        the power spectrum of `field`.
120
121
122
123
    """

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

127
    spaces = utilities.parse_spaces(spaces, len(field.domain))
128
129
130
131

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

132
133
134
135
    field_real = not np.issubdtype(field.dtype, np.complexfloating)
    if (not field_real) and keep_phase_information:
        raise ValueError("cannot keep phase from real-valued input Field")

136
137
138
    if keep_phase_information:
        parts = [field.real*field.real, field.imag*field.imag]
    else:
139
140
141
142
        if field_real:
            parts = [field**2]
        else:
            parts = [field.real*field.real + field.imag*field.imag]
143
144

    for space_index in spaces:
Martin Reinecke's avatar
Martin Reinecke committed
145
        parts = [_single_power_analyze(part, space_index, binbounds)
146
147
148
149
150
                 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
151
def _create_power_field(domain, power_spectrum):
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
152
153
154
155
156
157
158
159
    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]
160
        fp = Field(power_domain, val=power_spectrum.val)
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
161
162
    else:
        power_domain = PowerSpace(domain)
163
        fp = PS_field(power_domain, power_spectrum)
164

Martin Reinecke's avatar
Martin Reinecke committed
165
    return PowerDistributor(domain, power_domain)(fp)
166

167

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

171
    Constructs a diagonal operator that lives over the specified domain.
172

173
174
    Parameters
    ----------
Martin Reinecke's avatar
Martin Reinecke committed
175
    domain : Domain, tuple of Domain or DomainTuple
176
        Domain over which the power operator shall live.
Martin Reinecke's avatar
Martin Reinecke committed
177
178
    power_spectrum : callable or Field
        An object that contains the power spectrum as a function of k.
Martin Reinecke's avatar
Martin Reinecke committed
179
    space : int
Martin Reinecke's avatar
Martin Reinecke committed
180
        the domain index on which the power operator will work
Theo Steininger's avatar
Theo Steininger committed
181

182
183
    Returns
    -------
Martin Reinecke's avatar
Martin Reinecke committed
184
185
    DiagonalOperator
        An operator that implements the given power spectrum.
186
    """
Martin Reinecke's avatar
Martin Reinecke committed
187
    domain = DomainTuple.make(domain)
Martin Reinecke's avatar
Martin Reinecke committed
188
    space = utilities.infer_space(domain, space)
Martin Reinecke's avatar
Martin Reinecke committed
189
190
    field = _create_power_field(domain[space], power_spectrum)
    return DiagonalOperator(field, domain, space)
191

192

193
194
195
196
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229


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


def empty(domain, dtype):
    if isinstance(domain, (dict, MultiDomain)):
        return MultiField.empty(domain, dtype)
    return Field.empty(domain, dtype)


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
230
    if isinstance(domain, (MultiDomain, dict)):
Martin Reinecke's avatar
step 1    
Martin Reinecke committed
231
232
        return MultiDomain.make(domain)
    return DomainTuple.make(domain)
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250


# Arithmetic functions working on Fields

_current_module = sys.modules[__name__]

for f in ["sqrt", "exp", "log", "tanh", "conjugate"]:
    def func(f):
        def func2(x, out=None):
            if isinstance(x, MultiField):
                if out is not None:
                    if (not isinstance(out, MultiField) or
                            x._domain != out._domain):
                        raise ValueError("Bad 'out' argument")
                    for key, value in x.items():
                        func2(value, out=out[key])
                    return out
                return MultiField({key: func2(val) for key, val in x.items()})
251
252
253
254
255
256
257
258
259
            elif isinstance(x, Field):
                fu = getattr(dobj, f)
                if out is not None:
                    if not isinstance(out, Field) or x._domain != out._domain:
                        raise ValueError("Bad 'out' argument")
                    fu(x.val, out=out.val)
                    return out
                else:
                    return Field(domain=x._domain, val=fu(x.val))
260
            else:
261
                return getattr(np, f)(x, out)
262
263
        return func2
    setattr(_current_module, f, func(f))