rgrgtransformation.py 6.06 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 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/>.

Jait Dixit's avatar
Jait Dixit committed
19
20
21
import numpy as np
from transformation import Transformation
from rg_transforms import FFTW, GFFT
22
from nifty.config import dependency_injector as gdi
Jait Dixit's avatar
Jait Dixit committed
23
24
25
26
from nifty import RGSpace, nifty_configuration


class RGRGTransformation(Transformation):
Jait Dixit's avatar
Jait Dixit committed
27
    def __init__(self, domain, codomain=None, module=None):
28
29
        super(RGRGTransformation, self).__init__(domain, codomain,
                                                 module=module)
Jait Dixit's avatar
Jait Dixit committed
30
31
32

        if module is None:
            if nifty_configuration['fft_module'] == 'pyfftw':
Jait Dixit's avatar
Jait Dixit committed
33
                self._transform = FFTW(self.domain, self.codomain)
34
35
            elif (nifty_configuration['fft_module'] == 'gfft' or
                  nifty_configuration['fft_module'] == 'gfft_dummy'):
Jait Dixit's avatar
Jait Dixit committed
36
                self._transform = \
Jait Dixit's avatar
Jait Dixit committed
37
38
                    GFFT(self.domain,
                         self.codomain,
Jait Dixit's avatar
Jait Dixit committed
39
                         gdi.get(nifty_configuration['fft_module']))
Jait Dixit's avatar
Jait Dixit committed
40
            else:
Jait Dixit's avatar
Jait Dixit committed
41
42
                raise ValueError('ERROR: unknow default FFT module:' +
                                 nifty_configuration['fft_module'])
Jait Dixit's avatar
Jait Dixit committed
43
        else:
Jait Dixit's avatar
Jait Dixit committed
44
            if module == 'pyfftw':
Jait Dixit's avatar
Jait Dixit committed
45
                self._transform = FFTW(self.domain, self.codomain)
Jait Dixit's avatar
Jait Dixit committed
46
47
            elif module == 'gfft':
                self._transform = \
Jait Dixit's avatar
Jait Dixit committed
48
                    GFFT(self.domain, self.codomain, gdi.get('gfft'))
Jait Dixit's avatar
Jait Dixit committed
49
50
            elif module == 'gfft_dummy':
                self._transform = \
Jait Dixit's avatar
Jait Dixit committed
51
                    GFFT(self.domain, self.codomain, gdi.get('gfft_dummy'))
Jait Dixit's avatar
Jait Dixit committed
52
53
            else:
                raise ValueError('ERROR: unknow FFT module:' + module)
Jait Dixit's avatar
Jait Dixit committed
54

55
56
    @classmethod
    def get_codomain(cls, domain, dtype=None, zerocenter=None):
Jait Dixit's avatar
Jait Dixit committed
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
        """
            Generates a compatible codomain to which transformations are
            reasonable, i.e.\  either a shifted grid or a Fourier conjugate
            grid.

            Parameters
            ----------
            domain: RGSpace
                Space for which a codomain is to be generated
            cozerocenter : {bool, numpy.ndarray}, *optional*
                Whether or not the grid is zerocentered for each axis or not
                (default: None).

            Returns
            -------
            codomain : nifty.rg_space
                A compatible codomain.
        """
        if not isinstance(domain, RGSpace):
            raise TypeError('ERROR: domain needs to be a RGSpace')

        # parse the cozerocenter input
79
        if zerocenter is None:
80
            zerocenter = domain.zerocenter
Jait Dixit's avatar
Jait Dixit committed
81
82
        # if the input is something scalar, cast it to a boolean
        else:
83
            temp = np.empty_like(domain.zerocenter)
84
            temp[:] = zerocenter
85
            zerocenter = temp
Jait Dixit's avatar
Jait Dixit committed
86
87

        # calculate the initialization parameters
88
89
        distances = 1 / (np.array(domain.shape) *
                         np.array(domain.distances))
90
        if dtype is None:
91
92
93
            # create a definitely complex dtype from the dtype of domain
            one = domain.dtype.type(1)
            dtype = np.dtype(type(one + 1j))
Jait Dixit's avatar
Jait Dixit committed
94

95
        new_space = RGSpace(domain.shape,
96
97
98
99
                            zerocenter=zerocenter,
                            distances=distances,
                            harmonic=(not domain.harmonic),
                            dtype=dtype)
100
        cls.check_codomain(domain, new_space)
Jait Dixit's avatar
Jait Dixit committed
101
102
        return new_space

103
104
    @classmethod
    def check_codomain(cls, domain, codomain):
Jait Dixit's avatar
Jait Dixit committed
105
        if not isinstance(domain, RGSpace):
106
            raise TypeError('ERROR: domain is not a RGSpace')
Jait Dixit's avatar
Jait Dixit committed
107
108
109
110
111

        if codomain is None:
            return False

        if not isinstance(codomain, RGSpace):
112
            return False
Jait Dixit's avatar
Jait Dixit committed
113

114
115
        if not np.all(np.array(domain.shape) ==
                      np.array(codomain.shape)):
Jait Dixit's avatar
Jait Dixit committed
116
117
118
119
120
            return False

        if domain.harmonic == codomain.harmonic:
            return False

121
122
        if codomain.harmonic and not issubclass(codomain.dtype.type,
                                                np.complexfloating):
123
            cls.logger.warn("Codomain is harmonic but dtype is real.")
124

Jait Dixit's avatar
Jait Dixit committed
125
126
        # Check if the distances match, i.e. dist' = 1 / (num * dist)
        if not np.all(
127
128
129
            np.absolute(np.array(domain.shape) *
                        np.array(domain.distances) *
                        np.array(codomain.distances) - 1) <
130
                10**-7):
Jait Dixit's avatar
Jait Dixit committed
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
            return False

        return True

    def transform(self, val, axes=None, **kwargs):
        """
        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

        """
        if self._transform.codomain.harmonic:
149
150
151
152
153
            # correct for forward 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.
Jait Dixit's avatar
Jait Dixit committed
154
            val = self._transform.domain.weight(val, power=1, axes=axes)
Jait Dixit's avatar
Jait Dixit committed
155
156
157
158
159

        # Perform the transformation
        Tval = self._transform.transform(val, axes, **kwargs)

        if not self._transform.codomain.harmonic:
160
161
            # correct for inverse fft.
            # See discussion above.
Jait Dixit's avatar
Jait Dixit committed
162
            Tval = self._transform.codomain.weight(Tval, power=-1, axes=axes)
Jait Dixit's avatar
Jait Dixit committed
163
164

        return Tval