lm_space.py 6.38 KB
Newer Older
csongor's avatar
csongor committed
1 2 3 4
from __future__ import division

import numpy as np

5
from nifty.spaces.space import Space
theos's avatar
theos committed
6

csongor's avatar
csongor committed
7 8 9
from nifty.config import about,\
                         nifty_configuration as gc,\
                         dependency_injector as gdi
theos's avatar
theos committed
10

Jait Dixit's avatar
Jait Dixit committed
11 12 13 14
from lm_helper import _distance_array_helper

from d2o import arange

csongor's avatar
csongor committed
15 16 17 18
gl = gdi.get('libsharp_wrapper_gl')
hp = gdi.get('healpy')


19
class LMSpace(Space):
csongor's avatar
csongor committed
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 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
    """
        ..       __
        ..     /  /
        ..    /  /    __ ____ ___
        ..   /  /   /   _    _   |
        ..  /  /_  /  / /  / /  /
        ..  \___/ /__/ /__/ /__/  space class

        NIFTY subclass for spherical harmonics components, for representations
        of fields on the two-sphere.

        Parameters
        ----------
        lmax : int
            Maximum :math:`\ell`-value up to which the spherical harmonics
            coefficients are to be used.
        mmax : int, *optional*
            Maximum :math:`m`-value up to which the spherical harmonics
            coefficients are to be used (default: `lmax`).
        dtype : numpy.dtype, *optional*
            Data type of the field values (default: numpy.complex128).

        See Also
        --------
        hp_space : A class for the HEALPix discretization of the sphere [#]_.
        gl_space : A class for the Gauss-Legendre discretization of the
            sphere [#]_.

        Notes
        -----
        Hermitian symmetry, i.e. :math:`a_{\ell -m} = \overline{a}_{\ell m}` is
        always assumed for the spherical harmonics components, i.e. only fields
        on the two-sphere with real-valued representations in position space
        can be handled.

        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
            One-dimensional array containing the two numbers `lmax` and
            `mmax`.
        dtype : numpy.dtype
            Data type of the field values.
        discrete : bool
            Parameter captioning the fact that an :py:class:`lm_space` is
            always discrete.
        vol : numpy.ndarray
            Pixel volume of the :py:class:`lm_space`, which is always 1.
    """

    def __init__(self, lmax, mmax=None, dtype=np.dtype('complex128')):
        """
            Sets the attributes for an lm_space class instance.

            Parameters
            ----------
            lmax : int
                Maximum :math:`\ell`-value up to which the spherical harmonics
                coefficients are to be used.
            mmax : int, *optional*
                Maximum :math:`m`-value up to which the spherical harmonics
                coefficients are to be used (default: `lmax`).
            dtype : numpy.dtype, *optional*
                Data type of the field values (default: numpy.complex128).

            Returns
            -------
            None.

            Raises
            ------
            ImportError
                If neither the libsharp_wrapper_gl nor the healpy module are
                available.
            ValueError
                If input `nside` is invaild.

        """

        # check imports
        if not gc['use_libsharp'] and not gc['use_healpy']:
            raise ImportError(about._errors.cstring(
                "ERROR: neither libsharp_wrapper_gl nor healpy activated."))

csongor's avatar
csongor committed
112 113 114
        super(LMSpace, self).__init__(dtype)
        self._lmax = self._parse_lmax(lmax)
        self._mmax = self._parse_mmax(mmax)
csongor's avatar
csongor committed
115

theos's avatar
theos committed
116
    def distance_array(self, distribution_strategy):
Jait Dixit's avatar
Jait Dixit committed
117 118 119 120 121 122 123 124 125 126 127 128 129
        dists = arange(
            start=0, stop=self.shape[0], dtype=np.float128,
            distribution_strategy=distribution_strategy
        )

        l = hp.Alm.getlm(lmax=self.lmax)[0]
        dists = dists.apply_scalar_function(
            lambda x: _distance_array_helper(
                int(x), l, hp.Alm.getsize(self.lmax), self.lmax
                )
            )

        return dists
theos's avatar
theos committed
130 131 132 133 134 135

    def get_smoothing_kernel_function(self, sigma):
        if sigma is None:
            sigma = np.sqrt(2) * np.pi / (self.lmax + 1)

        return lambda x: np.exp(-0.5 * x * (x + 1) * sigma**2)
csongor's avatar
csongor committed
136

137
    # ---Mandatory properties and methods---
csongor's avatar
csongor committed
138 139 140 141

    @property
    def harmonic(self):
        return True
csongor's avatar
csongor committed
142 143

    @property
144 145
    def shape(self):
        return (self.dim, )
csongor's avatar
csongor committed
146 147

    @property
148 149 150
    def dim(self):
        l = self.lmax
        m = self.mmax
theos's avatar
theos committed
151 152 153 154
        # the LMSpace consist of the full triangle (including -m's!),
        # minus two little triangles if mmax < lmax
        # dim = (((2*(l+1)-1)+1)**2/4 - 2 * (l-m)(l-m+1)/2
        return np.int((l+1)**2 - (l-m)*(l-m+1.))
csongor's avatar
csongor committed
155

156 157 158 159
    @property
    def total_volume(self):
        # the individual pixels have a fixed volume of 1.
        return np.float(self.dim)
csongor's avatar
csongor committed
160

161 162 163 164
    def copy(self):
        return self.__class__(lmax=self.lmax,
                              mmax=self.mmax,
                              dtype=self.dtype)
csongor's avatar
csongor committed
165

166 167 168
    def weight(self, x, power=1, axes=None, inplace=False):
        if inplace:
            return x
csongor's avatar
csongor committed
169
        else:
170
            return x.copy()
csongor's avatar
csongor committed
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185

    # ---Added properties and methods---

    @property
    def lmax(self):
        return self._lmax

    @property
    def mmax(self):
        return self._mmax

    def _parse_lmax(self, lmax):
        lmax = np.int(lmax)
        if lmax < 1:
            raise ValueError(about._errors.cstring(
186
                "ERROR: negative lmax is not allowed."))
csongor's avatar
csongor committed
187 188 189 190 191 192 193
        # exception lmax == 2 (nside == 1)
        if (lmax % 2 == 0) and (lmax > 2):
            about.warnings.cprint(
                "WARNING: unrecommended parameter (lmax <> 2*n+1).")
        return lmax

    def _parse_mmax(self, mmax):
194
        if mmax is None:
csongor's avatar
csongor committed
195
            mmax = self.lmax
196 197 198 199 200 201 202 203 204 205
        else:
            mmax = int(mmax)

        if mmax < 1:
            raise ValueError(about._errors.cstring(
                "ERROR: mmax < 1 is not allowed."))
        if mmax > self.lmax:
            raise ValueError(about._errors.cstring(
                "ERROR: mmax > lmax is not allowed."))
        if mmax != self.lmax:
csongor's avatar
csongor committed
206
            about.warnings.cprint(
207
                "WARNING: unrecommended parameter combination (mmax <> lmax).")
csongor's avatar
csongor committed
208
        return mmax