sugar.py 8.85 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 numpy as np
Martin Reinecke's avatar
Martin Reinecke committed
20
21
from .domains.structured_domain import StructuredDomain
from .domains.power_space import PowerSpace
Martin Reinecke's avatar
Martin Reinecke committed
22
23
from .field import Field, sqrt
from .operators.diagonal_operator import DiagonalOperator
Martin Reinecke's avatar
Martin Reinecke committed
24
from .operators.power_distributor import PowerDistributor
25
from .operators.harmonic_transform_operator import HarmonicTransformOperator
Martin Reinecke's avatar
Martin Reinecke committed
26
27
from .domain_tuple import DomainTuple
from . import dobj, utilities
28

Martin Reinecke's avatar
Martin Reinecke committed
29
30
__all__ = ['PS_field',
           'power_analyze',
31
           'create_power_field',
32
           'create_power_operator',
33
           'create_harmonic_smoothing_operator']
34
35


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

Martin Reinecke's avatar
Martin Reinecke committed
42

43
44
def _single_power_analyze(field, idx, binbounds):
    power_domain = PowerSpace(field.domain[idx], binbounds)
Martin Reinecke's avatar
Martin Reinecke committed
45
46
    pd = PowerDistributor(field.domain, power_domain, idx)
    return pd.adjoint_times(field.weight(1)).weight(-1)  # divides by bin size
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62


def power_analyze(field, spaces=None, binbounds=None,
                  keep_phase_information=False):
    """ Computes the square root power spectrum for a subspace of `field`.

    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
    harmonic space. The resulting field has the same units as the initial
    field, corresponding to the square root of the power spectrum.

    Parameters
    ----------
    field : Field
        The field to be analyzed
Martin Reinecke's avatar
Martin Reinecke committed
63
64
65
    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
66
        If None, all subdomains will be converted.
67
        (default : None).
Martin Reinecke's avatar
Martin Reinecke committed
68
    binbounds : None or array-like, optional
69
        Inner bounds of the bins (default : None).
Martin Reinecke's avatar
Martin Reinecke committed
70
71
        if binbounds is None : bins are inferred.
    keep_phase_information : bool, optional
72
73
74
75
76
77
78
79
80
81
82
83
        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
84
    Field
85
        The output object. Its domain is a PowerSpace and it contains
Martin Reinecke's avatar
Martin Reinecke committed
86
        the power spectrum of `field`.
87
88
89
90
    """

    for sp in field.domain:
        if not sp.harmonic and not isinstance(sp, PowerSpace):
Martin Reinecke's avatar
Martin Reinecke committed
91
92
            dobj.mprint("WARNING: Field has a space in `domain` which is "
                        "neither harmonic nor a PowerSpace.")
93

94
    spaces = utilities.parse_spaces(spaces, len(field.domain))
95
96
97
98

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

99
100
101
102
    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")

103
104
105
    if keep_phase_information:
        parts = [field.real*field.real, field.imag*field.imag]
    else:
106
107
108
109
        if field_real:
            parts = [field**2]
        else:
            parts = [field.real*field.real + field.imag*field.imag]
110
111
112
113
114
115
116
117
118
119

    for space_index in spaces:
        parts = [_single_power_analyze(field=part,
                                       idx=space_index,
                                       binbounds=binbounds)
                 for part in parts]

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


120
def _power_synthesize_nonrandom(field, spaces=None):
121
    spaces = utilities.parse_spaces(spaces, len(field.domain))
122
123

    result_domain = list(field.domain)
124
    amplitude = sqrt(field)
125
126
    for i in spaces:
        result_domain[i] = field.domain[i].harmonic_partner
Martin Reinecke's avatar
Martin Reinecke committed
127
        pd = PowerDistributor(result_domain, field.domain[i], i)
128
        amplitude = pd(amplitude)
129

130
    return amplitude
131
132


