fft_operator.py 10 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
20
import numpy as np

Martin Reinecke's avatar
Martin Reinecke committed
21
22
23
24
25
from ... import nifty_utilities as utilities
from ...spaces import RGSpace,\
                      GLSpace,\
                      HPSpace,\
                      LMSpace
26

Martin Reinecke's avatar
Martin Reinecke committed
27
from ..linear_operator import LinearOperator
Martin Reinecke's avatar
Martin Reinecke committed
28
from .transformations import RGRGTransformation,\
29
30
31
32
33
                            LMGLTransformation,\
                            LMHPTransformation,\
                            GLLMTransformation,\
                            HPLMTransformation,\
                            TransformationCache
Jait Dixit's avatar
Jait Dixit committed
34
35


Jait Dixit's avatar
Jait Dixit committed
36
class FFTOperator(LinearOperator):
37
38
39
    """Transforms between a pair of position and harmonic domains.

    Built-in domain pairs are
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
      - a harmonic and a non-harmonic RGSpace (with matching distances)
      - a HPSpace and a LMSpace
      - a GLSpace and a LMSpace
    Within a domain pair, both orderings are possible.

    The operator provides a "times" and an "adjoint_times" operation.
    For a pair of RGSpaces, the "adjoint_times" operation is equivalent to
    "inverse_times"; for the sphere-related domains this is not the case, since
    the operator matrix is not square.

    Parameters
    ----------
    domain: Space or single-element tuple of Spaces
        The domain of the data that is input by "times" and output by
        "adjoint_times".
55
    target: Space or single-element tuple of Spaces (optional)
56
57
58
59
        The domain of the data that is output by "times" and input by
        "adjoint_times".
        If omitted, a co-domain will be chosen automatically.
        Whenever "domain" is an RGSpace, the codomain (and its parameters) are
Martin Reinecke's avatar
Martin Reinecke committed
60
        uniquely determined (except for "zerocenter").
61
62
        For GLSpace, HPSpace, and LMSpace, a sensible (but not unique)
        co-domain is chosen that should work satisfactorily in most situations,
Martin Reinecke's avatar
Martin Reinecke committed
63
        but for full control, the user should explicitly specify a codomain.
64
65
    module: String (optional)
        Software module employed for carrying out the transform operations.
Martin Reinecke's avatar
Martin Reinecke committed
66
67
68
69
        For RGSpace pairs this can be "scalar" or "mpi", where "scalar" is
        always available (using pyfftw if available, else numpy.fft), and "mpi"
        requires pyfftw and offers MPI parallelization.
        For sphere-related domains, only "pyHealpix" is
70
71
        available. If omitted, "fftw" is selected for RGSpaces if available,
        else "numpy"; on the sphere the default is "pyHealpix".
72
73
    domain_dtype: data type (optional)
        Data type of the fields that go into "times" and come out of
74
        "adjoint_times". Default is "numpy.complex".
75
76
77
78
79
80
81
82
83
84
85
86
87
    target_dtype: data type (optional)
        Data type of the fields that go into "adjoint_times" and come out of
        "times". Default is "numpy.complex".

    Attributes
    ----------
    domain: Tuple of Spaces (with one entry)
        The domain of the data that is input by "times" and output by
        "adjoint_times".
    target: Tuple of Spaces (with one entry)
        The domain of the data that is output by "times" and input by
        "adjoint_times".
    unitary: bool
88
89
        Returns True if the operator is unitary (currently only the case if
        the domain and codomain are RGSpaces), else False.
90
91
92
93
94

    Raises
    ------
    ValueError:
        if "domain" or "target" are not of the proper type.
95

96
    """
97

98
    # ---Class attributes---
99

100
101
102
    default_codomain_dictionary = {RGSpace: RGSpace,
                                   HPSpace: LMSpace,
                                   GLSpace: LMSpace,
103
                                   LMSpace: GLSpace,
104
105
106
107
108
109
110
111
112
                                   }

    transformation_dictionary = {(RGSpace, RGSpace): RGRGTransformation,
                                 (HPSpace, LMSpace): HPLMTransformation,
                                 (GLSpace, LMSpace): GLLMTransformation,
                                 (LMSpace, HPSpace): LMHPTransformation,
                                 (LMSpace, GLSpace): LMGLTransformation
                                 }

Jait Dixit's avatar
Jait Dixit committed
113
114
    # ---Overwritten properties and methods---

115
    def __init__(self, domain, target=None, module=None,
116
117
                 domain_dtype=None, target_dtype=None, default_spaces=None):
        super(FFTOperator, self).__init__(default_spaces)
118
119

        # Initialize domain and target
120
121

        self._domain = self._parse_domain(domain)
122
        if len(self.domain) != 1:
123
124
            raise ValueError("TransformationOperator accepts only exactly one "
                             "space as input domain.")
Jait Dixit's avatar
Jait Dixit committed
125

126
        if target is None:
127
            target = (self.get_default_codomain(self.domain[0]), )
Jait Dixit's avatar
Jait Dixit committed
128
        self._target = self._parse_domain(target)
129
130
131
        if len(self.target) != 1:
            raise ValueError("TransformationOperator accepts only exactly one "
                             "space as output target.")
