rg_space.py 7.75 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
Martin Reinecke's avatar
Martin Reinecke committed
32
from builtins import range
Martin Reinecke's avatar
Martin Reinecke committed
33
from functools import reduce
34

Marco Selig's avatar
Marco Selig committed
35
import numpy as np
Theo Steininger's avatar
Theo Steininger committed
36

Martin Reinecke's avatar
Martin Reinecke committed
37
from ..space import Space
csongor's avatar
csongor committed
38

Marco Selig's avatar
Marco Selig committed
39

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

        NIFTY subclass for spaces of regular Cartesian grids.

Theo Steininger's avatar
Theo Steininger committed
50
51
52
53
54
55
56
57
58
59
60
61
62
63
        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
64
            (default: False).
Marco Selig's avatar
Marco Selig committed
65
66
67

        Attributes
        ----------
Martin Reinecke's avatar
Martin Reinecke committed
68
        harmonic : bool
Theo Steininger's avatar
Theo Steininger committed
69
70
            Whether or not the grid represents a position or harmonic space.
        distances : tuple of floats
71
72
73
74
75
76
77
78
79
            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
80

Marco Selig's avatar
Marco Selig committed
81
82
    """

83
84
    # ---Overwritten properties and methods---

Martin Reinecke's avatar
Martin Reinecke committed
85
    def __init__(self, shape, distances=None, harmonic=False):
86
87
        self._harmonic = bool(harmonic)

Martin Reinecke's avatar
Martin Reinecke committed
88
        super(RGSpace, self).__init__()
89

90
91
        self._shape = self._parse_shape(shape)
        self._distances = self._parse_distances(distances)
Marco Selig's avatar
Marco Selig committed
92

93
    def __repr__(self):
Martin Reinecke's avatar
Martin Reinecke committed
94
95
        return ("RGSpace(shape=%r, distances=%r, harmonic=%r)"
                % (self.shape, self.distances, self.harmonic))
96

97
98
99
100
101
102
103
104
105
106
    @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
107
        return int(reduce(lambda x, y: x*y, self.shape))
108
109
110
111
112
113
114
115

    @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
116
                              harmonic=self.harmonic)
117
118

    def weight(self, x, power=1, axes=None, inplace=False):
119
        weight = reduce(lambda x, y: x*y, self.distances) ** np.float(power)
120
121
122
123
124
125
126
        if inplace:
            x *= weight
            result_x = x
        else:
            result_x = x*weight
        return result_x

Martin Reinecke's avatar
stage1    
Martin Reinecke committed
127
    def get_distance_array(self):
Theo Steininger's avatar
Theo Steininger committed
128
129
        """ Calculates an n-dimensional array with its entries being the
        lengths of the vectors from the zero point of the grid.
130

Theo Steininger's avatar
Theo Steininger committed
131
132
        Returns
        -------
Martin Reinecke's avatar
stage1    
Martin Reinecke committed
133
134
        numpy.ndarray
            An array containing the distances.
Theo Steininger's avatar
Theo Steininger committed
135

136
        """
Theo Steininger's avatar
Theo Steininger committed
137

Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
138
139
        if (not self.harmonic):
            raise NotImplementedError
140
        shape = self.shape
Martin Reinecke's avatar
stage1    
Martin Reinecke committed
141
142

        slice_of_first_dimension = slice(0, shape[0])
143
144
        dists = self._distance_array_helper(slice_of_first_dimension)

Martin Reinecke's avatar
stage1    
Martin Reinecke committed
145
        return dists
146
147
148
149
150
151
152
153
154
155
156

    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]

157
158
        dists = (cords[0] - shape[0]//2)*dk[0]
        dists *= dists
Martin Reinecke's avatar
Martin Reinecke committed
159
        dists = np.fft.ifftshift(dists)
160
161
162
        # only save the individual slice
        dists = dists[slice_of_first_dimension]
        for ii in range(1, len(shape)):
163
164
            temp = (cords[ii] - shape[ii] // 2) * dk[ii]
            temp *= temp
Martin Reinecke's avatar
Martin Reinecke committed
165
            temp = np.fft.ifftshift(temp)
166
167
168
169
            dists = dists + temp
        dists = np.sqrt(dists)
        return dists

Martin Reinecke's avatar
Martin Reinecke committed
170
    def get_unique_distances(self):
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
171
172
        if (not self.harmonic):
            raise NotImplementedError
Martin Reinecke's avatar
Martin Reinecke committed
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
        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
199
200
        if (not self.harmonic):
            raise NotImplementedError
Martin Reinecke's avatar
Martin Reinecke committed
201
202
203
        tmp = self.get_unique_distances()
        return 0.5*(tmp[:-1]+tmp[1:])

204
    def get_fft_smoothing_kernel_function(self, sigma):
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
205
206
        if (not self.harmonic):
            raise NotImplementedError
Theo Steininger's avatar
Theo Steininger committed
207
        return lambda x: np.exp(-2. * np.pi*np.pi * x*x * sigma*sigma)
208

209
210
211
212
    # ---Added properties and methods---

    @property
    def distances(self):
Theo Steininger's avatar
Theo Steininger committed
213
214
215
        """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.
216
        """
Theo Steininger's avatar
Theo Steininger committed
217

218
219
220
221
222
223
224
225
226
227
228
229
        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
230
                temp = np.ones_like(self.shape, dtype=np.float64)
231
            else:
Martin Reinecke's avatar
Martin Reinecke committed
232
                temp = 1 / np.array(self.shape, dtype=np.float64)
233
        else:
Martin Reinecke's avatar
Martin Reinecke committed
234
            temp = np.empty(len(self.shape), dtype=np.float64)
235
236
            temp[:] = distances
        return tuple(temp)