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

Martin Reinecke's avatar
Martin Reinecke committed
19
#from builtins import str
Martin Reinecke's avatar
Martin Reinecke committed
20
import ast
theos's avatar
theos committed
21
22
import numpy as np

23
24
from d2o import distributed_data_object,\
    STRATEGIES as DISTRIBUTION_STRATEGIES
25

Martin Reinecke's avatar
Martin Reinecke committed
26
from ...spaces.space import Space
Martin Reinecke's avatar
Martin Reinecke committed
27
from functools import reduce
Martin Reinecke's avatar
Martin Reinecke committed
28
from ...config import nifty_configuration as gc
theos's avatar
theos committed
29
30


Theo Steininger's avatar
Theo Steininger committed
31
class PowerSpace(Space):
Theo Steininger's avatar
Theo Steininger committed
32
33
34
35
36
37
38
39
40
41
    """ NIFTY class for spaces of power spectra.

    Parameters
    ----------
    harmonic_partner : Space
        The harmonic Space of which this is the power space.
    distribution_strategy : str *optional*
        The distribution strategy used for the distributed_data_objects
        derived from this PowerSpace, e.g. the pindex.
        (default : 'not')
Martin Reinecke's avatar
Martin Reinecke committed
42
43
44
45
46
47
48
49
50
51
52
53
    binbounds: None, or tuple/array/list of float
        if None:
            There will be as many bins as there are distinct k-vector lengths
            in the harmonic partner space.
            The "binbounds" property of the PowerSpace will also be None.

        else:
            the bin bounds requested for this PowerSpace. The array
            must be sorted and strictly ascending. The first entry is the right
            boundary of the first bin, and the last entry is the left boundary
            of the last bin, i.e. thee will be len(binbounds)+1 bins in total,
            with the first and last bins reaching to -+infinity, respectively.
Theo Steininger's avatar
Theo Steininger committed
54
55
56
57
58
        (default : None)

    Attributes
    ----------
    pindex : distributed_data_object
59
60
        This holds the information which pixel of the harmonic partner gets
        mapped to which power bin
Theo Steininger's avatar
Theo Steininger committed
61
    kindex : numpy.ndarray
62
        Sorted array of all k-modes.
Theo Steininger's avatar
Theo Steininger committed
63
64
65
    rho : numpy.ndarray
        The amount of k-modes that get mapped to one power bin is given by
        rho.
66
67
68
    dim : np.int
        Total number of dimensionality, i.e. the number of pixels.
    harmonic : bool
Martin Reinecke's avatar
Martin Reinecke committed
69
        Always True for this space.
70
71
72
73
    total_volume : np.float
        The total volume of the space.
    shape : tuple of np.ints
        The shape of the space's data array.
Martin Reinecke's avatar
Martin Reinecke committed
74
75
76
    binbounds : tuple or None
        Boundaries between the power spectrum bins; None is used to indicate
        natural binning
Theo Steininger's avatar
Theo Steininger committed
77
78
79
80
81
82
83

    Notes
    -----
    A power space is the result of a projection of a harmonic space where
    k-modes of equal length get mapped to one power index.

    """
84

85
86
    _powerIndexCache = {}

87
88
    # ---Overwritten properties and methods---

Martin Reinecke's avatar
Martin Reinecke committed
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
    @staticmethod
    def linear_binbounds (nbin, first_bound, last_bound):
        """
        nbin: integer
            the number of bins
        first_bound, last_bound: float
            the k values for the right boundary of the first bin and the left
            boundary of the last bin, respectively. They are given in length
            units of the harmonic partner space.
        This will produce a binbounds array with nbin-1 entries with
        binbounds[0]=first_bound and binbounds[-1]=last_bound and the remaining
        values equidistantly spaced (in linear scale) between these two.
        """
        nbin = int(nbin)
        assert nbin>=3, "nbin must be at least 3"
        first_bound = float(first_bound)
        last_bound = float(last_bound)
        binbounds = np.arange(nbin-1,dtype=np.float64)/(nbin-2)
        binbounds*=last_bound-first_bound
        binbounds+=first_bound
        return binbounds

    @staticmethod
    def logarithmic_binbounds (nbin, first_bound, last_bound):
        """
        nbin: integer
            the number of bins
        first_bound, last_bound: float
            the k values for the right boundary of the first bin and the left
            boundary of the last bin, respectively. They are given in length
            units of the harmonic partner space.
        This will produce a binbounds array with nbin-1 entries with
        binbounds[0]=first_bound and binbounds[-1]=last_bound and the remaining
        values equidistantly spaced (in natural logarithmic scale)
        between these two.
        """
        return np.exp(linear_binbounds(np.log(first_bound),np.log(last_bound)))

