rg_space.py 10.8 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

from __future__ import division
Martin Reinecke's avatar
Martin Reinecke committed
20
from builtins import range
Martin Reinecke's avatar
Martin Reinecke committed
21
from functools import reduce
Ultimanet's avatar
Ultimanet committed
22

Marco Selig's avatar
Marco Selig committed
23
import numpy as np
Ultimanet's avatar
Ultimanet committed
24

25
26
from d2o import distributed_data_object,\
                STRATEGIES as DISTRIBUTION_STRATEGIES
27

Martin Reinecke's avatar
Martin Reinecke committed
28
from ..space import Space
Martin Reinecke's avatar
Martin Reinecke committed
29
from ...config import nifty_configuration
csongor's avatar
csongor committed
30

Marco Selig's avatar
Marco Selig committed
31

Theo Steininger's avatar
Theo Steininger committed
32
class RGSpace(Space):
Marco Selig's avatar
Marco Selig committed
33
34
35
36
37
38
39
40
41
    """
        ..      _____   _______
        ..    /   __/ /   _   /
        ..   /  /    /  /_/  /
        ..  /__/     \____  /  space class
        ..          /______/

        NIFTY subclass for spaces of regular Cartesian grids.

Theo Steininger's avatar
Theo Steininger committed
42
43
44
45
46
47
48
49
50
51
52
53
54
55
        Parameters
        ----------
        shape : {int, numpy.ndarray}
            Number of grid points or numbers of gridpoints along each axis.
        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
56
            (default: False).
Marco Selig's avatar
Marco Selig committed
57
58
59

        Attributes
        ----------
Martin Reinecke's avatar
Martin Reinecke committed
60
        harmonic : bool
Theo Steininger's avatar
Theo Steininger committed
61
62
            Whether or not the grid represents a position or harmonic space.
        distances : tuple of floats
63
64
65
66
67
68
69
70
71
            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
72

Marco Selig's avatar
Marco Selig committed
73
74
    """

75
76
    # ---Overwritten properties and methods---

Martin Reinecke's avatar
Martin Reinecke committed
77
    def __init__(self, shape, distances=None, harmonic=False):
78
79
        self._harmonic = bool(harmonic)

Martin Reinecke's avatar
Martin Reinecke committed
80
        super(RGSpace, self).__init__()
81

82
83
        self._shape = self._parse_shape(shape)
        self._distances = self._parse_distances(distances)
Marco Selig's avatar
Marco Selig committed
84

85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# This code is unused but may be useful to keep around if it is ever needed
# again in the future ...

#    def hermitian_fixed_points(self):
#        dimensions = len(self.shape)
#        mid_index = np.array(self.shape)//2
#        ndlist = [1]*dimensions
#        for k in range(dimensions):
#            if self.shape[k] % 2 == 0:
#                ndlist[k] = 2
#        ndlist = tuple(ndlist)
#        fixed_points = []
#        for index in np.ndindex(ndlist):
#            for k in range(dimensions):
#                if self.shape[k] % 2 != 0 and self.zerocenter[k]:
#                    index = list(index)
#                    index[k] = 1
#                    index = tuple(index)
#            fixed_points += [tuple(index * mid_index)]
#        return fixed_points
105

106
    def hermitianize_inverter(self, x, axes):
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
107
108
        if (not self.harmonic):
            raise NotImplementedError
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
        if nifty_configuration['harmonic_rg_base'] == 'real':
            return x
        else:
            # calculate the number of dimensions the input array has
            dimensions = len(x.shape)
            # 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
            for k in range(len(axes)):
                i = axes[k]
                slice_picker = slice_primitive[:]
                slice_inverter = slice_primitive[:]
Martin Reinecke's avatar
Martin Reinecke committed
124
125
                slice_picker[i] = slice(1, None, None)
                slice_inverter[i] = slice(None, 0, -1)
126
127
128
129
130
131
132
133
134
                slice_picker = tuple(slice_picker)
                slice_inverter = tuple(slice_inverter)

                try:
                    y.set_data(to_key=slice_picker, data=y,
                               from_key=slice_inverter)
                except(AttributeError):
                    y[slice_picker] = y[slice_inverter]
            return y
135

136
137
    # ---Mandatory properties and methods---

138
    def __repr__(self):
Martin Reinecke's avatar
Martin Reinecke committed
139
140
        return ("RGSpace(shape=%r, distances=%r, harmonic=%r)"
                % (self.shape, self.distances, self.harmonic))
141

142
143
144
145
146
147
148
149
150
151
    @property
    def harmonic(self):
        return self._harmonic

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

    @property
    def dim(self):
Martin Reinecke's avatar
Martin Reinecke committed
152
        return int(reduce(lambda x, y: x*y, self.shape))
153
154
155
156
157
158
159
160

    @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,
                              distances=self.distances,
Martin Reinecke's avatar
Martin Reinecke committed
161
                              harmonic=self.harmonic)
162
163

    def weight(self, x, power=1, axes=None, inplace=False):
164
        weight = reduce(lambda x, y: x*y, self.distances) ** np.float(power)
165
166
167
168
169
170
171
        if inplace:
            x *= weight
            result_x = x
        else:
            result_x = x*weight
        return result_x

172
    def get_distance_array(self, distribution_strategy):
