sugar.py 11.6 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
15
16
17
#
# Copyright(C) 2013-2017 Max-Planck-Society
#
# 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
from . import Space, PowerSpace, Field, ComposedOperator, DiagonalOperator,\
Martin Reinecke's avatar
Martin Reinecke committed
21
22
              PowerProjectionOperator, FFTOperator, sqrt, DomainTuple, dobj,\
              utilities
23

Martin Reinecke's avatar
Martin Reinecke committed
24
25
__all__ = ['PS_field',
           'power_analyze',
26
27
28
           'power_synthesize',
           'power_synthesize_special',
           'create_power_field',
29
           'create_power_operator',
30
31
           'generate_posterior_sample',
           'create_composed_fft_operator']
32
33


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

Martin Reinecke's avatar
Martin Reinecke committed
40

41
42
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
def _single_power_analyze(field, idx, binbounds):
    from .operators.power_projection_operator import PowerProjectionOperator
    power_domain = PowerSpace(field.domain[idx], binbounds)
    ppo = PowerProjectionOperator(field.domain, power_domain, idx)
    return ppo(field.weight(-1))


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
    spaces : int *optional*
        The subspace for which the powerspectrum shall be computed.
        (default : None).
    binbounds : array-like *optional*
        Inner bounds of the bins (default : None).
        if binbounds==None : bins are inferred.
    keep_phase_information : boolean, *optional*
        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).

    Raise
    -----
    TypeError
        Raised if any of the input field's domains is not harmonic

    Returns
    -------
    out : Field
        The output object. Its domain is a PowerSpace and it contains
        the power spectrum of 'field'.
    """

    # check if all spaces in `field.domain` are either harmonic or
    # power_space instances
    for sp in field.domain:
        if not sp.harmonic and not isinstance(sp, PowerSpace):
Martin Reinecke's avatar
Martin Reinecke committed
95
96
            dobj.mprint("WARNING: Field has a space in `domain` which is "
                        "neither harmonic nor a PowerSpace.")
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212

    # check if the `spaces` input is valid
    if spaces is None:
        spaces = range(len(field.domain))
    else:
        spaces = utilities.cast_iseq_to_tuple(spaces)

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

    if keep_phase_information:
        parts = [field.real*field.real, field.imag*field.imag]
    else:
        parts = [field.real*field.real + field.imag*field.imag]

    parts = [part.weight(1, spaces) for part in parts]
    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]


def _compute_spec(field, spaces):
    from .operators.power_projection_operator import PowerProjectionOperator
    if spaces is None:
        spaces = range(len(field.domain))
    else:
        spaces = utilities.cast_iseq_to_tuple(spaces)

    # create the result domain
    result_domain = list(field.domain)

    spec = sqrt(field)
    for i in spaces:
        result_domain[i] = field.domain[i].harmonic_partner
        ppo = PowerProjectionOperator(result_domain, field.domain[i], i)
        spec = ppo.adjoint_times(spec)

    return spec


def power_synthesize(field, spaces=None, real_power=True, real_signal=True):
    """ Yields a sampled field with `field`**2 as its power spectrum.

    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
        The input field containing the square root of the power spectrum
    spaces : {tuple, int, None} *optional*
        Specifies the subspace containing all the PowerSpaces which
        should be converted (default : None).
        if spaces==None : Tries to convert the whole domain.
    real_power : boolean *optional*
        Determines whether the power spectrum is treated as intrinsically
        real or complex (default : True).
    real_signal : boolean *optional*
        True will result in a purely real signal-space field
        (default : True).

    Returns
    -------
    out : Field
        The output object. A random field created with the power spectrum
        stored in the `spaces` in `field`.

    Notes
    -----
    For this the spaces specified by `spaces` must be a PowerSpace.
    This expects this field to be the square root of a power spectrum, i.e.
    to have the unit of the field to be sampled.

    Raises
    ------
    ValueError : If domain specified by `spaces` is not a PowerSpace.

    """

    spec = _compute_spec(field, spaces)

    # 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,
                                dtype=np.float if real_signal
                                else np.complex)
              for x in range(1 if real_power else 2)]

    # MR: dummy call - will be removed soon
    if real_signal:
        field.from_random('normal', mean=0., std=1.,
                          domain=spec.domain, dtype=np.float)

    # apply the rescaler to the random fields
    result[0] *= spec.real
    if not real_power:
        result[1] *= spec.imag

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


def power_synthesize_special(field, spaces=None):
    spec = _compute_spec(field, spaces)

    # MR: dummy call - will be removed soon
    field.from_random('normal', mean=0., std=1.,
                      domain=spec.domain, dtype=np.complex)

    return spec.real


213
def create_power_field(domain, power_spectrum, dtype=None):
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
214
215
216
217
218
219
220
221
222
223
224
    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]
        fp = Field(power_domain, val=power_spectrum.val, dtype=dtype)
    else:
        power_domain = PowerSpace(domain)
Martin Reinecke's avatar
Martin Reinecke committed
225
        fp = PS_field(power_domain, power_spectrum, dtype)
Martin Reinecke's avatar
Martin Reinecke committed
226
227
    P = PowerProjectionOperator(domain, power_domain)
    f = P.adjoint_times(fp)
228
229
230
231
232
233

    if not issubclass(fp.dtype.type, np.complexfloating):
        f = f.real

    return f

234

Martin Reinecke's avatar
Martin Reinecke committed
235
def create_power_operator(domain, power_spectrum, space=None, dtype=None):
Theo Steininger's avatar
Theo Steininger committed
236
    """ Creates a diagonal operator with the given power spectrum.