Jait Dixit's avatar
Jait Dixit committed
132

133
        # Create transformation instances
134
        forward_class = self.transformation_dictionary[
135
                (self.domain[0].__class__, self.target[0].__class__)]
136
        backward_class = self.transformation_dictionary[
137
138
139
140
141
142
143
                (self.target[0].__class__, self.domain[0].__class__)]

        self._forward_transformation = TransformationCache.create(
            forward_class, self.domain[0], self.target[0], module=module)

        self._backward_transformation = TransformationCache.create(
            backward_class, self.target[0], self.domain[0], module=module)
Jait Dixit's avatar
Jait Dixit committed
144

145
146
        # Store the dtype information
        if domain_dtype is None:
147
148
            self.logger.info("Setting domain_dtype to np.complex.")
            self.domain_dtype = np.complex
149
150
151
152
        else:
            self.domain_dtype = np.dtype(domain_dtype)

        if target_dtype is None:
153
154
            self.logger.info("Setting target_dtype to np.complex.")
            self.target_dtype = np.complex
155
156
157
158
        else:
            self.target_dtype = np.dtype(target_dtype)

    def _times(self, x, spaces):
159
        spaces = utilities.cast_axis_to_tuple(spaces, len(x.domain))
160
        if spaces is None:
161
162
163
164
            # this case means that x lives on only one space, which is
            # identical to the space in the domain of `self`. Otherwise the
            # input check of LinearOperator would have failed.
            axes = x.domain_axes[0]
165
166
        else:
            axes = x.domain_axes[spaces[0]]
167

168
        new_val = self._forward_transformation.transform(x.val, axes=axes)
169

170
171
172
173
174
        if spaces is None:
            result_domain = self.target
        else:
            result_domain = list(x.domain)
            result_domain[spaces[0]] = self.target[0]
175

176
177
        result_field = x.copy_empty(domain=result_domain,
                                    dtype=self.target_dtype)
Theo Steininger's avatar
Theo Steininger committed
178
        result_field.set_val(new_val=new_val, copy=True)
Jait Dixit's avatar
Jait Dixit committed
179

180
        return result_field
Jait Dixit's avatar
Jait Dixit committed
181

182
    def _adjoint_times(self, x, spaces):
Jait Dixit's avatar
Jait Dixit committed
183
        spaces = utilities.cast_axis_to_tuple(spaces, len(x.domain))
184
        if spaces is None:
185
186
187
188
            # this case means that x lives on only one space, which is
            # identical to the space in the domain of `self`. Otherwise the
            # input check of LinearOperator would have failed.
            axes = x.domain_axes[0]
189
190
        else:
            axes = x.domain_axes[spaces[0]]
Jait Dixit's avatar
Jait Dixit committed
191

192
        new_val = self._backward_transformation.transform(x.val, axes=axes)
193
194
195
196
197
198
199

        if spaces is None:
            result_domain = self.domain
        else:
            result_domain = list(x.domain)
            result_domain[spaces[0]] = self.domain[0]

200
201
        result_field = x.copy_empty(domain=result_domain,
                                    dtype=self.domain_dtype)
Theo Steininger's avatar
Theo Steininger committed
202
        result_field.set_val(new_val=new_val, copy=True)
203
204

        return result_field
Jait Dixit's avatar
Jait Dixit committed
205
206
207

    # ---Mandatory properties and methods---

208
209
210
211
    @property
    def domain(self):
        return self._domain

Jait Dixit's avatar
Jait Dixit committed
212
213
214
215
    @property
    def target(self):
        return self._target

216
217
    @property
    def unitary(self):
218
219
        return (self._forward_transformation.unitary and
                self._backward_transformation.unitary)
220
221
222
223
224

    # ---Added properties and methods---

    @classmethod
    def get_default_codomain(cls, domain):
225
        """Returns a codomain to the given domain.
226
227
228
229
230
231
232
233
234
235
236
237

        Parameters
        ----------
        domain: Space
            An instance of RGSpace, HPSpace, GLSpace or LMSpace.

        Returns
        -------
        target: Space
            A (more or less perfect) counterpart to "domain" with respect
            to a FFT operation.
            Whenever "domain" is an RGSpace, the codomain (and its parameters)
Martin Reinecke's avatar
Martin Reinecke committed
238
239
240
241
242
            are uniquely determined (except for "zerocenter").
            For GLSpace, HPSpace, and LMSpace, a sensible (but not unique)
            co-domain is chosen that should work satisfactorily in most
            situations. For full control however, the user should not rely on
            this method.
243
244
245
246
247

        Raises
        ------
        ValueError:
            if no default codomain is defined for "domain".
248

249
        """
250
251
252
253
        domain_class = domain.__class__
        try:
            codomain_class = cls.default_codomain_dictionary[domain_class]
        except KeyError:
254
            raise ValueError("Unknown domain")
255
256
257
258
259

        try:
            transform_class = cls.transformation_dictionary[(domain_class,
                                                             codomain_class)]
        except KeyError:
260
            raise ValueError(
261
                "No transformation for domain-codomain pair found.")
262
263

        return transform_class.get_codomain(domain)