hp_space.py 12.9 KB
Newer Older
csongor's avatar
csongor committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
# NIFTY (Numerical Information Field Theory) has been developed at the
# Max-Planck-Institute for Astrophysics.
#
# Copyright (C) 2015 Max-Planck-Society
#
# Author: Marco Selig
# Project homepage: <http://www.mpa-garching.mpg.de/ift/nifty/>
#
# 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/>.

"""
    ..                  __   ____   __
    ..                /__/ /   _/ /  /_
    ..      __ ___    __  /  /_  /   _/  __   __
    ..    /   _   | /  / /   _/ /  /   /  / /  /
    ..   /  / /  / /  / /  /   /  /_  /  /_/  /
    ..  /__/ /__/ /__/ /__/    \___/  \___   /  lm
    ..                               /______/

    NIFTY submodule for grids on the two-sphere.

"""
from __future__ import division

36
import itertools
csongor's avatar
csongor committed
37 38 39 40 41
import numpy as np
import pylab as pl

from d2o import STRATEGIES as DISTRIBUTION_STRATEGIES

42
from nifty.spaces.lm_space import LMSpace
43

44
from nifty.spaces.space import Space
csongor's avatar
csongor committed
45

46
from nifty.config import about, nifty_configuration as gc, \
csongor's avatar
csongor committed
47
                         dependency_injector as gdi
theos's avatar
theos committed
48
from hp_space_paradict import HPSpaceParadict
csongor's avatar
csongor committed
49 50 51 52 53 54
from nifty.nifty_random import random

hp = gdi.get('healpy')

HP_DISTRIBUTION_STRATEGIES = DISTRIBUTION_STRATEGIES['global']

55 56

class HPSpace(Space):
csongor's avatar
csongor committed
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 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 127 128 129
    """
        ..        __
        ..      /  /
        ..     /  /___    ______
        ..    /   _   | /   _   |
        ..   /  / /  / /  /_/  /
        ..  /__/ /__/ /   ____/  space class
        ..           /__/

        NIFTY subclass for HEALPix discretizations of the two-sphere [#]_.

        Parameters
        ----------
        nside : int
            Resolution parameter for the HEALPix discretization, resulting in
            ``12*nside**2`` pixels.

        See Also
        --------
        gl_space : A class for the Gauss-Legendre discretization of the
            sphere [#]_.
        lm_space : A class for spherical harmonic components.

        Notes
        -----
        Only powers of two are allowed for `nside`.

        References
        ----------
        .. [#] K.M. Gorski et al., 2005, "HEALPix: A Framework for
               High-Resolution Discretization and Fast Analysis of Data
               Distributed on the Sphere", *ApJ* 622..759G.
        .. [#] M. Reinecke and D. Sverre Seljebotn, 2013, "Libsharp - spherical
               harmonic transforms revisited";
               `arXiv:1303.4945 <http://www.arxiv.org/abs/1303.4945>`_

        Attributes
        ----------
        para : numpy.ndarray
            Array containing the number `nside`.
        dtype : numpy.dtype
            Data type of the field values, which is always numpy.float64.
        discrete : bool
            Whether or not the underlying space is discrete, always ``False``
            for spherical spaces.
        vol : numpy.ndarray
            An array with one element containing the pixel size.
    """

    def __init__(self, nside):
        """
            Sets the attributes for a hp_space class instance.

            Parameters
            ----------
            nside : int
                Resolution parameter for the HEALPix discretization, resulting
                in ``12*nside**2`` pixels.

            Returns
            -------
            None

            Raises
            ------
            ImportError
                If the healpy module is not available.
            ValueError
                If input `nside` is invaild.

        """
        # check imports
        if not gc['use_healpy']:
Jait Dixit's avatar
Jait Dixit committed
130
            raise ImportError("ERROR: healpy not available.")
csongor's avatar
csongor committed
131

Jait Dixit's avatar
Jait Dixit committed
132 133
        # setup paradict
        self.paradict = HPSpaceParadict(nside=nside)
csongor's avatar
csongor committed
134

Jait Dixit's avatar
Jait Dixit committed
135 136
        # setup dtype
        self.dtype = np.dtype('float64')
Jait Dixit's avatar
Jait Dixit committed
137 138
        # HPSpace is never harmonic
        self._harmonic = False
csongor's avatar
csongor committed
139 140

    def copy(self):
141
        return HPSpace(nside=self.paradict['nside'])
csongor's avatar
csongor committed
142 143 144

    @property
    def shape(self):
Jait Dixit's avatar
Jait Dixit committed
145
        return (np.int(12 * self.paradict['nside'] ** 2),)
csongor's avatar
csongor committed
146 147

    @property
Jait Dixit's avatar
Jait Dixit committed
148 149
    def dim(self):
        return np.int(12 * self.paradict['nside'] ** 2)
