rg_space.py 12.6 KB
Newer Older
1
2
3
4
# 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.
5
#
6
7
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
8
9
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
11
# You should have received a copy of the GNU General Public License
12
# 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.
Marco Selig's avatar
Marco Selig committed
18
19
20
21
22
23
24
25
26
27

"""
    ..                  __   ____   __
    ..                /__/ /   _/ /  /_
    ..      __ ___    __  /  /_  /   _/  __   __
    ..    /   _   | /  / /   _/ /  /   /  / /  /
    ..   /  / /  / /  / /  /   /  /_  /  /_/  /
    ..  /__/ /__/ /__/ /__/    \___/  \___   /  rg
    ..                               /______/

Marco Selig's avatar
Marco Selig committed
28
    NIFTY submodule for regular Cartesian grids.
Marco Selig's avatar
Marco Selig committed
29
30
31

"""
from __future__ import division
Ultimanet's avatar
Ultimanet committed
32

Marco Selig's avatar
Marco Selig committed
33
import numpy as np
Ultimanet's avatar
Ultimanet committed
34

35
36
from d2o import distributed_data_object,\
                STRATEGIES as DISTRIBUTION_STRATEGIES
37

38
from nifty.spaces.space import Space
csongor's avatar
csongor committed
39

Marco Selig's avatar
Marco Selig committed
40

Theo Steininger's avatar
Theo Steininger committed
41
class RGSpace(Space):
Marco Selig's avatar
Marco Selig committed
42
43
44
45
46
47
48
49
50
    """
        ..      _____   _______
        ..    /   __/ /   _   /
        ..   /  /    /  /_/  /
        ..  /__/     \____  /  space class
        ..          /______/

        NIFTY subclass for spaces of regular Cartesian grids.

Theo Steininger's avatar
Theo Steininger committed
51
52
53
54
        Parameters
        ----------
        shape : {int, numpy.ndarray}
            Number of grid points or numbers of gridpoints along each axis.
55
56
57
58
        zerocenter : {bool, numpy.ndarray} *optional*
            Whether x==0 (or k==0, respectively) is located in the center of
            the grid (or the center of each axis speparately) or not.
            (default: False).
Theo Steininger's avatar
Theo Steininger committed
59
60
61
62
63
64
65
66
67
68
        distances : {float, numpy.ndarray}, *optional*
            Distance between two grid points along each axis
            (default: None).
            If distances==None:
                if harmonic==True, all distances will be set to 1
                if harmonic==False, the distance along each axis will be
                  set to the inverse of the number of points along that
                  axis.
        harmonic : bool, *optional*
        Whether the space represents a grid in position or harmonic space.
Theo Steininger's avatar
Theo Steininger committed
69
            (default: False).
Marco Selig's avatar
Marco Selig committed
70
71
72

        Attributes
        ----------
Martin Reinecke's avatar
Martin Reinecke committed
73
        harmonic : bool
Theo Steininger's avatar
Theo Steininger committed
74
75
76
77
78
            Whether or not the grid represents a position or harmonic space.
        zerocenter : tuple of bool
            Whether x==0 (or k==0, respectively) is located in the center of
            the grid (or the center of each axis speparately) or not.
        distances : tuple of floats
79
80
81
82
83
84
85
86
87
            Distance between two grid points along the correponding axis.
        dim : np.int
            Total number of dimensionality, i.e. the number of pixels.
        harmonic : bool
            Specifies whether the space is a signal or harmonic space.
        total_volume : np.float
            The total volume of the space.
        shape : tuple of np.ints
            The shape of the space's data array.
Theo Steininger's avatar
Theo Steininger committed
88

Marco Selig's avatar
Marco Selig committed
89
90
    """

91
92
    # ---Overwritten properties and methods---

93
    def __init__(self, shape, zerocenter=False, distances=None,
Martin Reinecke's avatar
Martin Reinecke committed
94
                 harmonic=False):
95
96
        self._harmonic = bool(harmonic)

