hp_space.py 5.74 KB
Newer Older
1
2
# NIFTy
# Copyright (C) 2017  Theo Steininger
csongor's avatar
csongor committed
3
#
4
# Author: Theo Steininger
csongor's avatar
csongor committed
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
13
14
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
csongor's avatar
csongor committed
15
16
#
# You should have received a copy of the GNU General Public License
17
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
csongor's avatar
csongor committed
18
19

import numpy as np
20

21
22
import d2o

23
from nifty.spaces.space import Space
24
from nifty.config import nifty_configuration as gc, \
csongor's avatar
csongor committed
25
26
27
28
                         dependency_injector as gdi

hp = gdi.get('healpy')

29

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

80
81
    # ---Overwritten properties and methods---

82
    def __init__(self, nside=2, dtype=None):
csongor's avatar
csongor committed
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
        """
            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']:
106
            raise ImportError("healpy not available or not loaded.")
csongor's avatar
csongor committed
107

108
        super(HPSpace, self).__init__(dtype)
csongor's avatar
csongor committed
109

110
        self._nside = self._parse_nside(nside)
csongor's avatar
csongor committed
111

112
113
114
115
116
    # ---Mandatory properties and methods---

    @property
    def harmonic(self):
        return False
csongor's avatar
csongor committed
117
118
119

    @property
    def shape(self):
120
        return (np.int(12 * self.nside ** 2),)
csongor's avatar
csongor committed
121
122

    @property
Jait Dixit's avatar
Jait Dixit committed
123
    def dim(self):
124
        return np.int(12 * self.nside ** 2)
csongor's avatar
csongor committed
125

126
127
128
    @property
    def total_volume(self):
        return 4 * np.pi
129

130
131
132
133
    def copy(self):
        return self.__class__(nside=self.nside,
                              dtype=self.dtype)

134
    def weight(self, x, power=1, axes=None, inplace=False):
Jait Dixit's avatar
Jait Dixit committed
135
        weight = ((4 * np.pi) / (12 * self.nside**2))**power
136
137
138
139
140
141
142
143

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

        return result_x
144

145
    def get_distance_array(self, distribution_strategy):
theos's avatar
theos committed
146
147
148
149
150
151
152
153
154
155
156
        """
        Calculates distance from center to all the points on the sphere

        Parameters
        ----------
        distribution_strategy: Result d2o's distribution strategy

        Returns
        -------
        dists: distributed_data_object
        """
157
        dists = d2o.arange(
158
            start=0, stop=self.shape[0],
theos's avatar
theos committed
159
160
161
            distribution_strategy=distribution_strategy
        )

162
163
164
        # translate distances to 3D unit vectors on a sphere,
        # extract the first entry (simulates the scalar product with (1,0,0))
        # and apply arccos
theos's avatar
theos committed
165
        dists = dists.apply_scalar_function(
166
167
                    lambda z: np.arccos(hp.pix2vec(self.nside, z)[0]),
                    dtype=np.float)
theos's avatar
theos committed
168
169
170

        return dists

171
    def get_fft_smoothing_kernel_function(self, sigma):
Jait Dixit's avatar
Jait Dixit committed
172
        if sigma is None:
173
            sigma = np.sqrt(2) * np.pi
Jait Dixit's avatar
Jait Dixit committed
174
175

        return lambda x: np.exp((-0.5 * x**2) / sigma**2)
theos's avatar
theos committed
176

177
178
179
180
181
182
183
184
    # ---Added properties and methods---

    @property
    def nside(self):
        return self._nside

    def _parse_nside(self, nside):
        nside = int(nside)
185
186
187
188
        if nside < 2:
            raise ValueError("nside must be greater than 2.")
        elif nside % 2 != 0:
            raise ValueError("nside must be a multiple of 2.")
189
        return nside
190
191
192
193

    # ---Serialization---

    def _to_hdf5(self, hdf5_group):
Jait Dixit's avatar
Jait Dixit committed
194
        hdf5_group['nside'] = self.nside
195
        hdf5_group.attrs['dtype'] = self.dtype.name
196
197
198
        return None

    @classmethod
Theo Steininger's avatar
Theo Steininger committed
199
    def _from_hdf5(cls, hdf5_group, repository):
200
        result = cls(
Jait Dixit's avatar
Jait Dixit committed
201
            nside=hdf5_group['nside'][()],
202
            dtype=np.dtype(hdf5_group.attrs['dtype'])
Jait Dixit's avatar
Jait Dixit committed
203
            )
204
        return result