Theo Steininger's avatar
Theo Steininger committed
173
174
        """ 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
175

Theo Steininger's avatar
Theo Steininger committed
176
177
        Parameters
        ----------
Theo Steininger's avatar
Theo Steininger committed
178
179
180
        distribution_strategy : str
            The distribution_strategy which shall be used the returned
            distributed_data_object.
theos's avatar
theos committed
181

Theo Steininger's avatar
Theo Steininger committed
182
183
        Returns
        -------
Theo Steininger's avatar
Theo Steininger committed
184
        distributed_data_object
Theo Steininger's avatar
Theo Steininger committed
185
186
            A d2o containing the distances.

theos's avatar
theos committed
187
        """
Theo Steininger's avatar
Theo Steininger committed
188

Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
189
190
        if (not self.harmonic):
            raise NotImplementedError
theos's avatar
theos committed
191
192
193
        shape = self.shape
        # prepare the distributed_data_object
        nkdict = distributed_data_object(
Martin Reinecke's avatar
Martin Reinecke committed
194
                        global_shape=shape, dtype=np.float64,
theos's avatar
theos committed
195
196
197
198
199
200
201
202
203
                        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:
204
205
            raise ValueError(
                "Unsupported distribution strategy")
theos's avatar
theos committed
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
        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]

221
222
        dists = (cords[0] - shape[0]//2)*dk[0]
        dists *= dists
Martin Reinecke's avatar
Martin Reinecke committed
223
        dists = np.fft.ifftshift(dists)
theos's avatar
theos committed
224
225
226
        # only save the individual slice
        dists = dists[slice_of_first_dimension]
        for ii in range(1, len(shape)):
227
228
            temp = (cords[ii] - shape[ii] // 2) * dk[ii]
            temp *= temp
Martin Reinecke's avatar
Martin Reinecke committed
229
            temp = np.fft.ifftshift(temp)
theos's avatar
theos committed
230
231
232
233
            dists = dists + temp
        dists = np.sqrt(dists)
        return dists

Martin Reinecke's avatar
Martin Reinecke committed
234
    def get_unique_distances(self):
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
235
236
        if (not self.harmonic):
            raise NotImplementedError
Martin Reinecke's avatar
Martin Reinecke committed
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
        dimensions = len(self.shape)
        if dimensions == 1:  # extra easy
            maxdist = self.shape[0]//2
            return np.arange(maxdist+1, dtype=np.float64) * self.distances[0]
        if np.all(self.distances == self.distances[0]):  # shortcut
            maxdist = np.asarray(self.shape)//2
            tmp = np.sum(maxdist*maxdist)
            tmp = np.zeros(tmp+1, dtype=np.bool)
            t2 = np.arange(maxdist[0]+1, dtype=np.int64)
            t2 *= t2
            for i in range(1, dimensions):
                t3 = np.arange(maxdist[i]+1, dtype=np.int64)
                t3 *= t3
                t2 = np.add.outer(t2, t3)
            tmp[t2] = True
            return np.sqrt(np.nonzero(tmp)[0])*self.distances[0]
        else:  # do it the hard way
            tmp = self.get_distance_array('not').unique()  # expensive!
            tol = 1e-12*tmp[-1]
            # remove all points that are closer than tol to their right
            # neighbors.
            # I'm appending the last value*2 to the array to treat the
            # rightmost point correctly.
            return tmp[np.diff(np.r_[tmp, 2*tmp[-1]]) > tol]

    def get_natural_binbounds(self):
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
263
264
        if (not self.harmonic):
            raise NotImplementedError
Martin Reinecke's avatar
Martin Reinecke committed
265
266
267
        tmp = self.get_unique_distances()
        return 0.5*(tmp[:-1]+tmp[1:])

268
    def get_fft_smoothing_kernel_function(self, sigma):
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
269
270
        if (not self.harmonic):
            raise NotImplementedError
Theo Steininger's avatar
Theo Steininger committed
271
        return lambda x: np.exp(-2. * np.pi*np.pi * x*x * sigma*sigma)
theos's avatar
theos committed
272

273
274
275
276
    # ---Added properties and methods---

    @property
    def distances(self):
Theo Steininger's avatar
Theo Steininger committed
277
278
279
        """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.
280
        """
Theo Steininger's avatar
Theo Steininger committed
281

282
283
284
285
286
287
288
289
290
291
292
293
        return self._distances

    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
294
                temp = np.ones_like(self.shape, dtype=np.float64)
295
            else:
Martin Reinecke's avatar
Martin Reinecke committed
296
                temp = 1 / np.array(self.shape, dtype=np.float64)
297
        else:
Martin Reinecke's avatar
Martin Reinecke committed
298
            temp = np.empty(len(self.shape), dtype=np.float64)
299
300
301
            temp[:] = distances
        return tuple(temp)

302
303
304
    # ---Serialization---

    def _to_hdf5(self, hdf5_group):
Jait Dixit's avatar
Jait Dixit committed
305
306
        hdf5_group['shape'] = self.shape
        hdf5_group['distances'] = self.distances
307
        hdf5_group['harmonic'] = self.harmonic
Jait Dixit's avatar
Jait Dixit committed
308

309
310
311
        return None

    @classmethod
Theo Steininger's avatar
Theo Steininger committed
312
    def _from_hdf5(cls, hdf5_group, repository):
313
        result = cls(
Jait Dixit's avatar
Jait Dixit committed
314
315
            shape=hdf5_group['shape'][:],
            distances=hdf5_group['distances'][:],
316
            harmonic=hdf5_group['harmonic'][()],
Jait Dixit's avatar
Jait Dixit committed
317
            )
318
        return result