sugar.py 6.07 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
from .domains.power_space import PowerSpace
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
21
from .field import Field
Martin Reinecke's avatar
Martin Reinecke committed
22
from .operators.diagonal_operator import DiagonalOperator
Martin Reinecke's avatar
Martin Reinecke committed
23
from .operators.power_distributor import PowerDistributor
Martin Reinecke's avatar
Martin Reinecke committed
24
25
from .domain_tuple import DomainTuple
from . import dobj, utilities
Martin Reinecke's avatar
Martin Reinecke committed
26
from .logger import logger
27

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


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

Martin Reinecke's avatar
Martin Reinecke committed
40

41
42
def _single_power_analyze(field, idx, binbounds):
    power_domain = PowerSpace(field.domain[idx], binbounds)
Martin Reinecke's avatar
Martin Reinecke committed
43
44
    pd = PowerDistributor(field.domain, power_domain, idx)
    return pd.adjoint_times(field.weight(1)).weight(-1)  # divides by bin size
45
46
47
48


def power_analyze(field, spaces=None, binbounds=None,
                  keep_phase_information=False):
Martin Reinecke's avatar
Martin Reinecke committed
49
    """ Computes the power spectrum for a subspace of `field`.
50
51
52
53

    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
54
55
    harmonic space. The resulting field has the same units as the square of the
    initial field.
56
57
58
59
60

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

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

92
    spaces = utilities.parse_spaces(spaces, len(field.domain))
93
94
95
96

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

97
98
99
100
    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")

101
102
103
    if keep_phase_information:
        parts = [field.real*field.real, field.imag*field.imag]
    else:
104
105
106
107
        if field_real:
            parts = [field**2]
        else:
            parts = [field.real*field.real + field.imag*field.imag]
108
109

    for space_index in spaces:
Martin Reinecke's avatar
Martin Reinecke committed
110
        parts = [_single_power_analyze(part, space_index, binbounds)
111
112
113
114
115
                 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
116
def _create_power_field(domain, power_spectrum):
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
117
118
119
120
121
122
123
124
    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]
125
        fp = Field(power_domain, val=power_spectrum.val)
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
126
127
    else:
        power_domain = PowerSpace(domain)
128
        fp = PS_field(power_domain, power_spectrum)
129

Martin Reinecke's avatar
Martin Reinecke committed
130
    return PowerDistributor(domain, power_domain)(fp)
131

132

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

136
    Constructs a diagonal operator that lives over the specified domain.
137

138
139
    Parameters
    ----------
Martin Reinecke's avatar
Martin Reinecke committed
140
    domain : Domain, tuple of Domain or DomainTuple
141
        Domain over which the power operator shall live.
Martin Reinecke's avatar
Martin Reinecke committed
142
143
    power_spectrum : callable or Field
        An object that contains the power spectrum as a function of k.
Martin Reinecke's avatar
Martin Reinecke committed
144
    space : int
Martin Reinecke's avatar
Martin Reinecke committed
145
        the domain index on which the power operator will work
Theo Steininger's avatar
Theo Steininger committed
146

147
148
    Returns
    -------
Martin Reinecke's avatar
Martin Reinecke committed
149
150
    DiagonalOperator
        An operator that implements the given power spectrum.
151
    """
Martin Reinecke's avatar
Martin Reinecke committed
152
    domain = DomainTuple.make(domain)
Martin Reinecke's avatar
Martin Reinecke committed
153
    space = utilities.infer_space(domain, space)
Martin Reinecke's avatar
Martin Reinecke committed
154
155
    field = _create_power_field(domain[space], power_spectrum)
    return DiagonalOperator(field, domain, space)
156

157

158
159
160
161
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)