Martin Reinecke's avatar
Martin Reinecke committed
97
        super(RGSpace, self).__init__()
98

99
100
101
        self._shape = self._parse_shape(shape)
        self._distances = self._parse_distances(distances)
        self._zerocenter = self._parse_zerocenter(zerocenter)
Marco Selig's avatar
Marco Selig committed
102

103
104
    def hermitian_decomposition(self, x, axes=None,
                                preserve_gaussian_variance=False):
Martin Reinecke's avatar
Martin Reinecke committed
105
106
        # check axes
        if axes is None:
Martin Reinecke's avatar
fix    
Martin Reinecke committed
107
            axes = range(len(self.shape))
Martin Reinecke's avatar
Martin Reinecke committed
108
109
110
        assert len(x.shape) >= len(self.shape), "shapes mismatch"
        assert len(axes) == len(self.shape), "axes mismatch"

111
112
113
114
115
116
117
118
        # compute the hermitian part
        flipped_x = self._hermitianize_inverter(x, axes=axes)
        flipped_x = flipped_x.conjugate()
        # average x and flipped_x.
        hermitian_part = x + flipped_x
        hermitian_part /= 2.

        # use subtraction since it is faster than flipping another time
119
        anti_hermitian_part = (x-hermitian_part)
120
121
122
123
124
125
126

        if preserve_gaussian_variance:
            hermitian_part, anti_hermitian_part = \
                self._hermitianize_correct_variance(hermitian_part,
                                                    anti_hermitian_part,
                                                    axes=axes)

127
128
        return (hermitian_part, anti_hermitian_part)

129
130
131
132
133
134
    def _hermitianize_correct_variance(self, hermitian_part,
                                       anti_hermitian_part, axes):
        # Correct the variance by multiplying sqrt(2)
        hermitian_part = hermitian_part * np.sqrt(2)
        anti_hermitian_part = anti_hermitian_part * np.sqrt(2)

135
136
137
138
139
140
141
142
143
144
145
146
        # If the dtype of the input is complex, the fixed points lose the power
        # of their imaginary-part (or real-part, respectively). Therefore
        # the factor of sqrt(2) also applies there
        if not issubclass(hermitian_part.dtype.type, np.complexfloating):
            # The fixed points of the point inversion must not be averaged.
            # Hence one must divide out the sqrt(2) again
            # -> Get the middle index of the array
            mid_index = np.array(hermitian_part.shape, dtype=np.int) // 2
            dimensions = mid_index.size
            # Use ndindex to iterate over all combinations of zeros and the
            # mid_index in order to correct all fixed points.

Martin Reinecke's avatar
Martin Reinecke committed
147
148
149
150
151
            ndlist=[1]*dimensions
            for k in range(len(axes)):
                i = axes[k]
                if self.shape[k]%2 == 0:
                    ndlist[i] = 2
152
153
154
155
156
            ndlist = tuple(ndlist)
            for i in np.ndindex(ndlist):
                temp_index = tuple(i * mid_index)
                hermitian_part[temp_index] /= np.sqrt(2)
                anti_hermitian_part[temp_index] /= np.sqrt(2)
157
158
        return hermitian_part, anti_hermitian_part

159
160
    def _hermitianize_inverter(self, x, axes):
        # calculate the number of dimensions the input array has
Martin Reinecke's avatar
Martin Reinecke committed
161
        dimensions = len(x.shape)
162
163
164
165
166
167
        # prepare the slicing object which will be used for mirroring
        slice_primitive = [slice(None), ] * dimensions
        # copy the input data
        y = x.copy()

        # flip in the desired directions
Martin Reinecke's avatar
Martin Reinecke committed
168
169
        for k in range(len(axes)):
            i = axes[k]
170
171
            slice_picker = slice_primitive[:]
            slice_inverter = slice_primitive[:]
Martin Reinecke's avatar
Martin Reinecke committed
172
            if (not self.zerocenter[k]) or self.shape[k] % 2 == 0:
Martin Reinecke's avatar
Martin Reinecke committed
173
                slice_picker[i] = slice(1, None, None)
