fft_operator_support.py 7.85 KB
Newer Older
Martin Reinecke's avatar
Martin Reinecke committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 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/>.
#
# 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.

from __future__ import division
import numpy as np
from ... import nifty_utilities as utilities


Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
24
class Transformation(object):
Martin Reinecke's avatar
Martin Reinecke committed
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
    def __init__(self, domain, codomain):
        self.domain = domain
        self.codomain = codomain

    def unitary(self):
        raise NotImplementedError

    def transform(self, val, axes=None):
        raise NotImplementedError


class RGRGTransformation(Transformation):
    def __init__(self, domain, codomain=None):
        import pyfftw
        super(RGRGTransformation, self).__init__(domain, codomain)
        pyfftw.interfaces.cache.enable()

    @property
    def unitary(self):
        return True

Martin Reinecke's avatar
tuning    
Martin Reinecke committed
46
47
48
49
50
51
    @staticmethod
    def _fill_upper_half(tmp, res, axes):
        lastaxis = axes[-1]
        nlast = res.shape[lastaxis]
        ntmplast = tmp.shape[lastaxis]
        nrem = nlast - ntmplast
Martin Reinecke's avatar
Martin Reinecke committed
52
53
54
        slice1 = [slice(None)]*lastaxis + [slice(ntmplast, None)]
        slice2 = [slice(None)]*lastaxis + [slice(nrem, 0, -1)]
        for i in axes[:-1]:
Martin Reinecke's avatar
tuning    
Martin Reinecke committed
55
56
            slice1[i] = slice(1, None)
            slice2[i] = slice(None, 0, -1)
Martin Reinecke's avatar
Martin Reinecke committed
57
        np.subtract(tmp[slice2].real, tmp[slice2].imag, out=res[slice1])
Martin Reinecke's avatar
Martin Reinecke committed
58
59
        for i, ax in enumerate(axes[:-1]):
            dim1 = [slice(None)]*ax + [slice(0,1)]
Martin Reinecke's avatar
tuning    
Martin Reinecke committed
60
61
62
            axes2 = axes[:i] + axes[i+1:]
            RGRGTransformation._fill_upper_half(tmp[dim1], res[dim1], axes2)

Martin Reinecke's avatar
Martin Reinecke committed
63
64
    @staticmethod
    def _hartley(a, axes=None):
Martin Reinecke's avatar
Martin Reinecke committed
65
66
        # Check if the axes provided are valid given the shape
        if axes is not None and \
Martin Reinecke's avatar
Martin Reinecke committed
67
                not all(axis<len(a.shape) for axis in axes):
Martin Reinecke's avatar
Martin Reinecke committed
68
69
            raise ValueError("Provided axes does not match array shape")

Martin Reinecke's avatar
Martin Reinecke committed
70
        from pyfftw.interfaces.numpy_fft import rfftn
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
71
72
73
        if issubclass(a.dtype.type, np.complexfloating):
            raise TypeError("Hartley tansform requires real-valued arrays.")
        tmp = rfftn(a, axes=axes)
Martin Reinecke's avatar
Martin Reinecke committed
74
75
        res = np.empty_like(a)
        if axes is None:
Martin Reinecke's avatar
Martin Reinecke committed
76
            axes = range(a.ndim)
Martin Reinecke's avatar
Martin Reinecke committed
77
78
79
80
        lastaxis = axes[-1]
        nlast = a.shape[lastaxis]
        ntmplast = tmp.shape[lastaxis]
        nrem = nlast - ntmplast
Martin Reinecke's avatar
Martin Reinecke committed
81
        slice1 = [slice(None)]*lastaxis + [slice(0, ntmplast)]
Martin Reinecke's avatar
Martin Reinecke committed
82
        np.add(tmp.real, tmp.imag, out=res[slice1])
Martin Reinecke's avatar
Martin Reinecke committed
83
        RGRGTransformation._fill_upper_half(tmp, res, axes)
Martin Reinecke's avatar
Martin Reinecke committed
84
        return res
Martin Reinecke's avatar
Martin Reinecke committed
85
86
87
88
89
90
91
92
93
94
95
96
97
98

    def transform(self, val, axes=None):
        """
        RG -> RG transform method.

        Parameters
        ----------
        val : np.ndarray or distributed_data_object
            The value array which is to be transformed

        axes : None or tuple
            The axes along which the transformation should take place

        """
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
99
100
101
102
103
        # correct for forward/inverse fft.
        # naively one would set power to 0.5 here in order to
        # apply effectively a factor of 1/sqrt(N) to the field.
        # BUT: the pixel volumes of the domain and codomain are different.
        # Hence, in order to produce the same scalar product, power==1.
Martin Reinecke's avatar
Martin Reinecke committed
104
        if self.codomain.harmonic:
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
105
106
            fct = self.domain.weight()
        else:
Martin Reinecke's avatar
Martin Reinecke committed
107
            fct = 1./(self.codomain.weight()*self.domain.dim)
Martin Reinecke's avatar
Martin Reinecke committed
108
109
110

        # Perform the transformation
        if issubclass(val.dtype.type, np.complexfloating):
