power_space.py 7.95 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.
Theo Steininger's avatar
Theo Steininger committed
18

19
import numpy as np
Martin Reinecke's avatar
Martin Reinecke committed
20
21
from .space import Space
from .. import dobj
Theo Steininger's avatar
Theo Steininger committed
22
23


Theo Steininger's avatar
Theo Steininger committed
24
class PowerSpace(Space):
Martin Reinecke's avatar
Martin Reinecke committed
25
    """NIFTY class for spaces of power spectra.
Theo Steininger's avatar
Theo Steininger committed
26
27
28
29
30

    Parameters
    ----------
    harmonic_partner : Space
        The harmonic Space of which this is the power space.
Martin Reinecke's avatar
Martin Reinecke committed
31
32
33
34
35
36
37
38
39
40
41
42
    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
43
44
45
46
47
48
49
        (default : None)

    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.
    """
50

51
52
    _powerIndexCache = {}

53
54
    # ---Overwritten properties and methods---

Martin Reinecke's avatar
Martin Reinecke committed
55
    @staticmethod
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
56
    def linear_binbounds(nbin, first_bound, last_bound):
Martin Reinecke's avatar
Martin Reinecke committed
57
58
59
60
61
62
63
64
65
66
67
68
        """
        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)
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
69
70
        assert nbin >= 3, "nbin must be at least 3"
        return np.linspace(float(first_bound), float(last_bound), nbin-1)
Martin Reinecke's avatar
Martin Reinecke committed
71
72

    @staticmethod
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
73
    def logarithmic_binbounds(nbin, first_bound, last_bound):
Martin Reinecke's avatar
Martin Reinecke committed
74
75
76
77
78
79
80
81
82
83
84
85
        """
        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.
        """
Martin Reinecke's avatar
Martin Reinecke committed
86
        nbin = int(nbin)
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
87
        assert nbin >= 3, "nbin must be at least 3"
Martin Reinecke's avatar
Martin Reinecke committed
88
89
90
        return np.logspace(np.log(float(first_bound)),
                           np.log(float(last_bound)),
                           nbin-1, base=np.e)
Martin Reinecke's avatar
Martin Reinecke committed
91

92
93
94
95
96
97
98
99
    @staticmethod
    def useful_binbounds(space, logarithmic, nbin=None):
        if not (isinstance(space, Space) and space.harmonic):
            raise ValueError("first argument must be a harmonic space.")
        if logarithmic is None and nbin is None:
            return None
        nbin = None if nbin is None else int(nbin)
        logarithmic = bool(logarithmic)
100
        dists = space.get_unique_k_lengths()
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
        if len(dists) < 3:
            raise ValueError("Space does not have enough unique k lengths")
        lbound = 0.5*(dists[0]+dists[1])
        rbound = 0.5*(dists[-2]+dists[-1])
        dists[0] = lbound
        dists[-1] = rbound
        if logarithmic:
            dists = np.log(dists)
        binsz_min = np.max(np.diff(dists))
        nbin_max = int((dists[-1]-dists[0])/binsz_min)+2
        if nbin is None:
            nbin = nbin_max
        assert nbin >= 3, "nbin must be at least 3"
        if nbin > nbin_max:
            raise ValueError("nbin is too large")
        if logarithmic:
            return PowerSpace.logarithmic_binbounds(nbin, lbound, rbound)
        else:
            return PowerSpace.linear_binbounds(nbin, lbound, rbound)

Martin Reinecke's avatar
Martin Reinecke committed
121
    def __init__(self, harmonic_partner, binbounds=None):
Martin Reinecke's avatar
Martin Reinecke committed
122
        super(PowerSpace, self).__init__()
123
        self._needed_for_hash += ['_harmonic_partner', '_binbounds']
124

Martin Reinecke's avatar
Martin Reinecke committed
125
126
127
        if not (isinstance(harmonic_partner, Space) and
                harmonic_partner.harmonic):
            raise ValueError("harmonic_partner must be a harmonic space.")
Martin Reinecke's avatar
Martin Reinecke committed
128
129
130
        if harmonic_partner.scalar_dvol() is None:
            raise ValueError("harmonic partner must have "
                             "scalar volume factors")
131
        self._harmonic_partner = harmonic_partner
Martin Reinecke's avatar
Martin Reinecke committed
132
        pdvol = harmonic_partner.scalar_dvol()
133

Martin Reinecke's avatar
Martin Reinecke committed
134
135
        if binbounds is not None:
            binbounds = tuple(binbounds)
136

Martin Reinecke's avatar
Martin Reinecke committed
137
        key = (harmonic_partner, binbounds)
138
        if self._powerIndexCache.get(key) is None:
139
            k_length_array = self.harmonic_partner.get_k_length_array()
140
            temp_pindex = self._compute_pindex(
141
                                harmonic_partner=self.harmonic_partner,
142
                                k_length_array=k_length_array,
Martin Reinecke's avatar
Martin Reinecke committed
143
                                binbounds=binbounds)
Martin Reinecke's avatar
Martin Reinecke committed
144
            temp_rho = dobj.to_ndarray(dobj.bincount(temp_pindex.ravel()))
Martin Reinecke's avatar
Martin Reinecke committed
145
            assert not (temp_rho == 0).any(), "empty bins detected"
Martin Reinecke's avatar
Martin Reinecke committed
146
147
            temp_k_lengths = dobj.to_ndarray(dobj.bincount(temp_pindex.ravel(),
                weights=dobj.from_ndarray(k_length_array.ravel())) / temp_rho)
Martin Reinecke's avatar
Martin Reinecke committed
148
            temp_dvol = temp_rho*pdvol
Martin Reinecke's avatar
Martin Reinecke committed
149
            self._powerIndexCache[key] = (binbounds,
150
                                          temp_pindex,
Martin Reinecke's avatar
Martin Reinecke committed
151
                                          temp_k_lengths,
Martin Reinecke's avatar
Martin Reinecke committed
152
                                          temp_dvol)
153

Martin Reinecke's avatar
Martin Reinecke committed
154
        (self._binbounds, self._pindex, self._k_lengths, self._dvol) = \
155
156
            self._powerIndexCache[key]

157
    @staticmethod
158
    def _compute_pindex(harmonic_partner, k_length_array, binbounds):
159
        if binbounds is None:
160
            tmp = harmonic_partner.get_unique_k_lengths()
161
            binbounds = 0.5*(tmp[:-1]+tmp[1:])
Martin Reinecke's avatar
Martin Reinecke committed
162
        return dobj.from_ndarray(np.searchsorted(binbounds, k_length_array))
163

164
165
    # ---Mandatory properties and methods---

166
    def __repr__(self):
Martin Reinecke's avatar
stage1    
Martin Reinecke committed
167
168
        return ("PowerSpace(harmonic_partner=%r, binbounds=%r)"
                % (self.harmonic_partner, self._binbounds))
169

170
171
    @property
    def harmonic(self):
172
        return False
173

174
175
    @property
    def shape(self):
Martin Reinecke's avatar
Martin Reinecke committed
176
        return self.k_lengths.shape
177

178
179
180
181
    @property
    def dim(self):
        return self.shape[0]

182
    def scalar_dvol(self):
Martin Reinecke's avatar
Martin Reinecke committed
183
184
185
186
        return None

    def dvol(self):
        return self._dvol
187

188
189
190
    # ---Added properties and methods---

    @property
191
    def harmonic_partner(self):
Martin Reinecke's avatar
Martin Reinecke committed
192
        """Returns the Space of which this is the power space."""
193
        return self._harmonic_partner
194
195

    @property
Martin Reinecke's avatar
Martin Reinecke committed
196
    def binbounds(self):
Martin Reinecke's avatar
Martin Reinecke committed
197
198
199
        """Returns the boundaries between the power spectrum bins as a tuple.
        None is used to indicate natural binning.
        """
Martin Reinecke's avatar
Martin Reinecke committed
200
        return self._binbounds
201
202
203

    @property
    def pindex(self):
Martin Reinecke's avatar
Martin Reinecke committed
204
        """Returns a data object having the shape of the harmonic partner
Theo Steininger's avatar
Theo Steininger committed
205
206
        space containing the indices of the power bin a pixel belongs to.
        """
207
208
209
        return self._pindex

    @property
Martin Reinecke's avatar
Martin Reinecke committed
210
    def k_lengths(self):
Martin Reinecke's avatar
Martin Reinecke committed
211
        """Returns a sorted array of all k-modes."""
Martin Reinecke's avatar
Martin Reinecke committed
212
        return self._k_lengths