174
175
                slice_inverter[i] = slice(None, 0, -1)
            else:
Martin Reinecke's avatar
Martin Reinecke committed
176
                slice_picker[i] = slice(None)
177
                slice_inverter[i] = slice(None, None, -1)
Martin Reinecke's avatar
Martin Reinecke committed
178
            slice_picker = tuple(slice_picker)
179
180
181
            slice_inverter = tuple(slice_inverter)

            try:
Martin Reinecke's avatar
Martin Reinecke committed
182
183
                y.set_data(to_key=slice_picker, data=y,
                           from_key=slice_inverter)
184
185
186
187
            except(AttributeError):
                y[slice_picker] = y[slice_inverter]
        return y

188
189
    # ---Mandatory properties and methods---

190
191
192
193
    def __repr__(self):
        return ("RGSpace(shape=%r, zerocenter=%r, distances=%r, harmonic=%r)"
                % (self.shape, self.zerocenter, self.distances, self.harmonic))

194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
    @property
    def harmonic(self):
        return self._harmonic

    @property
    def shape(self):
        return self._shape

    @property
    def dim(self):
        return reduce(lambda x, y: x*y, self.shape)

    @property
    def total_volume(self):
        return self.dim * reduce(lambda x, y: x*y, self.distances)

    def copy(self):
        return self.__class__(shape=self.shape,
                              zerocenter=self.zerocenter,
                              distances=self.distances,
Martin Reinecke's avatar
Martin Reinecke committed
214
                              harmonic=self.harmonic)
215
216

    def weight(self, x, power=1, axes=None, inplace=False):
217
        weight = reduce(lambda x, y: x*y, self.distances) ** np.float(power)
218
219
220
221
222
223
224
        if inplace:
            x *= weight
            result_x = x
        else:
            result_x = x*weight
        return result_x

225
    def get_distance_array(self, distribution_strategy):
Theo Steininger's avatar
Theo Steininger committed
226
227
        """ Calculates an n-dimensional array with its entries being the
        lengths of the vectors from the zero point of the grid.
theos's avatar
theos committed
228

Theo Steininger's avatar
Theo Steininger committed
229
230
        Parameters
        ----------
Theo Steininger's avatar
Theo Steininger committed
231
232
233
        distribution_strategy : str
            The distribution_strategy which shall be used the returned
            distributed_data_object.
theos's avatar
theos committed
234

Theo Steininger's avatar
Theo Steininger committed
235
236
        Returns
        -------
Theo Steininger's avatar
Theo Steininger committed
237
        distributed_data_object
Theo Steininger's avatar
Theo Steininger committed
238
239
            A d2o containing the distances.

theos's avatar
theos committed
240
        """
Theo Steininger's avatar
Theo Steininger committed
241

theos's avatar
theos committed
242
243
244
        shape = self.shape
        # prepare the distributed_data_object
        nkdict = distributed_data_object(
Martin Reinecke's avatar
Martin Reinecke committed
245
                        global_shape=shape, dtype=np.float64,
theos's avatar
theos committed
246
247
248
249
250
251
252
253
254
                        distribution_strategy=distribution_strategy)

        if distribution_strategy in DISTRIBUTION_STRATEGIES['slicing']:
            # get the node's individual slice of the first dimension
            slice_of_first_dimension = slice(
                                    *nkdict.distributor.local_slice[0:2])
        elif distribution_strategy in DISTRIBUTION_STRATEGIES['not']:
            slice_of_first_dimension = slice(0, shape[0])
        else:
255
256
            raise ValueError(
                "Unsupported distribution strategy")
theos's avatar
theos committed
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
        dists = self._distance_array_helper(slice_of_first_dimension)
        nkdict.set_local_data(dists)

        return nkdict

    def _distance_array_helper(self, slice_of_first_dimension):
        dk = self.distances
        shape = self.shape

        inds = []
        for a in shape:
            inds += [slice(0, a)]

        cords = np.ogrid[inds]