127
    def __init__(self, harmonic_partner, distribution_strategy=None,
Martin Reinecke's avatar
Martin Reinecke committed
128
                 binbounds=None):
Martin Reinecke's avatar
Martin Reinecke committed
129
        super(PowerSpace, self).__init__()
Martin Reinecke's avatar
Martin Reinecke committed
130
        self._ignore_for_hash += ['_pindex', '_kindex', '_rho']
131

132
133
134
135
136
137
138
        if distribution_strategy is None:
            distribution_strategy = gc['default_distribution_strategy']
        elif distribution_strategy not in DISTRIBUTION_STRATEGIES['global']:
            raise ValueError(
                    "distribution_strategy must be a global-type "
                    "strategy.")

Martin Reinecke's avatar
Martin Reinecke committed
139
140
141
        if not (isinstance(harmonic_partner, Space) and
                harmonic_partner.harmonic):
            raise ValueError("harmonic_partner must be a harmonic space.")
142
        self._harmonic_partner = harmonic_partner
143

Martin Reinecke's avatar
Martin Reinecke committed
144
145
        if binbounds is not None:
            binbounds = tuple(binbounds)
146

Martin Reinecke's avatar
Martin Reinecke committed
147
        key = (harmonic_partner, distribution_strategy, binbounds)
148
149
150
151
        if self._powerIndexCache.get(key) is None:
            distance_array = \
                self.harmonic_partner.get_distance_array(distribution_strategy)
            temp_pindex = self._compute_pindex(
152
                                harmonic_partner=self.harmonic_partner,
153
                                distance_array=distance_array,
Martin Reinecke's avatar
Martin Reinecke committed
154
                                binbounds=binbounds,
155
156
                                distribution_strategy=distribution_strategy)
            temp_rho = temp_pindex.bincount().get_full_data()
Martin Reinecke's avatar
Martin Reinecke committed
157
            assert not np.any(temp_rho==0), "empty bins detected"
158
159
160
            temp_kindex = \
                (temp_pindex.bincount(weights=distance_array).get_full_data() /
                 temp_rho)
Martin Reinecke's avatar
Martin Reinecke committed
161
            self._powerIndexCache[key] = (binbounds,
162
163
164
165
166
167
168
                                          temp_pindex,
                                          temp_kindex,
                                          temp_rho)

        (self._binbounds, self._pindex, self._kindex, self._rho) = \
            self._powerIndexCache[key]

169
170
    @staticmethod
    def _compute_pindex(harmonic_partner, distance_array, binbounds,
171
                        distribution_strategy):
172

Martin Reinecke's avatar
Martin Reinecke committed
173
        # Compute pindex, kindex and rho according to bb
174
175
176
177
178
        pindex = distributed_data_object(
                                global_shape=distance_array.shape,
                                dtype=np.int,
                                distribution_strategy=distribution_strategy)
        if binbounds is None:
179
            binbounds = harmonic_partner.get_natural_binbounds()
180
181
182
        pindex.set_local_data(
                np.searchsorted(binbounds, distance_array.get_local_data()))
        return pindex
183

Theo Steininger's avatar
Theo Steininger committed
184
    def pre_cast(self, x, axes):
Theo Steininger's avatar
Theo Steininger committed
185
186
187
188
189
190
        """ Casts power spectrum functions to discretized power spectra.

        This function takes an array or a function. If it is an array it does
        nothing, otherwise it interpretes the function as power spectrum and
        evaluates it at every k-mode.

191
192
193
        Parameters
        ----------
        x : {array-like, function array-like -> array-like}
Theo Steininger's avatar
Theo Steininger committed
194
195
196
197
198
199
            power spectrum given either in discretized form or implicitly as a
            function
        axes : tuple of ints
            Specifies the axes of x which correspond to this space. For
            explicifying the power spectrum function, this is ignored.

200
201
        Returns
        -------
Theo Steininger's avatar
Theo Steininger committed
202
203
204
        array-like
            discretized power spectrum

205
        """
Theo Steininger's avatar
Theo Steininger committed
206

Martin Reinecke's avatar
Martin Reinecke committed
207
        return x(self.kindex) if callable(x) else x
208

