fft_operator.py 9.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# NIFTy
# Copyright (C) 2017  Theo Steininger
#
# Author: Theo Steininger
#
# 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/>.
18

19
20
import numpy as np

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

Jait Dixit's avatar
Jait Dixit committed
27
from nifty.operators.linear_operator import LinearOperator
28
29
30
31
32
33
from transformations import RGRGTransformation,\
                            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.
66
67
68
69
70
        For RGSpace pairs this can be "numpy" or "fftw", where "numpy" is
        always available, but "fftw" offers higher performance and
        parallelization. For sphere-related domains, only "pyHealpix" is
        available. If omitted, "fftw" is selected for RGSpaces if available,
        else "numpy"; on the sphere the default is "pyHealpix".
71
72
    domain_dtype: data type (optional)
        Data type of the fields that go into "times" and come out of
73
        "adjoint_times". Default is "numpy.complex".
74
75
76
77
78
79
80
81
82
83
84
85
86
    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
87
88
        Returns True if the operator is unitary (currently only the case if
        the domain and codomain are RGSpaces), else False.
89
90
91
92
93

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

95
    """
96

97
    # ---Class attributes---
98

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

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

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

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

        # Initialize domain and target
119
120

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

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

132
        # Create transformation instances
133
        forward_class = self.transformation_dictionary[
134
                (self.domain[0].__class__, self.target[0].__class__)]
135
        backward_class = self.transformation_dictionary[
136
137
138
139
140
141
142
                (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
143

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

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

    def _times(self, x, spaces):
158
        spaces = utilities.cast_axis_to_tuple(spaces, len(x.domain))
159
        if spaces is None:
160
161
162
163
            # 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]
164
165
        else:
            axes = x.domain_axes[spaces[0]]
166

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

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

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

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

181
    def _adjoint_times(self, x, spaces):
Jait Dixit's avatar
Jait Dixit committed
182
        spaces = utilities.cast_axis_to_tuple(spaces, len(x.domain))
183
        if spaces is None:
184
185
186
187
            # 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]
188
189
        else:
            axes = x.domain_axes[spaces[0]]
Jait Dixit's avatar
Jait Dixit committed
190

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

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

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

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

    # ---Mandatory properties and methods---

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

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

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

    # ---Added properties and methods---

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

        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
237
238
239
240
241
            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.
242
243
244
245
246

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

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

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

        return transform_class.get_codomain(domain)