133
134
def _power_synthesize(field, spaces=None, real_power=True, real_signal=True):
    """Returns a sampled field with `field` as its power spectrum.
135
136
137
138
139
140
141

    This method draws a Gaussian random field in the harmonic partner
    domain of this field's domains, using this field as power spectrum.

    Parameters
    ----------
    field : Field
142
        The input field containing the power spectrum
Martin Reinecke's avatar
Martin Reinecke committed
143
144
    spaces : None, int, or tuple of int, optional
        Specifies the subdomains containing all the PowerSpaces which
145
        should be converted (default : None).
Martin Reinecke's avatar
Martin Reinecke committed
146
147
        if spaces is None : Tries to convert the whole domain.
    real_power : bool, optional
148
149
        Determines whether the power spectrum is treated as intrinsically
        real or complex (default : True).
Martin Reinecke's avatar
Martin Reinecke committed
150
    real_signal : bool, optional
151
152
153
154
155
        True will result in a purely real signal-space field
        (default : True).

    Returns
    -------
Martin Reinecke's avatar
Martin Reinecke committed
156
    Field
157
158
159
160
161
        The output object. A random field created with the power spectrum
        stored in the `spaces` in `field`.

    Notes
    -----
162
163
164
    For this the spaces specified by `spaces` must be of type PowerSpace.
    This expects this field to be a power spectrum, i.e.
    to have the unit of "field to be sampled"**2.
165
166
167

    Raises
    ------
Martin Reinecke's avatar
Martin Reinecke committed
168
    ValueError : If a domain specified by `spaces` is not a PowerSpace.
169
170
    """

171
    spec = _power_synthesize_nonrandom(field, spaces)
172
173
174
    self_real = not np.issubdtype(spec.dtype, np.complexfloating)
    if (not real_power) and self_real:
        raise ValueError("can't draw complex realizations from real spectrum")
175
176
177
178
179

    # create random samples: one or two, depending on whether the
    # power spectrum is real or complex
    result = [field.from_random('normal', mean=0., std=1.,
                                domain=spec.domain,
Martin Reinecke's avatar
Martin Reinecke committed
180
181
                                dtype=np.float64 if real_signal
                                else np.complex128)
182
183
              for x in range(1 if real_power else 2)]

184
    result[0] *= spec if self_real else spec.real
185
186
187
188
189
190
    if not real_power:
        result[1] *= spec.imag

    return result[0] if real_power else result[0] + 1j*result[1]


191
def create_power_field(domain, power_spectrum):
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
192
193
194
195
196
197
198
199
    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]
200
        fp = Field(power_domain, val=power_spectrum.val)
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
201
202
    else:
        power_domain = PowerSpace(domain)
203
        fp = PS_field(power_domain, power_spectrum)
204

Martin Reinecke's avatar
Martin Reinecke committed
205
    return PowerDistributor(domain, power_domain)(fp)
206

207

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

211
    Constructs a diagonal operator that lives over the specified domain.
212

213
214
    Parameters
    ----------
Martin Reinecke's avatar
Martin Reinecke committed
215
    domain : Domain, tuple of Domain or DomainTuple
216
        Domain over which the power operator shall live.
Martin Reinecke's avatar
Martin Reinecke committed
217
218
    power_spectrum : callable or Field
        An object that contains the power spectrum as a function of k.
Martin Reinecke's avatar
Martin Reinecke committed
219
    space : int
Martin Reinecke's avatar
Martin Reinecke committed
220
        the domain index on which the power operator will work
Theo Steininger's avatar
Theo Steininger committed
221

222
223
    Returns
    -------
Martin Reinecke's avatar
Martin Reinecke committed
224
225
    DiagonalOperator
        An operator that implements the given power spectrum.
226
    """
Martin Reinecke's avatar
Martin Reinecke committed
227
    domain = DomainTuple.make(domain)
Martin Reinecke's avatar
Martin Reinecke committed
228
    space = utilities.infer_space(domain, space)
229
    return DiagonalOperator(
230
        create_power_field(domain[space], power_spectrum),
Martin Reinecke's avatar
Martin Reinecke committed
231
        domain=domain, spaces=space)
232

233

234
235
236
237
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)