rg_space.py 7.68 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
Marco Selig's avatar
Marco Selig committed
34
import numpy as np
Martin Reinecke's avatar
Martin Reinecke committed
35
from ..space import Space
csongor's avatar
csongor committed
36

Marco Selig's avatar
Marco Selig committed
37

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

        NIFTY subclass for spaces of regular Cartesian grids.

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

        Attributes
        ----------
Martin Reinecke's avatar
Martin Reinecke committed
66
        harmonic : bool
Theo Steininger's avatar
Theo Steininger committed
67
68
            Whether or not the grid represents a position or harmonic space.
        distances : tuple of floats
69
70
71
72
73
74
75
            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.
        shape : tuple of np.ints
            The shape of the space's data array.
Theo Steininger's avatar
Theo Steininger committed
76

Marco Selig's avatar
Marco Selig committed
77
78
    """

79
80
    # ---Overwritten properties and methods---

Martin Reinecke's avatar
Martin Reinecke committed
81
    def __init__(self, shape, distances=None, harmonic=False):
Martin Reinecke's avatar
Martin Reinecke committed
82
        super(RGSpace, self).__init__()
83
        self._needed_for_hash += ["_distances", "_shape", "_harmonic"]
84

Martin Reinecke's avatar
Martin Reinecke committed
85
        self._harmonic = bool(harmonic)
86
87
        self._shape = self._parse_shape(shape)
        self._distances = self._parse_distances(distances)
88
        self._dvol = float(reduce(lambda x, y: x*y, self._distances))
Martin Reinecke's avatar
Martin Reinecke committed
89
        self._dim = int(reduce(lambda x, y: x*y, self._shape))
Marco Selig's avatar
Marco Selig committed
90

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

95
96
97
98
99
100
101
102
103
104
    @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
105
        return self._dim
106

107
108
    def scalar_dvol(self):
        return self._dvol
109

110
    def get_k_length_array(self):
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
111
112
        if (not self.harmonic):
            raise NotImplementedError
Martin Reinecke's avatar
Martin Reinecke committed
113
114
115
116
117
118
119
120
121
122
123
        res = np.arange(self.shape[0], dtype=np.float64)
        res = np.minimum(res, self.shape[0]-res)*self.distances[0]
        if len(self.shape) == 1:
            return res
        res *= res
        for i in range(1, len(self.shape)):
            tmp = np.arange(self.shape[i], dtype=np.float64)
            tmp = np.minimum(tmp, self.shape[i]-tmp)*self.distances[i]
            tmp *= tmp
            res = np.add.outer(res, tmp)
        return np.sqrt(res)
theos's avatar
theos committed
124

125
    def get_unique_k_lengths(self):
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
126
127
        if (not self.harmonic):
            raise NotImplementedError
Martin Reinecke's avatar
Martin Reinecke committed
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
        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
145
            tmp = self.get_k_length_array().unique()  # expensive!
Martin Reinecke's avatar
Martin Reinecke committed
146
147
148
149
150
151
152
            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]

Martin Reinecke's avatar
Martin Reinecke committed
153
154
155
156
157
158
159
    @staticmethod
    def _kernel(x, sigma):
        tmp = x*x
        tmp *= -2.*np.pi*np.pi*sigma*sigma
        np.exp(tmp, out=tmp)
        return tmp

160
    def get_fft_smoothing_kernel_function(self, sigma):
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
161
162
        if (not self.harmonic):
            raise NotImplementedError
Martin Reinecke's avatar
Martin Reinecke committed
163
        return lambda x: self._kernel(x, sigma)
theos's avatar
theos committed
164

Martin Reinecke's avatar
Martin Reinecke committed
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
    def get_default_codomain(self):
        distances = 1. / (np.array(self.shape)*np.array(self.distances))
        return RGSpace(self.shape, distances, not self.harmonic)

    def check_codomain(self, codomain):
        if not isinstance(codomain, RGSpace):
            raise TypeError("domain is not a RGSpace")

        if self.shape != codomain.shape:
            raise AttributeError("The shapes of domain and codomain must be "
                                 "identical.")

        if self.harmonic == codomain.harmonic:
            raise AttributeError("domain.harmonic and codomain.harmonic must "
                                 "not be the same.")

        # Check if the distances match, i.e. dist' = 1 / (num * dist)
        if not np.all(
            np.absolute(np.array(self.shape) *
                        np.array(self.distances) *
                        np.array(codomain.distances) - 1) < 1e-7):
            raise AttributeError("The grid-distances of domain and codomain "
                                 "do not match.")

189
190
191
192
    # ---Added properties and methods---

    @property
    def distances(self):
Theo Steininger's avatar
Theo Steininger committed
193
194
195
        """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.
196
        """
Theo Steininger's avatar
Theo Steininger committed
197

198
199
200
201
202
203
204
205
206
207
208
209
        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
210
                temp = np.ones_like(self.shape, dtype=np.float64)
211
            else:
Martin Reinecke's avatar
Martin Reinecke committed
212
                temp = 1 / np.array(self.shape, dtype=np.float64)
213
        else:
Martin Reinecke's avatar
Martin Reinecke committed
214
            temp = np.empty(len(self.shape), dtype=np.float64)
215
216
            temp[:] = distances
        return tuple(temp)