gl_space.py 6.22 KB
Newer Older
csongor's avatar
csongor committed
1
2
from __future__ import division

Jait Dixit's avatar
Jait Dixit committed
3
import itertools
csongor's avatar
csongor committed
4
5
import numpy as np

6
from d2o import arange, STRATEGIES as DISTRIBUTION_STRATEGIES
csongor's avatar
csongor committed
7

8
from nifty.spaces.space import Space
9
10
from nifty.config import about, nifty_configuration as gc,\
                         dependency_injector as gdi
11
import nifty.nifty_utilities as utilities
csongor's avatar
csongor committed
12
13
14
15
16

gl = gdi.get('libsharp_wrapper_gl')

GL_DISTRIBUTION_STRATEGIES = DISTRIBUTION_STRATEGIES['global']

17
18

class GLSpace(Space):
csongor's avatar
csongor committed
19
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
    """
        ..                 __
        ..               /  /
        ..     ____ __  /  /
        ..   /   _   / /  /
        ..  /  /_/  / /  /_
        ..  \___   /  \___/  space class
        .. /______/

        NIFTY subclass for Gauss-Legendre pixelizations [#]_ of the two-sphere.

        Parameters
        ----------
        nlat : int
            Number of latitudinal bins, or rings.
        nlon : int, *optional*
            Number of longitudinal bins (default: ``2*nlat - 1``).
        dtype : numpy.dtype, *optional*
            Data type of the field values (default: numpy.float64).

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

        Notes
        -----
        Only real-valued fields on the two-sphere are supported, i.e.
        `dtype` has to be either numpy.float64 or numpy.float32.

        References
        ----------
        .. [#] M. Reinecke and D. Sverre Seljebotn, 2013, "Libsharp - spherical
               harmonic transforms revisited";
               `arXiv:1303.4945 <http://www.arxiv.org/abs/1303.4945>`_
        .. [#] 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.

        Attributes
        ----------
        para : numpy.ndarray
            One-dimensional array containing the two numbers `nlat` and `nlon`.
        dtype : numpy.dtype
            Data type of the field values.
        discrete : bool
            Whether or not the underlying space is discrete, always ``False``
            for spherical spaces.
        vol : numpy.ndarray
            An array containing the pixel sizes.
    """

71
72
    # ---Overwritten properties and methods---

73
    def __init__(self, nlat=2, nlon=None, dtype=np.dtype('float')):
csongor's avatar
csongor committed
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
        """
            Sets the attributes for a gl_space class instance.

            Parameters
            ----------
            nlat : int
                Number of latitudinal bins, or rings.
            nlon : int, *optional*
                Number of longitudinal bins (default: ``2*nlat - 1``).
            dtype : numpy.dtype, *optional*
                Data type of the field values (default: numpy.float64).

            Returns
            -------
            None

            Raises
            ------
            ImportError
                If the libsharp_wrapper_gl module is not available.
            ValueError
                If input `nlat` is invaild.

        """
        # check imports
        if not gc['use_libsharp']:
            raise ImportError(about._errors.cstring(
101
102
103
                "ERROR: libsharp_wrapper_gl not available or not loaded."))

        super(GLSpace, self).__init__(dtype)
csongor's avatar
csongor committed
104

105
106
        self._nlat = self._parse_nlat(nlat)
        self._nlon = self._parse_nlon(nlon)
csongor's avatar
csongor committed
107

108
    # ---Mandatory properties and methods---
csongor's avatar
csongor committed
109

110
111
112
    @property
    def harmonic(self):
        return False
csongor's avatar
csongor committed
113
114
115

    @property
    def shape(self):
116
        return (np.int((self.nlat * self.nlon)),)
csongor's avatar
csongor committed
117

118
    @property
119
    def dim(self):
120
        return np.int((self.nlat * self.nlon))
121
122
123
124

    @property
    def total_volume(self):
        return 4 * np.pi
125

126
127
128
129
130
    def copy(self):
        return self.__class__(nlat=self.nlat,
                              nlon=self.nlon,
                              dtype=self.dtype)

Jait Dixit's avatar
Jait Dixit committed
131
    def weight(self, x, power=1, axes=None, inplace=False):
132
        axes = utilities.cast_axis_to_tuple(axes, length=1)
133

134
135
        nlon = self.nlon
        nlat = self.nlat
136
137

        weight = np.array(list(itertools.chain.from_iterable(
138
139
            itertools.repeat(x ** power, nlon)
            for x in gl.vol(nlat))))
Jait Dixit's avatar
Jait Dixit committed
140
141
142

        if axes is not None:
            # reshape the weight array to match the input shape
143
            new_shape = np.ones(len(x.shape), dtype=np.int)
Jait Dixit's avatar
Jait Dixit committed
144
145
146
147
148
149
150
            for index in range(len(axes)):
                new_shape[index] = len(weight)
            weight = weight.reshape(new_shape)

        if inplace:
            x *= weight
            result_x = x
csongor's avatar
csongor committed
151
        else:
Jait Dixit's avatar
Jait Dixit committed
152
            result_x = x * weight
csongor's avatar
csongor committed
153

Jait Dixit's avatar
Jait Dixit committed
154
        return result_x
155

156
157
    def distance_array(self, distribution_strategy):
        dists = arange(
158
            start=0, stop=self.shape[0],
159
160
161
            distribution_strategy=distribution_strategy
        )

162
        dists = dists.apply_scalar_function(
163
164
            lambda x: self._distance_array_helper(divmod(int(x), self.nlon)),
            dtype=np.float
165
        )
166
167
168

        return dists

theos's avatar
theos committed
169
170
171
172
    def _distance_array_helper(self, qr_tuple):
        numerator = np.sqrt(np.sin(qr_tuple[1])**2 +
                            (np.sin(qr_tuple[0]) * np.cos(qr_tuple[1]))**2)
        denominator = np.cos(qr_tuple[0]) * np.cos(qr_tuple[1])
173

theos's avatar
theos committed
174
        return np.arctan(numerator / denominator)
175

theos's avatar
theos committed
176
    def get_smoothing_kernel_function(self, sigma):
Jait Dixit's avatar
Jait Dixit committed
177
178
179
180
        if sigma is None:
            sigma = np.sqrt(2) * np.pi / self.nlat

        return lambda x: np.exp((-0.5 * x**2) / sigma**2)
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
    # ---Added properties and methods---

    @property
    def nlat(self):
        return self._nlat

    @property
    def nlon(self):
        return self._nlon

    def _parse_nlat(self, nlat):
        nlat = int(nlat)
        if nlat < 2:
            raise ValueError(about._errors.cstring(
                "ERROR: nlat must be a positive number."))
        elif nlat % 2 != 0:
            raise ValueError(about._errors.cstring(
                "ERROR: nlat must be a multiple of 2."))
        return nlat

    def _parse_nlon(self, nlon):
        if nlon is None:
            nlon = 2 * self.nlat - 1
        else:
            nlon = int(nlon)
            if nlon != 2 * self.nlat - 1:
                about.warnings.cprint(
                    "WARNING: nlon was set to an unrecommended value: "
                    "nlon <> 2*nlat-1.")
        return nlon