272
273
        dists = (cords[0] - shape[0]//2)*dk[0]
        dists *= dists
theos's avatar
theos committed
274
        # apply zerocenterQ shift
275
276
        if not self.zerocenter[0]:
            dists = np.fft.ifftshift(dists)
theos's avatar
theos committed
277
278
279
        # only save the individual slice
        dists = dists[slice_of_first_dimension]
        for ii in range(1, len(shape)):
280
281
            temp = (cords[ii] - shape[ii] // 2) * dk[ii]
            temp *= temp
282
            if not self.zerocenter[ii]:
Martin Reinecke's avatar
Martin Reinecke committed
283
                temp = np.fft.ifftshift(temp)
theos's avatar
theos committed
284
285
286
287
            dists = dists + temp
        dists = np.sqrt(dists)
        return dists

288
    def get_fft_smoothing_kernel_function(self, sigma):
Theo Steininger's avatar
Theo Steininger committed
289
        return lambda x: np.exp(-2. * np.pi*np.pi * x*x * sigma*sigma)
theos's avatar
theos committed
290

291
292
293
294
    # ---Added properties and methods---

    @property
    def distances(self):
Theo Steininger's avatar
Theo Steininger committed
295
296
297
        """Distance between two grid points along each axis. It is a tuple
        of positive floating point numbers with the n-th entry giving the
        distances of grid points along the n-th dimension.
298
        """
Theo Steininger's avatar
Theo Steininger committed
299

300
301
302
303
        return self._distances

    @property
    def zerocenter(self):
304
        """Returns True if grid points lie symmetrically around zero.
Theo Steininger's avatar
Theo Steininger committed
305

306
307
        Returns
        -------
Theo Steininger's avatar
Theo Steininger committed
308
309
310
311
312
        bool
            True if the grid points are centered around the 0 grid point. This
            option is most common for harmonic spaces (where both conventions
            are used) but may be used for position spaces, too.

313
        """
Theo Steininger's avatar
Theo Steininger committed
314

315
316
317
318
319
320
321
322
323
324
325
326
        return self._zerocenter

    def _parse_shape(self, shape):
        if np.isscalar(shape):
            shape = (shape,)
        temp = np.empty(len(shape), dtype=np.int)
        temp[:] = shape
        return tuple(temp)

    def _parse_distances(self, distances):
        if distances is None:
            if self.harmonic:
Martin Reinecke's avatar
Martin Reinecke committed
327
                temp = np.ones_like(self.shape, dtype=np.float64)
328
            else:
Martin Reinecke's avatar
Martin Reinecke committed
329
                temp = 1 / np.array(self.shape, dtype=np.float64)
330
        else:
Martin Reinecke's avatar
Martin Reinecke committed
331
            temp = np.empty(len(self.shape), dtype=np.float64)
332
333
334
335
336
337
338
            temp[:] = distances
        return tuple(temp)

    def _parse_zerocenter(self, zerocenter):
        temp = np.empty(len(self.shape), dtype=bool)
        temp[:] = zerocenter
        return tuple(temp)
339
340
341
342

    # ---Serialization---

    def _to_hdf5(self, hdf5_group):
Jait Dixit's avatar
Jait Dixit committed
343
344
345
        hdf5_group['shape'] = self.shape
        hdf5_group['zerocenter'] = self.zerocenter
        hdf5_group['distances'] = self.distances
346
        hdf5_group['harmonic'] = self.harmonic
Jait Dixit's avatar
Jait Dixit committed
347

348
349
350
        return None

    @classmethod
Theo Steininger's avatar
Theo Steininger committed
351
    def _from_hdf5(cls, hdf5_group, repository):
352
        result = cls(
Jait Dixit's avatar
Jait Dixit committed
353
354
355
            shape=hdf5_group['shape'][:],
            zerocenter=hdf5_group['zerocenter'][:],
            distances=hdf5_group['distances'][:],
356
            harmonic=hdf5_group['harmonic'][()],
Jait Dixit's avatar
Jait Dixit committed
357
            )
358
        return result