Martin Reinecke's avatar
Martin Reinecke committed
111
112
            Tval = self._hartley(val.real, axes) \
                  +1j*self._hartley(val.imag, axes)
Martin Reinecke's avatar
Martin Reinecke committed
113
        else:
Martin Reinecke's avatar
Martin Reinecke committed
114
            Tval = self._hartley(val, axes)
Martin Reinecke's avatar
Martin Reinecke committed
115
116
117
118
119
120
121
122
123

        Tval *= fct
        return Tval


class SlicingTransformation(Transformation):
    def transform(self, val, axes=None):
        return_shape = np.array(val.shape)
        return_shape[list(axes)] = self.codomain.shape
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
124
        return_val = np.empty(tuple(return_shape), dtype=val.dtype)
Martin Reinecke's avatar
Martin Reinecke committed
125

Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
126
127
        for slice in utilities.get_slice_list(val.shape, axes):
            return_val[slice] = self._transformation_of_slice(val[slice])
Martin Reinecke's avatar
Martin Reinecke committed
128
129
130
131
132
133
134
        return return_val

    def _transformation_of_slice(self, inp):
        raise NotImplementedError


def buildLm(nr, lmax):
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
135
    new_dtype = np.result_type(nr[0]*1j)
Martin Reinecke's avatar
Martin Reinecke committed
136
137
138
139
140
141
142
143
144

    size = (len(nr)-lmax-1)//2+lmax+1
    res = np.empty([size], dtype=new_dtype)
    res[0:lmax+1] = nr[0:lmax+1]
    res[lmax+1:] = np.sqrt(0.5)*(nr[lmax+1::2] + 1j*nr[lmax+2::2])
    return res


def buildIdx(nr, lmax):
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
145
    new_dtype = np.result_type(nr[0].real)
Martin Reinecke's avatar
Martin Reinecke committed
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245

    size = (lmax+1)*(lmax+1)
    final = np.empty(size, dtype=new_dtype)
    final[0:lmax+1] = nr[0:lmax+1].real
    final[lmax+1::2] = np.sqrt(2)*nr[lmax+1:].real
    final[lmax+2::2] = np.sqrt(2)*nr[lmax+1:].imag
    return final


class HPLMTransformation(SlicingTransformation):
    @property
    def unitary(self):
        return False

    def _transformation_of_slice(self, inp):
        from pyHealpix import map2alm

        lmax = self.codomain.lmax
        mmax = lmax

        if issubclass(inp.dtype.type, np.complexfloating):
            rr = map2alm(inp.real, lmax, mmax)
            rr = buildIdx(rr, lmax=lmax)
            ri = map2alm(inp.imag, lmax, mmax)
            ri = buildIdx(ri, lmax=lmax)
            return rr + 1j*ri
        else:
            rr = map2alm(inp, lmax, mmax)
            return buildIdx(rr, lmax=lmax)


class LMHPTransformation(SlicingTransformation):
    @property
    def unitary(self):
        return False

    def _transformation_of_slice(self, inp):
        from pyHealpix import alm2map

        nside = self.codomain.nside
        lmax = self.domain.lmax
        mmax = lmax

        if issubclass(inp.dtype.type, np.complexfloating):
            rr = buildLm(inp.real, lmax=lmax)
            ri = buildLm(inp.imag, lmax=lmax)
            rr = alm2map(rr, lmax, mmax, nside)
            ri = alm2map(ri, lmax, mmax, nside)
            return rr + 1j*ri
        else:
            rr = buildLm(inp, lmax=lmax)
            return alm2map(rr, lmax, mmax, nside)


class GLLMTransformation(SlicingTransformation):
    @property
    def unitary(self):
        return False

    def _transformation_of_slice(self, inp):
        from pyHealpix import sharpjob_d

        lmax = self.codomain.lmax
        mmax = self.codomain.mmax

        sjob = sharpjob_d()
        sjob.set_Gauss_geometry(self.domain.nlat, self.domain.nlon)
        sjob.set_triangular_alm_info(lmax, mmax)
        if issubclass(inp.dtype.type, np.complexfloating):
            rr = sjob.map2alm(inp.real)
            rr = buildIdx(rr, lmax=lmax)
            ri = sjob.map2alm(inp.imag)
            ri = buildIdx(ri, lmax=lmax)
            return rr + 1j*ri
        else:
            rr = sjob.map2alm(inp)
            return buildIdx(rr, lmax=lmax)


class LMGLTransformation(SlicingTransformation):
    @property
    def unitary(self):
        return False

    def _transformation_of_slice(self, inp):
        from pyHealpix import sharpjob_d

        lmax = self.domain.lmax
        mmax = self.domain.mmax

        sjob = sharpjob_d()
        sjob.set_Gauss_geometry(self.codomain.nlat, self.codomain.nlon)
        sjob.set_triangular_alm_info(lmax, mmax)
        if issubclass(inp.dtype.type, np.complexfloating):
            rr = buildLm(inp.real, lmax=lmax)
            ri = buildLm(inp.imag, lmax=lmax)
            return sjob.alm2map(rr) + 1j*sjob.alm2map(ri)
        else:
            result = buildLm(inp, lmax=lmax)
            return sjob.alm2map(result)