csongor's avatar
csongor committed
150

Jait Dixit's avatar
Jait Dixit committed
151
    def weight(self, x, power=1, axes=None, inplace=False):
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
        # check if the axes provided are valid given the input shape
        if axes is not None and \
                not all(axis in range(len(x.shape)) for axis in axes):
            raise ValueError("ERROR: Provided axes does not match array shape")

        weight = np.array(list(
            itertools.chain.from_iterable(
                itertools.repeat(
                    (4 * np.pi / 12 * self.paradict['nside'] ** 2) ** power,
                    12 * self.paradict['nside'] ** 2
                )
            )
        ))

        if axes is not None:
            # reshape the weight array to match the input shape
            new_shape = np.ones(x.shape)
            for index in range(len(axes)):
                new_shape[index] = len(weight)
            weight = weight.reshape(new_shape)

        if inplace:
            x *= weight
            result_x = x
        else:
            result_x = x * weight

        return result_x
csongor's avatar
csongor committed
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229

    def get_plot(self, x, title="", vmin=None, vmax=None, power=False, unit="",
                 norm=None, cmap=None, cbar=True, other=None, legend=False,
                 mono=True, **kwargs):
        """
            Creates a plot of field values according to the specifications
            given by the parameters.

            Parameters
            ----------
            x : numpy.ndarray
                Array containing the field values.

            Returns
            -------
            None

            Other parameters
            ----------------
            title : string, *optional*
                Title of the plot (default: "").
            vmin : float, *optional*
                Minimum value to be displayed (default: ``min(x)``).
            vmax : float, *optional*
                Maximum value to be displayed (default: ``max(x)``).
            power : bool, *optional*
                Whether to plot the power contained in the field or the field
                values themselves (default: False).
            unit : string, *optional*
                Unit of the field values (default: "").
            norm : string, *optional*
                Scaling of the field values before plotting (default: None).
            cmap : matplotlib.colors.LinearSegmentedColormap, *optional*
                Color map to be used for two-dimensional plots (default: None).
            cbar : bool, *optional*
                Whether to show the color bar or not (default: True).
            other : {single object, tuple of objects}, *optional*
                Object or tuple of objects to be added, where objects can be
                scalars, arrays, or fields (default: None).
            legend : bool, *optional*
                Whether to show the legend or not (default: False).
            mono : bool, *optional*
                Whether to plot the monopole or not (default: True).
            save : string, *optional*
                Valid file name where the figure is to be stored, by default
                the figure is not saved (default: False).
            iter : int, *optional*
                Number of iterations performed in the HEALPix basis
                transformation.
        """
230 231
        from nifty.field import Field

csongor's avatar
csongor committed
232 233 234 235 236
        try:
            x = x.get_full_data()
        except AttributeError:
            pass

Jait Dixit's avatar
Jait Dixit committed
237
        if (not pl.isinteractive()) and (not bool(kwargs.get("save", False))):
csongor's avatar
csongor committed
238 239
            about.warnings.cprint("WARNING: interactive mode off.")

Jait Dixit's avatar
Jait Dixit committed
240
        if (power):
csongor's avatar
csongor committed
241 242
            x = self.calc_power(x, **kwargs)

Jait Dixit's avatar
Jait Dixit committed
243 244 245 246
            fig = pl.figure(num=None, figsize=(6.4, 4.8), dpi=None,
                            facecolor="none",
                            edgecolor="none", frameon=False,
                            FigureClass=pl.Figure)
csongor's avatar
csongor committed
247 248 249
            ax0 = fig.add_axes([0.12, 0.12, 0.82, 0.76])

            xaxes = np.arange(3 * self.para[0], dtype=np.int)
Jait Dixit's avatar
Jait Dixit committed
250
            if (vmin is None):
csongor's avatar
csongor committed
251
                vmin = np.min(x[:mono].tolist(
Jait Dixit's avatar
Jait Dixit committed
252 253 254
                ) + (xaxes * (2 * xaxes + 1) * x)[1:].tolist(), axis=None,
                              out=None)
            if (vmax is None):
csongor's avatar
csongor committed
255
                vmax = np.max(x[:mono].tolist(
Jait Dixit's avatar
Jait Dixit committed
256 257
                ) + (xaxes * (2 * xaxes + 1) * x)[1:].tolist(), axis=None,
                              out=None)