237

238
    Constructs a diagonal operator that lives over the specified domain.
239

240
241
242
    Parameters
    ----------
    domain : DomainObject
243
        Domain over which the power operator shall live.
Martin Reinecke's avatar
Martin Reinecke committed
244
245
246
247
    power_spectrum : callable of Field
        An object that implements the power spectrum as a function of k.
    space : int
            the domain index on which the power operator will work
Theo Steininger's avatar
Theo Steininger committed
248
    dtype : type *optional*
249
        dtype that the field holding the power spectrum shall use
Theo Steininger's avatar
Theo Steininger committed
250
251
252
        (default : None).
        if dtype == None: the dtype of `power_spectrum` will be used.

253
254
    Returns
    -------
Theo Steininger's avatar
Theo Steininger committed
255
    DiagonalOperator : An operator that implements the given power spectrum.
256

257
    """
Martin Reinecke's avatar
Martin Reinecke committed
258
259
    domain = DomainTuple.make(domain)
    if space is None:
Martin Reinecke's avatar
Martin Reinecke committed
260
        if len(domain) != 1:
Martin Reinecke's avatar
Martin Reinecke committed
261
262
263
264
            raise ValueError("space keyword must be set")
        else:
            space = 0
    space = int(space)
265
    return DiagonalOperator(
Martin Reinecke's avatar
Martin Reinecke committed
266
267
268
269
        create_power_field(domain[space],
                           power_spectrum, dtype).weight(1),
        domain=domain,
        spaces=space)
270

271

272
273
274
def generate_posterior_sample(mean, covariance):
    """ Generates a posterior sample from a Gaussian distribution with given
    mean and covariance
275

276
277
278
    This method generates samples by setting up the observation and
    reconstruction of a mock signal in order to obtain residuals of the right
    correlation which are added to the given mean.
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293

    Parameters
    ----------
    mean : Field
        the mean of the posterior Gaussian distribution
    covariance : WienerFilterCurvature
        The posterior correlation structure consisting of a
        response operator, noise covariance and prior signal covariance

    Returns
    -------
    sample : Field
        Returns the a sample from the Gaussian of given mean and covariance.
    """

294
295
296
    S = covariance.op.S
    R = covariance.op.R
    N = covariance.op.N
297

298
    power = sqrt(power_analyze(S.diagonal()))
299
    mock_signal = power_synthesize(power, real_signal=True)
300

301
    noise = N.diagonal().weight(-1)
302

303
    mock_noise = Field.from_random(random_type="normal", domain=N.domain,
Martin Reinecke's avatar
Martin Reinecke committed
304
                                   dtype=noise.dtype.type)
305
306
    mock_noise *= sqrt(noise)

Jakob Knollmueller's avatar
Jakob Knollmueller committed
307
    mock_data = R(mock_signal) + mock_noise
308

Jakob Knollmueller's avatar
Jakob Knollmueller committed
309
    mock_j = R.adjoint_times(N.inverse_times(mock_data))
310
311
312
    mock_m = covariance.inverse_times(mock_j)
    sample = mock_signal - mock_m + mean
    return sample
313
314
315
316
317
318
319


def create_composed_fft_operator(domain, codomain=None, all_to='other'):
    fft_op_list = []

    if codomain is None:
        codomain = [None]*len(domain)
320
    interdomain = list(domain.domains)
Martin Reinecke's avatar
Martin Reinecke committed
321
    for i, space in enumerate(domain):
322
323
324
325
326
        if not isinstance(space, Space):
            continue
        if (all_to == 'other' or
                (all_to == 'position' and space.harmonic) or
                (all_to == 'harmonic' and not space.harmonic)):
327
328
329
330
331
332
333
334
            if codomain[i] is None:
                interdomain[i] = domain[i].get_default_codomain()
            else:
                interdomain[i] = codomain[i]
            fft_op_list += [FFTOperator(domain=domain, target=interdomain,
                                        space=i)]
        domain = interdomain
    return ComposedOperator(fft_op_list)