rgrgtransformation.py 5.26 KB
Newer Older
Jait Dixit's avatar
Jait Dixit committed
1
2
3
4
5
6
7
8
import numpy as np
from transformation import Transformation
from rg_transforms import FFTW, GFFT
from nifty.config import about, dependency_injector as gdi
from nifty import RGSpace, nifty_configuration


class RGRGTransformation(Transformation):
Jait Dixit's avatar
Jait Dixit committed
9
    def __init__(self, domain, codomain=None, module=None):
10
        super(RGRGTransformation, self).__init__(domain, codomain, module)
Jait Dixit's avatar
Jait Dixit committed
11
12
13
14

        if module is None:
            if nifty_configuration['fft_module'] == 'pyfftw':
                self._transform = FFTW(domain, codomain)
15
16
            elif (nifty_configuration['fft_module'] == 'gfft' or
                  nifty_configuration['fft_module'] == 'gfft_dummy'):
Jait Dixit's avatar
Jait Dixit committed
17
18
19
20
                self._transform = \
                    GFFT(domain,
                         codomain,
                         gdi.get(nifty_configuration['fft_module']))
Jait Dixit's avatar
Jait Dixit committed
21
            else:
Jait Dixit's avatar
Jait Dixit committed
22
23
                raise ValueError('ERROR: unknow default FFT module:' +
                                 nifty_configuration['fft_module'])
Jait Dixit's avatar
Jait Dixit committed
24
        else:
Jait Dixit's avatar
Jait Dixit committed
25
26
27
28
29
30
31
32
33
34
            if module == 'pyfftw':
                self._transform = FFTW(domain, codomain)
            elif module == 'gfft':
                self._transform = \
                    GFFT(domain, codomain, gdi.get('gfft'))
            elif module == 'gfft_dummy':
                self._transform = \
                    GFFT(domain, codomain, gdi.get('gfft_dummy'))
            else:
                raise ValueError('ERROR: unknow FFT module:' + module)
Jait Dixit's avatar
Jait Dixit committed
35

Jait Dixit's avatar
Jait Dixit committed
36
    @staticmethod
theos's avatar
theos committed
37
    def get_codomain(domain, dtype=None, zerocenter=None, **kwargs):
Jait Dixit's avatar
Jait Dixit committed
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
        """
            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
theos's avatar
theos committed
60
        if zerocenter is None:
61
            zerocenter = domain.zerocenter
Jait Dixit's avatar
Jait Dixit committed
62
63
        # if the input is something scalar, cast it to a boolean
        else:
64
            temp = np.empty_like(domain.zerocenter)
theos's avatar
theos committed
65
            temp[:] = zerocenter
66
            zerocenter = temp
Jait Dixit's avatar
Jait Dixit committed
67
68

        # calculate the initialization parameters
69
70
        distances = 1 / (np.array(domain.shape) *
                         np.array(domain.distances))
theos's avatar
theos committed
71
        if dtype is None:
72
73
74
            # 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
75

76
        new_space = RGSpace(domain.shape,
theos's avatar
theos committed
77
78
79
80
                            zerocenter=zerocenter,
                            distances=distances,
                            harmonic=(not domain.harmonic),
                            dtype=dtype)
Jait Dixit's avatar
Jait Dixit committed
81
82
83

        return new_space

Jait Dixit's avatar
Jait Dixit committed
84
85
86
    @staticmethod
    def check_codomain(domain, codomain):
        if not isinstance(domain, RGSpace):
87
            raise TypeError('ERROR: domain is not a RGSpace')
Jait Dixit's avatar
Jait Dixit committed
88
89
90
91
92

        if codomain is None:
            return False

        if not isinstance(codomain, RGSpace):
theos's avatar
theos committed
93
            return False
Jait Dixit's avatar
Jait Dixit committed
94

95
96
        if not np.all(np.array(domain.shape) ==
                      np.array(codomain.shape)):
Jait Dixit's avatar
Jait Dixit committed
97
98
99
100
101
            return False

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

102
103
104
105
106
        if codomain.harmonic and not issubclass(codomain.dtype.type,
                                                np.complexfloating):
            about.warnings.cprint(
                "WARNING: codomain is harmonic but dtype is real.")

Jait Dixit's avatar
Jait Dixit committed
107
108
        # Check if the distances match, i.e. dist' = 1 / (num * dist)
        if not np.all(
109
110
111
            np.absolute(np.array(domain.shape) *
                        np.array(domain.distances) *
                        np.array(codomain.distances) - 1) <
theos's avatar
theos committed
112
                10**-7):
Jait Dixit's avatar
Jait Dixit committed
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
            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:
131
132
133
134
135
            # 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
136
            val = self._transform.domain.weight(val, power=1, axes=axes)
Jait Dixit's avatar
Jait Dixit committed
137
138
139
140
141

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

        if not self._transform.codomain.harmonic:
142
143
            # correct for inverse fft.
            # See discussion above.
Jait Dixit's avatar
Jait Dixit committed
144
            Tval = self._transform.codomain.weight(Tval, power=-1, axes=axes)
Jait Dixit's avatar
Jait Dixit committed
145
146

        return Tval