csongor's avatar
csongor committed
258
            ax0.loglog(xaxes[1:], (xaxes * (2 * xaxes + 1) * x)[1:], color=[0.0,
Jait Dixit's avatar
Jait Dixit committed
259 260 261 262 263 264 265 266 267 268 269
                                                                            0.5,
                                                                            0.0],
                       label="graph 0", linestyle='-', linewidth=2.0, zorder=1)
            if (mono):
                ax0.scatter(0.5 * (xaxes[1] + xaxes[2]), x[0], s=20,
                            color=[0.0, 0.5, 0.0], marker='o',
                            cmap=None, norm=None, vmin=None, vmax=None,
                            alpha=None, linewidths=None, verts=None, zorder=1)

            if (other is not None):
                if (isinstance(other, tuple)):
csongor's avatar
csongor committed
270 271
                    other = list(other)
                    for ii in xrange(len(other)):
Jait Dixit's avatar
Jait Dixit committed
272
                        if (isinstance(other[ii], Field)):
csongor's avatar
csongor committed
273 274 275
                            other[ii] = other[ii].power(**kwargs)
                        else:
                            other[ii] = self.enforce_power(other[ii])
Jait Dixit's avatar
Jait Dixit committed
276
                elif (isinstance(other, Field)):
csongor's avatar
csongor committed
277 278 279 280 281
                    other = [other.power(**kwargs)]
                else:
                    other = [self.enforce_power(other)]
                imax = max(1, len(other) - 1)
                for ii in xrange(len(other)):
Jait Dixit's avatar
Jait Dixit committed
282 283 284 285 286
                    ax0.loglog(xaxes[1:],
                               (xaxes * (2 * xaxes + 1) * other[ii])[1:],
                               color=[max(0.0, 1.0 - (2 * ii / imax) ** 2),
                                      0.5 * ((2 * ii - imax) / imax)
                                      ** 2, max(0.0, 1.0 - (
287
                                       2 * (ii - imax) / imax) ** 2)],
Jait Dixit's avatar
Jait Dixit committed
288 289 290 291 292 293 294 295 296
                               label="graph " + str(ii + 1), linestyle='-',
                               linewidth=1.0, zorder=-ii)
                    if (mono):
                        ax0.scatter(0.5 * (xaxes[1] + xaxes[2]), other[ii][0],
                                    s=20,
                                    color=[max(0.0, 1.0 - (2 * ii / imax) ** 2),
                                           0.5 * ((2 * ii - imax) / imax) ** 2,
                                           max(
                                               0.0, 1.0 - (
297 298
                                                   2 * (
                                                   ii - imax) / imax) ** 2)],
Jait Dixit's avatar
Jait Dixit committed
299 300 301 302
                                    marker='o', cmap=None, norm=None, vmin=None,
                                    vmax=None, alpha=None, linewidths=None,
                                    verts=None, zorder=-ii)
                if (legend):
csongor's avatar
csongor committed
303 304 305 306 307 308 309 310 311
                    ax0.legend()

            ax0.set_xlim(xaxes[1], xaxes[-1])
            ax0.set_xlabel(r"$\ell$")
            ax0.set_ylim(vmin, vmax)
            ax0.set_ylabel(r"$\ell(2\ell+1) C_\ell$")
            ax0.set_title(title)

        else:
Jait Dixit's avatar
Jait Dixit committed
312 313 314
            if (norm == "log"):
                if (vmin is not None):
                    if (vmin <= 0):
csongor's avatar
csongor committed
315 316
                        raise ValueError(about._errors.cstring(
                            "ERROR: nonpositive value(s)."))
Jait Dixit's avatar
Jait Dixit committed
317
                elif (np.min(x, axis=None, out=None) <= 0):
csongor's avatar
csongor committed
318 319
                    raise ValueError(about._errors.cstring(
                        "ERROR: nonpositive value(s)."))
Jait Dixit's avatar
Jait Dixit committed
320
            if (cmap is None):
csongor's avatar
csongor committed
321 322
                cmap = pl.cm.jet  # default
            cmap.set_under(color='k', alpha=0.0)  # transparent box
Jait Dixit's avatar
Jait Dixit committed
323 324 325 326 327 328
            hp.mollview(x, fig=None, rot=None, coord=None, unit=unit, xsize=800,
                        title=title, nest=False, min=vmin, max=vmax,
                        flip="astro", remove_dip=False,
                        remove_mono=False, gal_cut=0, format="%g", format2="%g",
                        cbar=cbar, cmap=cmap, notext=False, norm=norm,
                        hold=False, margins=None, sub=None)
csongor's avatar
csongor committed
329 330
            fig = pl.gcf()

Jait Dixit's avatar
Jait Dixit committed
331 332 333 334 335
        if (bool(kwargs.get("save", False))):
            fig.savefig(str(kwargs.get("save")), dpi=None, facecolor="none",
                        edgecolor="none", orientation="portrait",
                        papertype=None, format=None, transparent=False,
                        bbox_inches=None, pad_inches=0.1)
csongor's avatar
csongor committed
336 337 338
            pl.close(fig)
        else:
            fig.canvas.draw()