lm_space.py 7.15 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# NIFTy
# Copyright (C) 2017  Theo Steininger
#
# Author: Theo Steininger
#
# 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/>.

csongor's avatar
csongor committed
19
20
21
22
from __future__ import division

import numpy as np

23
from nifty.spaces.space import Space
theos's avatar
theos committed
24

25
from nifty.config import nifty_configuration as gc,\
csongor's avatar
csongor committed
26
                         dependency_injector as gdi
theos's avatar
theos committed
27

Jait Dixit's avatar
Jait Dixit committed
28
29
from d2o import arange

csongor's avatar
csongor committed
30
31
32
gl = gdi.get('libsharp_wrapper_gl')
hp = gdi.get('healpy')

Martin Reinecke's avatar
Martin Reinecke committed
33
34
35
36
37
38
39
def _distance_array_helper(index_array, lmax):
    u=2*lmax+1
    index_half=(index_array+np.minimum(lmax,index_array)+1)//2
    m = (np.ceil((u - np.sqrt(u*u - 8 * (index_half - lmax))) / 2)).astype(int)
    res = (index_half - m * (u - m) // 2).astype(np.float64)
    return res

csongor's avatar
csongor committed
40

Theo Steininger's avatar
Theo Steininger committed
41
class LMSpace(Space):
csongor's avatar
csongor committed
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
    """
        ..       __
        ..     /  /
        ..    /  /    __ ____ ___
        ..   /  /   /   _    _   |
        ..  /  /_  /  / /  / /  /
        ..  \___/ /__/ /__/ /__/  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.
    """

100
    def __init__(self, lmax, dtype=None):
csongor's avatar
csongor committed
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
130
        """
            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']:
131
132
            raise ImportError(
                "neither libsharp_wrapper_gl nor healpy activated.")
csongor's avatar
csongor committed
133

csongor's avatar
csongor committed
134
135
        super(LMSpace, self).__init__(dtype)
        self._lmax = self._parse_lmax(lmax)
csongor's avatar
csongor committed
136

137
138
    def hermitian_decomposition(self, x, axes=None,
                                preserve_gaussian_variance=False):
139
140
141
142
143
144
145
        hermitian_part = x.copy_empty()
        anti_hermitian_part = x.copy_empty()
        hermitian_part[:] = x.real
        anti_hermitian_part[:] = x.imag
        return (hermitian_part, anti_hermitian_part)

        # ---Mandatory properties and methods---
csongor's avatar
csongor committed
146
147
148
149

    @property
    def harmonic(self):
        return True
csongor's avatar
csongor committed
150
151

    @property
152
153
    def shape(self):
        return (self.dim, )
csongor's avatar
csongor committed
154
155

    @property
156
157
    def dim(self):
        l = self.lmax
theos's avatar
theos committed
158
159
160
        # 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
161
162
163
        # dim = np.int((l+1)**2 - (l-m)*(l-m+1.))
        # We fix l == m
        return np.int((l+1)**2)
csongor's avatar
csongor committed
164

165
166
167
168
    @property
    def total_volume(self):
        # the individual pixels have a fixed volume of 1.
        return np.float(self.dim)
csongor's avatar
csongor committed
169

170
171
172
    def copy(self):
        return self.__class__(lmax=self.lmax,
                              dtype=self.dtype)
csongor's avatar
csongor committed
173

174
175
176
    def weight(self, x, power=1, axes=None, inplace=False):
        if inplace:
            return x
csongor's avatar
csongor committed
177
        else:
178
            return x.copy()
csongor's avatar
csongor committed
179

180
181
182
183
184
185
186
187
188
189
    def get_distance_array(self, distribution_strategy):
        dists = arange(start=0, stop=self.shape[0],
                       distribution_strategy=distribution_strategy)

        dists = dists.apply_scalar_function(
            lambda x: _distance_array_helper(x, self.lmax),
            dtype=np.float)

        return dists

190
    def get_fft_smoothing_kernel_function(self, sigma):
191
192
193
194
195
        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
196
197
198
199
200
201
202
203
    # ---Added properties and methods---

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

    @property
    def mmax(self):
204
        return self._lmax
csongor's avatar
csongor committed
205
206
207
208

    def _parse_lmax(self, lmax):
        lmax = np.int(lmax)
        if lmax < 1:
209
            raise ValueError("lmax must be non-zero and positive.")
csongor's avatar
csongor committed
210
211
        # exception lmax == 2 (nside == 1)
        if (lmax % 2 == 0) and (lmax > 2):
212
            self.logger.warn("Unrecommended parameter (lmax <> 2*n+1).")
csongor's avatar
csongor committed
213
        return lmax
Jait Dixit's avatar
Jait Dixit committed
214
215
216
217
218

    # ---Serialization---

    def _to_hdf5(self, hdf5_group):
        hdf5_group['lmax'] = self.lmax
219
        hdf5_group.attrs['dtype'] = self.dtype.name
Jait Dixit's avatar
Jait Dixit committed
220
221
222
        return None

    @classmethod
Theo Steininger's avatar
Theo Steininger committed
223
    def _from_hdf5(cls, hdf5_group, repository):
Jait Dixit's avatar
Jait Dixit committed
224
225
        result = cls(
            lmax=hdf5_group['lmax'][()],
226
            dtype=np.dtype(hdf5_group.attrs['dtype'])
Jait Dixit's avatar
Jait Dixit committed
227
228
            )
        return result