power_space.py 9.03 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
from .structured_domain import StructuredDomain
Martin Reinecke's avatar
Martin Reinecke committed
21
from .. import dobj
Theo Steininger's avatar
Theo Steininger committed
22 23


Martin Reinecke's avatar
Martin Reinecke committed
24
class PowerSpace(StructuredDomain):
Martin Reinecke's avatar
Martin Reinecke committed
25
    """NIFTy class for spaces of power spectra.
Theo Steininger's avatar
Theo Steininger committed
26

Martin Reinecke's avatar
Martin Reinecke committed
27
    A power space is the result of a projection of a harmonic domain where
Martin Reinecke's avatar
Martin Reinecke committed
28 29
    k-modes of equal length get mapped to one power index.

Theo Steininger's avatar
Theo Steininger committed
30 31
    Parameters
    ----------
Martin Reinecke's avatar
Martin Reinecke committed
32 33 34
    harmonic_partner : StructuredDomain
        The harmonic dmain of which this is the power space.
    binbounds : None, or tuple of float
Martin Reinecke's avatar
Martin Reinecke committed
35 36 37 38 39 40 41 42 43 44
        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.
45
            (default : None)
Theo Steininger's avatar
Theo Steininger committed
46
    """
47

48 49
    _powerIndexCache = {}

Martin Reinecke's avatar
Martin Reinecke committed
50
    @staticmethod
Martin Reinecke's avatar
PEP8  
Martin Reinecke committed
51
    def linear_binbounds(nbin, first_bound, last_bound):
Martin Reinecke's avatar
Martin Reinecke committed
52 53
        """Produces linearly spaced bin bounds.

Martin Reinecke's avatar
Martin Reinecke committed
54 55 56 57
        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.

Martin Reinecke's avatar
Martin Reinecke committed
58
        nbin : int
Martin Reinecke's avatar
Martin Reinecke committed
59
            the number of bins
Martin Reinecke's avatar
Martin Reinecke committed
60
        first_bound, last_bound : float
Martin Reinecke's avatar
Martin Reinecke committed
61 62 63 64 65
            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.
        """
        nbin = int(nbin)
66 67
        if nbin < 3:
            raise ValueError("nbin must be at least 3")
Martin Reinecke's avatar
PEP8  
Martin Reinecke committed
68
        return np.linspace(float(first_bound), float(last_bound), nbin-1)
Martin Reinecke's avatar
Martin Reinecke committed
69 70

    @staticmethod
Martin Reinecke's avatar
PEP8  
Martin Reinecke committed
71
    def logarithmic_binbounds(nbin, first_bound, last_bound):
Martin Reinecke's avatar
Martin Reinecke committed
72 73
        """Produces logarithmically spaced bin bounds.

Martin Reinecke's avatar
Martin Reinecke committed
74 75 76 77 78
        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
79
        nbin : int
Martin Reinecke's avatar
Martin Reinecke committed
80
            the number of bins
Martin Reinecke's avatar
Martin Reinecke committed
81
        first_bound, last_bound : float
Martin Reinecke's avatar
Martin Reinecke committed
82 83 84 85
            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.
        """
Martin Reinecke's avatar
Martin Reinecke committed
86
        nbin = int(nbin)
87 88
        if nbin < 3:
            raise ValueError("nbin must be at least 3")
Martin Reinecke's avatar
Martin Reinecke committed
89 90 91
        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
92

93 94
    @staticmethod
    def useful_binbounds(space, logarithmic, nbin=None):
Martin Reinecke's avatar
Martin Reinecke committed
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
        """Produces bin bounds suitable for a given domain.

        This will produce a binbounds array with `nbin-1` entries, if `nbin` is
        supplied, or the maximum number of entries that does not produce empty
        bins, if `nbin` is not supplied.
        The first and last bin boundary are inferred from `space`.

        space : StructuredDomain
            the domain for which the binbounds will be computed.
        logarithmic : bool
            If True bins will have equal size in linear space; otherwise they
            will have equali size in logarithmic space.
        nbin : int, optional
            the number of bins
            If None, the highest possible number of bins will be used
        """
Martin Reinecke's avatar
Martin Reinecke committed
111
        if not (isinstance(space, StructuredDomain) and space.harmonic):
112 113 114 115 116
            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)
117
        dists = space.get_unique_k_lengths()
118 119 120 121 122 123 124 125 126 127 128 129
        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
130 131
        if nbin < 3:
            raise ValueError("nbin must be at least 3")
132 133 134 135 136 137 138
        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
139
    def __init__(self, harmonic_partner, binbounds=None):
Martin Reinecke's avatar
Martin Reinecke committed
140
        super(PowerSpace, self).__init__()
141
        self._needed_for_hash += ['_harmonic_partner', '_binbounds']
142

Martin Reinecke's avatar
Martin Reinecke committed
143
        if not (isinstance(harmonic_partner, StructuredDomain) and
Martin Reinecke's avatar
Martin Reinecke committed
144 145
                harmonic_partner.harmonic):
            raise ValueError("harmonic_partner must be a harmonic space.")