209
210
    # ---Mandatory properties and methods---

211
212
    def __repr__(self):
        return ("PowerSpace(harmonic_partner=%r, distribution_strategy=%r, "
Martin Reinecke's avatar
Martin Reinecke committed
213
                "binbounds=%r)"
214
                % (self.harmonic_partner, self.pindex.distribution_strategy,
Martin Reinecke's avatar
Martin Reinecke committed
215
                   self._binbounds))
216

217
218
219
    @property
    def harmonic(self):
        return True
220

221
222
    @property
    def shape(self):
223
        return self.kindex.shape
224

225
226
227
228
229
230
231
    @property
    def dim(self):
        return self.shape[0]

    @property
    def total_volume(self):
        # every power-pixel has a volume of 1
Jait Dixit's avatar
Jait Dixit committed
232
        return float(reduce(lambda x, y: x*y, self.pindex.shape))
233
234

    def copy(self):
235
        distribution_strategy = self.pindex.distribution_strategy
236
        return self.__class__(harmonic_partner=self.harmonic_partner,
237
                              distribution_strategy=distribution_strategy,
Martin Reinecke's avatar
Martin Reinecke committed
238
                              binbounds=self._binbounds)
239

Martin Reinecke's avatar
Martin Reinecke committed
240
    def weight(self, x, power, axes, inplace=False):
Jait Dixit's avatar
Jait Dixit committed
241
242
        reshaper = [1, ] * len(x.shape)
        # we know len(axes) is always 1
243
244
        reshaper[axes[0]] = self.shape[0]

245
        weight = self.rho.reshape(reshaper)
246
        if power != 1:
247
            weight = weight ** np.float(power)
248
249
250
251
252
253

        if inplace:
            x *= weight
            result_x = x
        else:
            result_x = x*weight
254
255
256

        return result_x

257
    def get_distance_array(self, distribution_strategy):
Martin Reinecke's avatar
Martin Reinecke committed
258
        return distributed_data_object(
Martin Reinecke's avatar
Martin Reinecke committed
259
                                self.kindex, dtype=np.float64,
260
                                distribution_strategy=distribution_strategy)
theos's avatar
theos committed
261

262
    def get_fft_smoothing_kernel_function(self, sigma):
263
        raise NotImplementedError(
264
            "There is no fft smoothing function for PowerSpace.")
theos's avatar
theos committed
265

266
267
268
    # ---Added properties and methods---

    @property
269
    def harmonic_partner(self):
Theo Steininger's avatar
Theo Steininger committed
270
        """ Returns the Space of which this is the power space.
271
272
        """
        return self._harmonic_partner
273
274

    @property
Martin Reinecke's avatar
Martin Reinecke committed
275
276
    def binbounds(self):
        return self._binbounds
277
278
279

    @property
    def pindex(self):
280
        """ A distributed_data_object having the shape of the harmonic partner
Theo Steininger's avatar
Theo Steininger committed
281
282
        space containing the indices of the power bin a pixel belongs to.
        """
283
284
285
286
        return self._pindex

    @property
    def kindex(self):
Theo Steininger's avatar
Theo Steininger committed
287
288
        """ Sorted array of all k-modes.
        """
289
290
291
292
        return self._kindex

    @property
    def rho(self):
Theo Steininger's avatar
Theo Steininger committed
293
294
        """Degeneracy factor of the individual k-vectors.
        """
295
        return self._rho
296

297
298
299
    # ---Serialization---

    def _to_hdf5(self, hdf5_group):
Martin Reinecke's avatar
Martin Reinecke committed
300
301
302
303
        hdf5_group.attrs['binbounds'] = str(self._binbounds)
        hdf5_group.attrs['distribution_strategy'] = \
            self._pindex.distribution_strategy

304
        return {
305
            'harmonic_partner': self.harmonic_partner,
306
307
308
        }

    @classmethod
Theo Steininger's avatar
Theo Steininger committed
309
    def _from_hdf5(cls, hdf5_group, repository):
Martin Reinecke's avatar
Martin Reinecke committed
310
        hp = repository.get('harmonic_partner', hdf5_group)
Martin Reinecke's avatar
Martin Reinecke committed
311
        bb = ast.literal_eval(hdf5_group.attrs['binbounds'])
Martin Reinecke's avatar
Martin Reinecke committed
312
313
        ds = hdf5_group.attrs['distribution_strategy']
        return PowerSpace(hp, ds, binbounds=bb)