Martin Reinecke's avatar
Martin Reinecke committed
146 147 148
        if harmonic_partner.scalar_dvol() is None:
            raise ValueError("harmonic partner must have "
                             "scalar volume factors")
149
        self._harmonic_partner = harmonic_partner
Martin Reinecke's avatar
Martin Reinecke committed
150
        pdvol = harmonic_partner.scalar_dvol()
151

Martin Reinecke's avatar
Martin Reinecke committed
152 153
        if binbounds is not None:
            binbounds = tuple(binbounds)
154

Martin Reinecke's avatar
Martin Reinecke committed
155
        key = (harmonic_partner, binbounds)
156
        if self._powerIndexCache.get(key) is None:
157
            k_length_array = self.harmonic_partner.get_k_length_array()
Martin Reinecke's avatar
Martin Reinecke committed
158 159 160 161 162 163
            if binbounds is None:
                tmp = harmonic_partner.get_unique_k_lengths()
                tbb = 0.5*(tmp[:-1]+tmp[1:])
            else:
                tbb = binbounds
            locdat = np.searchsorted(tbb, dobj.local_data(k_length_array.val))
Martin Reinecke's avatar
tweaks  
Martin Reinecke committed
164
            temp_pindex = dobj.from_local_data(
165 166
                k_length_array.val.shape, locdat,
                dobj.distaxis(k_length_array.val))
Martin Reinecke's avatar
Martin Reinecke committed
167
            nbin = len(tbb)+1
Martin Reinecke's avatar
Martin Reinecke committed
168 169
            temp_rho = np.bincount(dobj.local_data(temp_pindex).ravel(),
                                   minlength=nbin)
Martin Reinecke's avatar
Martin Reinecke committed
170
            temp_rho = dobj.np_allreduce_sum(temp_rho)
171 172
            if (temp_rho == 0).any():
                raise ValueError("empty bins detected")
Martin Reinecke's avatar
Martin Reinecke committed
173 174 175
            # The explicit conversion to float64 is necessary because bincount
            # sometimes returns its result as an integer array, even when
            # floating-point weights are present ...
176 177
            temp_k_lengths = np.bincount(
                dobj.local_data(temp_pindex).ravel(),
Martin Reinecke's avatar
Martin Reinecke committed
178
                weights=dobj.local_data(k_length_array.val).ravel(),
Martin Reinecke's avatar
Martin Reinecke committed
179
                minlength=nbin).astype(np.float64, copy=False)
Martin Reinecke's avatar
Martin Reinecke committed
180
            temp_k_lengths = dobj.np_allreduce_sum(temp_k_lengths) / temp_rho
Martin Reinecke's avatar
Martin Reinecke committed
181
            temp_dvol = temp_rho*pdvol
Martin Reinecke's avatar
Martin Reinecke committed
182 183
            self._powerIndexCache[key] = (binbounds, temp_pindex,
                                          temp_k_lengths, temp_dvol)
184

Martin Reinecke's avatar
Martin Reinecke committed
185
        (self._binbounds, self._pindex, self._k_lengths, self._dvol) = \
186 187
            self._powerIndexCache[key]

188
    def __repr__(self):
Martin Reinecke's avatar
stage1  
Martin Reinecke committed
189 190
        return ("PowerSpace(harmonic_partner=%r, binbounds=%r)"
                % (self.harmonic_partner, self._binbounds))
191

192 193
    @property
    def harmonic(self):
194
        return False
195

196 197
    @property
    def shape(self):
Martin Reinecke's avatar
Martin Reinecke committed
198
        return self.k_lengths.shape
199

200
    @property
Martin Reinecke's avatar
Martin Reinecke committed
201
    def size(self):
202 203
        return self.shape[0]

204
    def scalar_dvol(self):
Martin Reinecke's avatar
Martin Reinecke committed
205 206 207 208
        return None

    def dvol(self):
        return self._dvol
209

210
    @property
211
    def harmonic_partner(self):
Martin Reinecke's avatar
Martin Reinecke committed
212
        """Returns the Space of which this is the power space."""
213
        return self._harmonic_partner
214 215

    @property
Martin Reinecke's avatar
Martin Reinecke committed
216
    def binbounds(self):
Martin Reinecke's avatar
Martin Reinecke committed
217
        """Returns the boundaries between the power spectrum bins as a tuple.
Martin Reinecke's avatar
Martin Reinecke committed
218 219

        `None` is used to indicate natural binning.
Martin Reinecke's avatar
Martin Reinecke committed
220
        """
Martin Reinecke's avatar
Martin Reinecke committed
221
        return self._binbounds
222 223 224

    @property
    def pindex(self):
Martin Reinecke's avatar
Martin Reinecke committed
225
        """Returns a data object having the shape of the harmonic partner
Theo Steininger's avatar
Theo Steininger committed
226 227
        space containing the indices of the power bin a pixel belongs to.
        """
228 229 230
        return self._pindex

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