nifty_lm.py 82.7 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 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/>.
Marco Selig's avatar
Marco Selig committed
21
22
23
24
25
26
27
28
29
30
31
32
33
34

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

    NIFTY submodule for grids on the two-sphere.

"""
from __future__ import division
35

Marco Selig's avatar
Marco Selig committed
36
37
38
39
40
import os
import numpy as np
import pylab as pl
from matplotlib.colors import LogNorm as ln
from matplotlib.ticker import LogFormatter as lf
41
42
43
44

from nifty.nifty_core import space,\
                             point_space,\
                             field
45
from nifty.keepers import about,\
46
47
                    global_configuration as gc,\
                    global_dependency_injector as gdi
Ultimanet's avatar
Ultimanet committed
48
from nifty.nifty_paradict import lm_space_paradict,\
49
50
51
52
                                 gl_space_paradict,\
                                 hp_space_paradict
from nifty.nifty_power_indices import lm_power_indices

csongor's avatar
csongor committed
53
from nifty.nifty_mpi_data import distributed_data_object
54
from nifty.nifty_mpi_data import STRATEGIES as DISTRIBUTION_STRATEGIES
csongor's avatar
csongor committed
55

Ultimanet's avatar
Ultimanet committed
56
from nifty.nifty_random import random
57

Ultima's avatar
Ultima committed
58
59
gl = gdi.get('libsharp_wrapper_gl')
hp = gdi.get('healpy')
60

61
62
63
LM_DISTRIBUTION_STRATEGIES = DISTRIBUTION_STRATEGIES['global']
GL_DISTRIBUTION_STRATEGIES = DISTRIBUTION_STRATEGIES['global']
HP_DISTRIBUTION_STRATEGIES = DISTRIBUTION_STRATEGIES['global']
Marco Selig's avatar
Marco Selig committed
64
65


66
class lm_space(point_space):
Marco Selig's avatar
Marco Selig committed
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
    """
        ..       __
        ..     /  /
        ..    /  /    __ ____ ___
        ..   /  /   /   _    _   |
        ..  /  /_  /  / /  / /  /
        ..  \___/ /__/ /__/ /__/  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`).
86
        dtype : numpy.dtype, *optional*
Marco Selig's avatar
Marco Selig committed
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
            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`.
116
        dtype : numpy.dtype
Marco Selig's avatar
Marco Selig committed
117
118
119
120
121
122
123
            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.
    """
124
125

    def __init__(self, lmax, mmax=None, dtype=np.dtype('complex128'),
csongor's avatar
csongor committed
126
                 datamodel='not', comm=gc['default_comm']):
Marco Selig's avatar
Marco Selig committed
127
128
129
130
131
132
133
134
135
136
137
        """
            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`).
138
            dtype : numpy.dtype, *optional*
Marco Selig's avatar
Marco Selig committed
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
                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.

        """
154

155
        # check imports
Ultima's avatar
Ultima committed
156
        if not gc['use_libsharp'] and not gc['use_healpy']:
157
            raise ImportError(about._errors.cstring(
Ultima's avatar
Ultima committed
158
                "ERROR: neither libsharp_wrapper_gl nor healpy activated."))
159

Ultima's avatar
Ultima committed
160
161
        self._cache_dict = {'check_codomain': {}}

162
        self.paradict = lm_space_paradict(lmax=lmax, mmax=mmax)
Marco Selig's avatar
Marco Selig committed
163

164
165
166
        # check data type
        dtype = np.dtype(dtype)
        if dtype not in [np.dtype('complex64'), np.dtype('complex128')]:
theos's avatar
theos committed
167
            about.warnings.cprint("WARNING: data type set to complex128.")
168
169
            dtype = np.dtype('complex128')
        self.dtype = dtype
170

171
        # set datamodel
csongor's avatar
csongor committed
172
        if datamodel not in ['not']:
theos's avatar
theos committed
173
174
175
176
177
178
            about.warnings.cprint(
                "WARNING: %s is not a recommended datamodel for lm_space."
                % datamodel)
        if datamodel not in LM_DISTRIBUTION_STRATEGIES:
            raise ValueError(about._errors.cstring(
                "ERROR: %s is not a valid datamodel" % datamodel))
179
        self.datamodel = datamodel
180

Marco Selig's avatar
Marco Selig committed
181
        self.discrete = True
182
        self.harmonic = True
183
        self.distances = (np.float(1),)
184
        self.comm = self._parse_comm(comm)
185
186
187
188
189
190
191

        self.power_indices = lm_power_indices(
                    lmax=self.paradict['lmax'],
                    dim=self.get_dim(),
                    comm=self.comm,
                    datamodel=self.datamodel,
                    allowed_distribution_strategies=LM_DISTRIBUTION_STRATEGIES)
Marco Selig's avatar
Marco Selig committed
192

193
194
    @property
    def para(self):
195
        temp = np.array([self.paradict['lmax'],
196
197
                         self.paradict['mmax']], dtype=int)
        return temp
198

199
200
201
202
203
    @para.setter
    def para(self, x):
        self.paradict['lmax'] = x[0]
        self.paradict['mmax'] = x[1]

Ultima's avatar
Ultima committed
204
205
206
    def __hash__(self):
        result_hash = 0
        for (key, item) in vars(self).items():
Ultima's avatar
Ultima committed
207
            if key in ['_cache_dict', 'power_indices']:
Ultima's avatar
Ultima committed
208
209
210
211
                continue
            result_hash ^= item.__hash__() * hash(key)
        return result_hash

Ultima's avatar
Ultima committed
212
213
214
215
216
217
    def _identifier(self):
        # Extract the identifying parts from the vars(self) dict.
        temp = [(ii[0],
                 ((lambda x: tuple(x) if
                  isinstance(x, np.ndarray) else x)(ii[1])))
                for ii in vars(self).iteritems()
Ultima's avatar
Ultima committed
218
                if ii[0] not in ['_cache_dict', 'power_indices', 'comm']]
Ultima's avatar
Ultima committed
219
220
221
222
        temp.append(('comm', self.comm.__hash__()))
        # Return the sorted identifiers as a tuple.
        return tuple(sorted(temp))

223
    def copy(self):
224
225
226
227
        return lm_space(lmax=self.paradict['lmax'],
                        mmax=self.paradict['mmax'],
                        dtype=self.dtype)

228
    def get_shape(self):
Ultima's avatar
Ultima committed
229
        lmax = self.paradict['lmax']
Ultima's avatar
Ultima committed
230
231
        mmax = self.paradict['mmax']
        return (np.int((mmax + 1) * (lmax + 1) - ((mmax + 1) * mmax) // 2),)
232
233

    def get_dof(self, split=False):
Marco Selig's avatar
Marco Selig committed
234
235
236
237
238
239
240
241
242
243
244
245
246
247
        """
            Computes the number of degrees of freedom of the space, taking into
            account symmetry constraints and complex-valuedness.

            Returns
            -------
            dof : int
                Number of degrees of freedom of the space.

            Notes
            -----
            The number of degrees of freedom is reduced due to the hermitian
            symmetry, which is assumed for the spherical harmonics components.
        """
248
249
        # dof = 2*dim-(lmax+1) = (lmax+1)*(2*mmax+1)*(mmax+1)*mmax
        lmax = self.paradict['lmax']
Ultima's avatar
Ultima committed
250
        mmax = self.paradict['mmax']
251
252
253
254
255
        dof = np.int((lmax + 1) * (2 * mmax + 1) - (mmax + 1) * mmax)
        if split:
            return (dof, )
        else:
            return dof
Marco Selig's avatar
Marco Selig committed
256

257
    def get_meta_volume(self, split=False):
Marco Selig's avatar
Marco Selig committed
258
        """
259
            Calculates the meta volumes.
Marco Selig's avatar
Marco Selig committed
260

261
262
263
264
            The meta volumes are the volumes associated with each component of
            a field, taking into account field components that are not
            explicitly included in the array of field values but are determined
            by symmetry conditions.
Marco Selig's avatar
Marco Selig committed
265
266
267

            Parameters
            ----------
268
269
270
            total : bool, *optional*
                Whether to return the total meta volume of the space or the
                individual ones of each field component (default: False).
Marco Selig's avatar
Marco Selig committed
271
272
273

            Returns
            -------
274
275
            mol : {numpy.ndarray, float}
                Meta volume of the field components or the complete space.
Marco Selig's avatar
Marco Selig committed
276

277
278
279
280
281
            Notes
            -----
            The spherical harmonics components with :math:`m=0` have meta
            volume 1, the ones with :math:`m>0` have meta volume 2, sinnce they
            each determine another component with negative :math:`m`.
Marco Selig's avatar
Marco Selig committed
282
        """
283
284
285
286
287
288
        if not split:
            return np.float(self.get_dof())
        else:
            mol = self.cast(1, dtype=np.float)
            mol[self.paradict['lmax'] + 1:] = 2  # redundant: (l,m) and (l,-m)
            return mol
Marco Selig's avatar
Marco Selig committed
289

theos's avatar
theos committed
290
291
292
293
    def _cast_to_d2o(self, x, dtype=None, **kwargs):
        casted_x = super(lm_space, self)._cast_to_d2o(x=x,
                                                      dtype=dtype,
                                                      **kwargs)
294
295
        lmax = self.paradict['lmax']
        complexity_mask = casted_x[:lmax+1].iscomplex()
theos's avatar
theos committed
296
        if complexity_mask.any():
Ultima's avatar
Ultima committed
297
            about.warnings.cprint("WARNING: Taking the absolute values for " +
298
                                  "all complex entries where lmax==0")
299
            casted_x[:lmax+1] = abs(casted_x[:lmax+1])
300
301
        return casted_x

302
    # TODO: Extend to binning/log
303
304
305
306
307
    def enforce_power(self, spec, size=None, kindex=None):
        if kindex is None:
            kindex_size = self.paradict['lmax'] + 1
            kindex = np.arange(kindex_size,
                               dtype=np.array(self.distances).dtype)
308
309
310
311
        return self._enforce_power_helper(spec=spec,
                                          size=size,
                                          kindex=kindex)

Ultima's avatar
Ultima committed
312
    def _check_codomain(self, codomain):
Marco Selig's avatar
Marco Selig committed
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
        """
            Checks whether a given codomain is compatible to the
            :py:class:`lm_space` or not.

            Parameters
            ----------
            codomain : nifty.space
                Space to be checked for compatibility.

            Returns
            -------
            check : bool
                Whether or not the given codomain is compatible to the space.

            Notes
            -----
            Compatible codomains are instances of :py:class:`lm_space`,
            :py:class:`gl_space`, and :py:class:`hp_space`.
        """
332
333
        if codomain is None:
            return False
334

335
336
337
        if not isinstance(codomain, space):
            raise TypeError(about._errors.cstring(
                "ERROR: The given codomain must be a nifty lm_space."))
Marco Selig's avatar
Marco Selig committed
338

339
340
341
        if self.comm is not codomain.comm:
            return False

342
343
344
        if self.datamodel is not codomain.datamodel:
            return False

345
346
347
        elif isinstance(codomain, gl_space):
            # lmax==mmax
            # nlat==lmax+1
348
            # nlon==2*lmax+1
349
350
351
            if ((self.paradict['lmax'] == self.paradict['mmax']) and
                    (codomain.paradict['nlat'] == self.paradict['lmax']+1) and
                    (codomain.paradict['nlon'] == 2*self.paradict['lmax']+1)):
Marco Selig's avatar
Marco Selig committed
352
353
                return True

354
355
356
357
358
        elif isinstance(codomain, hp_space):
            # lmax==mmax
            # 3*nside-1==lmax
            if ((self.paradict['lmax'] == self.paradict['mmax']) and
                    (3*codomain.paradict['nside']-1 == self.paradict['lmax'])):
Marco Selig's avatar
Marco Selig committed
359
360
361
362
                return True

        return False

363
    def get_codomain(self, coname=None, **kwargs):
Marco Selig's avatar
Marco Selig committed
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
        """
            Generates a compatible codomain to which transformations are
            reasonable, i.e.\  a pixelization of the two-sphere.

            Parameters
            ----------
            coname : string, *optional*
                String specifying a desired codomain (default: None).

            Returns
            -------
            codomain : nifty.space
                A compatible codomain.

            Notes
            -----
            Possible arguments for `coname` are ``'gl'`` in which case a Gauss-
            Legendre pixelization [#]_ of the sphere is generated, and ``'hp'``
            in which case a HEALPix pixelization [#]_ is generated.

            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.
389
390
            .. [#] M. Reinecke and D. Sverre Seljebotn, 2013,
                   "Libsharp - spherical
Marco Selig's avatar
Marco Selig committed
391
392
393
394
                   harmonic transforms revisited";
                   `arXiv:1303.4945 <http://www.arxiv.org/abs/1303.4945>`_

        """
395
396
397
398
399
        if coname == 'gl' or (coname is None and gc['lm2gl']):
            if self.dtype == np.dtype('complex64'):
                new_dtype = np.float32
            elif self.dtype == np.dtype('complex128'):
                new_dtype = np.float64
Marco Selig's avatar
Marco Selig committed
400
            else:
401
402
403
                raise NotImplementedError
            nlat = self.paradict['lmax'] + 1
            nlon = self.paradict['lmax'] * 2 + 1
404
405
406
407
            return gl_space(nlat=nlat, nlon=nlon, dtype=new_dtype,
                            datamodel=self.datamodel,
                            comm=self.comm)

408
409
        elif coname == 'hp' or (coname is None and not gc['lm2gl']):
            nside = (self.paradict['lmax']+1) // 3
410
411
412
413
            return hp_space(nside=nside,
                            datamodel=self.datamodel,
                            comm=self.comm)

Marco Selig's avatar
Marco Selig committed
414
        else:
415
            raise ValueError(about._errors.cstring(
416
417
418
419
420
421
422
423
424
425
426
427
                "ERROR: unsupported or incompatible codomain '"+coname+"'."))

    def get_random_values(self, **kwargs):
        """
            Generates random field values according to the specifications given
            by the parameters, taking into account complex-valuedness and
            hermitian symmetry.

            Returns
            -------
            x : numpy.ndarray
                Valid field values.
Marco Selig's avatar
Marco Selig committed
428

429
430
431
432
433
434
            Other parameters
            ----------------
            random : string, *optional*
                Specifies the probability distribution from which the random
                numbers are to be drawn.
                Supported distributions are:
Marco Selig's avatar
Marco Selig committed
435

436
437
438
439
440
441
                - "pm1" (uniform distribution over {+1,-1} or {+1,+i,-1,-i}
                - "gau" (normal distribution with zero-mean and a given
                    standard
                    deviation or variance)
                - "syn" (synthesizes from a given power spectrum)
                - "uni" (uniform distribution over [vmin,vmax[)
Marco Selig's avatar
Marco Selig committed
442

443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
                (default: None).
            dev : float, *optional*
                Standard deviation (default: 1).
            var : float, *optional*
                Variance, overriding `dev` if both are specified
                (default: 1).
            spec : {scalar, list, numpy.array, nifty.field, function},
                *optional*
                Power spectrum (default: 1).
            vmin : float, *optional*
                Lower limit for a uniform distribution (default: 0).
            vmax : float, *optional*
                Upper limit for a uniform distribution (default: 1).
        """
        arg = random.parse_arguments(self, **kwargs)

459
460
461
462
463
464
465
466
467
468
469
#        if arg is None:
#            x = 0
#
#        elif arg['random'] == "pm1":
#            x = random.pm1(dtype=self.dtype, shape=self.get_shape())
#
#        elif arg['random'] == "gau":
#            x = random.gau(dtype=self.dtype,
#                           shape=self.get_shape(),
#                           mean=arg['mean'],
#                           std=arg['std'])
470

471
        if arg['random'] == "syn":
472
473
474
            lmax = self.paradict['lmax']
            mmax = self.paradict['mmax']
            if self.dtype == np.dtype('complex64'):
Ultima's avatar
Ultima committed
475
                if gc['use_libsharp']:
476
                    sample = gl.synalm_f(arg['spec'], lmax=lmax, mmax=mmax)
477
                else:
478
479
480
481
                    sample = hp.synalm(
                                arg['spec'].astype(np.complex128),
                                lmax=lmax, mmax=mmax).astype(np.complex64,
                                                             copy=False)
482
            else:
Ultima's avatar
Ultima committed
483
                if gc['use_healpy']:
484
                    sample = hp.synalm(arg['spec'], lmax=lmax, mmax=mmax)
485
                else:
486
                    sample = gl.synalm(arg['spec'], lmax=lmax, mmax=mmax)
487
488

        else:
489
            sample = super(lm_space, self).get_random_values(**arg)
Marco Selig's avatar
Marco Selig committed
490

491
492
493
494
495
496
497
498
499
500
501
#        elif arg['random'] == "uni":
#            x = random.uni(dtype=self.dtype,
#                           shape=self.get_shape(),
#                           vmin=arg['vmin'],
#                           vmax=arg['vmax'])
#
#        else:
#            raise KeyError(about._errors.cstring(
#                "ERROR: unsupported random key '" + str(arg['random']) + "'."))
        sample = self.cast(sample)
        return sample
502

503
    def calc_dot(self, x, y):
Marco Selig's avatar
Marco Selig committed
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
        """
            Computes the discrete inner product of two given arrays of field
            values.

            Parameters
            ----------
            x : numpy.ndarray
                First array
            y : numpy.ndarray
                Second array

            Returns
            -------
            dot : scalar
                Inner product of the two arrays.
        """
520
521
522
523
        x = self.cast(x)
        y = self.cast(y)

        lmax = self.paradict['lmax']
524
525
526
527
528
529
530
531
532

        x_low = x[:lmax + 1]
        x_high = x[lmax + 1:]
        y_low = y[:lmax + 1]
        y_high = y[lmax + 1:]

        dot = (x_low.real * y_low.real).sum()
        dot += 2 * (x_high.real * y_high.real).sum()
        dot += 2 * (x_high.imag * y_high.imag).sum()
533
534
        return dot

535
    def calc_transform(self, x, codomain=None, **kwargs):
Marco Selig's avatar
Marco Selig committed
536
537
538
539
540
541
542
543
        """
            Computes the transform of a given array of field values.

            Parameters
            ----------
            x : numpy.ndarray
                Array to be transformed.
            codomain : nifty.space, *optional*
544
                codomain space to which the transformation shall map
Marco Selig's avatar
Marco Selig committed
545
546
547
548
549
550
551
                (default: self).

            Returns
            -------
            Tx : numpy.ndarray
                Transformed array
        """
552
        x = self.cast(x)
Marco Selig's avatar
Marco Selig committed
553

554
555
        if codomain is None:
            codomain = self.get_codomain()
Marco Selig's avatar
Marco Selig committed
556

557
558
559
560
        # Check if the given codomain is suitable for the transformation
        if not self.check_codomain(codomain):
            raise ValueError(about._errors.cstring(
                "ERROR: unsupported codomain."))
Marco Selig's avatar
Marco Selig committed
561

562
563
564
565
566
567
568
        if self.datamodel != 'not':
            about.warnings.cprint(
                "WARNING: Field data is consolidated to all nodes for "
                "external alm2map method!")

        np_x = x.get_full_data()

569
570
571
572
573
        if isinstance(codomain, gl_space):
            nlat = codomain.paradict['nlat']
            nlon = codomain.paradict['nlon']
            lmax = self.paradict['lmax']
            mmax = self.paradict['mmax']
Marco Selig's avatar
Marco Selig committed
574

575
            # transform
576
            if self.dtype == np.dtype('complex64'):
577
578
                np_Tx = gl.alm2map_f(np_x, nlat=nlat, nlon=nlon,
                                     lmax=lmax, mmax=mmax, cl=False)
Marco Selig's avatar
Marco Selig committed
579
            else:
580
581
582
                np_Tx = gl.alm2map(np_x, nlat=nlat, nlon=nlon,
                                   lmax=lmax, mmax=mmax, cl=False)
            Tx = codomain.cast(np_Tx)
Marco Selig's avatar
Marco Selig committed
583

584
585
586
587
588
        elif isinstance(codomain, hp_space):
            nside = codomain.paradict['nside']
            lmax = self.paradict['lmax']
            mmax = self.paradict['mmax']

589
            # transform
590
591
592
593
594
            np_x = np_x.astype(np.complex128, copy=False)
            np_Tx = hp.alm2map(np_x, nside, lmax=lmax,
                               mmax=mmax, pixwin=False, fwhm=0.0, sigma=None,
                               pol=True, inplace=False)
            Tx = codomain.cast(np_Tx)
Marco Selig's avatar
Marco Selig committed
595
596

        else:
597
598
            raise ValueError(about._errors.cstring(
                "ERROR: unsupported transformation."))
Marco Selig's avatar
Marco Selig committed
599

600
601
602
603
604
        # re-weight if discrete
        if codomain.discrete:
            Tx = codomain.calc_weight(Tx, power=0.5)

        return codomain.cast(Tx)
Marco Selig's avatar
Marco Selig committed
605

606
    def calc_smooth(self, x, sigma=0, **kwargs):
Marco Selig's avatar
Marco Selig committed
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
        """
            Smoothes an array of field values by convolution with a Gaussian
            kernel in position space.

            Parameters
            ----------
            x : numpy.ndarray
                Array of field values to be smoothed.
            sigma : float, *optional*
                Standard deviation of the Gaussian kernel, specified in units
                of length in position space; for testing: a sigma of -1 will be
                reset to a reasonable value (default: 0).

            Returns
            -------
            Gx : numpy.ndarray
                Smoothed array.
        """
625
        x = self.cast(x)
626
        # check sigma
627
        if sigma == 0:
Ultima's avatar
Ultima committed
628
            return self.unary_operation(x, op='copy')
629
        elif sigma == -1:
Marco Selig's avatar
Marco Selig committed
630
            about.infos.cprint("INFO: invalid sigma reset.")
631
632
            sigma = np.sqrt(2) * np.pi / (self.paradict['lmax'] + 1)
        elif sigma < 0:
Marco Selig's avatar
Marco Selig committed
633
            raise ValueError(about._errors.cstring("ERROR: invalid sigma."))
634

theos's avatar
theos committed
635
636
637
638
639
640
641
        if self.datamodel != 'not':
            about.warnings.cprint(
                "WARNING: Field data is consolidated to all nodes for "
                "external smoothalm method!")

        np_x = x.get_full_data()

Ultima's avatar
Ultima committed
642
        if gc['use_healpy']:
theos's avatar
theos committed
643
644
645
646
647
648
649
            np_smoothed_x = hp.smoothalm(np_x,
                                         fwhm=0.0,
                                         sigma=sigma,
                                         pol=True,
                                         mmax=self.paradict['mmax'],
                                         verbose=False,
                                         inplace=False)
Marco Selig's avatar
Marco Selig committed
650
        else:
theos's avatar
theos committed
651
652
653
654
655
656
657
            np_smoothed_x = gl.smoothalm(np_x,
                                         lmax=self.paradict['lmax'],
                                         mmax=self.paradict['mmax'],
                                         fwhm=0.0,
                                         sigma=sigma,
                                         overwrite=False)
        return self.cast(np_smoothed_x)
Marco Selig's avatar
Marco Selig committed
658

659
    def calc_power(self, x, **kwargs):
Marco Selig's avatar
Marco Selig committed
660
661
662
663
664
665
666
667
668
669
670
671
672
673
        """
            Computes the power of an array of field values.

            Parameters
            ----------
            x : numpy.ndarray
                Array containing the field values of which the power is to be
                calculated.

            Returns
            -------
            spec : numpy.ndarray
                Power contained in the input array.
        """
674
675
676
677
        x = self.cast(x)
        lmax = self.paradict['lmax']
        mmax = self.paradict['mmax']

theos's avatar
theos committed
678
679
680
681
682
683
684
        if self.datamodel != 'not':
            about.warnings.cprint(
                "WARNING: Field data is consolidated to all nodes for "
                "external anaalm/alm2cl method!")

        np_x = x.get_full_data()

685
        # power spectrum
686
        if self.dtype == np.dtype('complex64'):
Ultima's avatar
Ultima committed
687
            if gc['use_libsharp']:
theos's avatar
theos committed
688
                result = gl.anaalm_f(np_x, lmax=lmax, mmax=mmax)
Marco Selig's avatar
Marco Selig committed
689
            else:
theos's avatar
theos committed
690
691
692
693
694
695
696
                np_x = np_x.astype(np.complex128, copy=False)
                result = hp.alm2cl(np_x,
                                   alms2=None,
                                   lmax=lmax,
                                   mmax=mmax,
                                   lmax_out=lmax,
                                   nspec=None)
Marco Selig's avatar
Marco Selig committed
697
        else:
Ultima's avatar
Ultima committed
698
            if gc['use_healpy']:
theos's avatar
theos committed
699
700
701
702
703
704
                result = hp.alm2cl(np_x,
                                   alms2=None,
                                   lmax=lmax,
                                   mmax=mmax,
                                   lmax_out=lmax,
                                   nspec=None)
Marco Selig's avatar
Marco Selig committed
705
            else:
theos's avatar
theos committed
706
707
708
                result = gl.anaalm(np_x,
                                   lmax=lmax,
                                   mmax=mmax)
theos's avatar
theos committed
709
710
711
712
713
714
715
716
717

        if self.dtype == np.dtype('complex64'):
            result = result.astype(np.float32, copy=False)
        elif self.dtype == np.dtype('complex128'):
            result = result.astype(np.float64, copy=False)
        else:
            raise NotImplementedError(about._errors.cstring(
                "ERROR: dtype %s not known to calc_power method." %
                str(self.dtype)))
Marco Selig's avatar
Marco Selig committed
718

719
720
721
    def get_plot(self, x, title="", vmin=None, vmax=None, power=True,
                 norm=None, cmap=None, cbar=True, other=None, legend=False,
                 mono=True, **kwargs):
Marco Selig's avatar
Marco Selig committed
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
        """
            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: True).
            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).

        """
theos's avatar
theos committed
766
767
768
769
770
        try:
            x = x.get_full_data()
        except AttributeError:
            pass

771
        if(not pl.isinteractive())and(not bool(kwargs.get("save", False))):
Marco Selig's avatar
Marco Selig committed
772
773
774
775
776
            about.warnings.cprint("WARNING: interactive mode off.")

        if(power):
            x = self.calc_power(x)

777
778
779
            fig = pl.figure(num=None, figsize=(6.4, 4.8), dpi=None, facecolor="none",
                            edgecolor="none", frameon=False, FigureClass=pl.Figure)
            ax0 = fig.add_axes([0.12, 0.12, 0.82, 0.76])
Marco Selig's avatar
Marco Selig committed
780

781
            xaxes = np.arange(self.para[0] + 1, dtype=np.int)
Marco Selig's avatar
Marco Selig committed
782
            if(vmin is None):
783
784
                vmin = np.min(x[:mono].tolist(
                ) + (xaxes * (2 * xaxes + 1) * x)[1:].tolist(), axis=None, out=None)
Marco Selig's avatar
Marco Selig committed
785
            if(vmax is None):
786
787
788
789
                vmax = np.max(x[:mono].tolist(
                ) + (xaxes * (2 * xaxes + 1) * x)[1:].tolist(), axis=None, out=None)
            ax0.loglog(xaxes[1:], (xaxes * (2 * xaxes + 1) * x)[1:], color=[0.0,
                                                                            0.5, 0.0], label="graph 0", linestyle='-', linewidth=2.0, zorder=1)
Marco Selig's avatar
Marco Selig committed
790
            if(mono):
791
792
                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)
Marco Selig's avatar
Marco Selig committed
793
794

            if(other is not None):
795
                if(isinstance(other, tuple)):
Marco Selig's avatar
Marco Selig committed
796
797
                    other = list(other)
                    for ii in xrange(len(other)):
798
                        if(isinstance(other[ii], field)):
Marco Selig's avatar
Marco Selig committed
799
800
801
                            other[ii] = other[ii].power(**kwargs)
                        else:
                            other[ii] = self.enforce_power(other[ii])
802
                elif(isinstance(other, field)):
Marco Selig's avatar
Marco Selig committed
803
804
805
                    other = [other.power(**kwargs)]
                else:
                    other = [self.enforce_power(other)]
806
                imax = max(1, len(other) - 1)
Marco Selig's avatar
Marco Selig committed
807
                for ii in xrange(len(other)):
808
809
                    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 - (2 * (ii - imax) / imax)**2)], label="graph " + str(ii + 1), linestyle='-', linewidth=1.0, zorder=-ii)
Marco Selig's avatar
Marco Selig committed
810
                    if(mono):
811
812
                        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 - (2 * (ii - imax) / imax)**2)], marker='o', cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, verts=None, zorder=-ii)
Marco Selig's avatar
Marco Selig committed
813
814
815
                if(legend):
                    ax0.legend()

816
            ax0.set_xlim(xaxes[1], xaxes[-1])
Marco Selig's avatar
Marco Selig committed
817
            ax0.set_xlabel(r"$\ell$")
818
            ax0.set_ylim(vmin, vmax)
Marco Selig's avatar
Marco Selig committed
819
820
821
822
823
824
825
            ax0.set_ylabel(r"$\ell(2\ell+1) C_\ell$")
            ax0.set_title(title)

        else:
            if(np.iscomplexobj(x)):
                if(title):
                    title += " "
826
827
828
829
830
831
                if(bool(kwargs.get("save", False))):
                    save_ = os.path.splitext(
                        os.path.basename(str(kwargs.get("save"))))
                    kwargs.update(save=save_[0] + "_absolute" + save_[1])
                self.get_plot(np.absolute(x), title=title + "(absolute)", vmin=vmin, vmax=vmax,
                              power=False, norm=norm, cmap=cmap, cbar=cbar, other=None, legend=False, **kwargs)
Marco Selig's avatar
Marco Selig committed
832
833
834
835
#                self.get_plot(np.real(x),title=title+"(real part)",vmin=vmin,vmax=vmax,power=False,norm=norm,cmap=cmap,cbar=cbar,other=None,legend=False,**kwargs)
#                self.get_plot(np.imag(x),title=title+"(imaginary part)",vmin=vmin,vmax=vmax,power=False,norm=norm,cmap=cmap,cbar=cbar,other=None,legend=False,**kwargs)
                if(cmap is None):
                    cmap = pl.cm.hsv_r
836
837
838
839
840
                if(bool(kwargs.get("save", False))):
                    kwargs.update(save=save_[0] + "_phase" + save_[1])
                self.get_plot(np.angle(x, deg=False), title=title + "(phase)", vmin=-3.1416, vmax=3.1416, power=False,
                              norm=None, cmap=cmap, cbar=cbar, other=None, legend=False, **kwargs)  # values in [-pi,pi]
                return None  # leave method
Marco Selig's avatar
Marco Selig committed
841
842
            else:
                if(vmin is None):
843
                    vmin = np.min(x, axis=None, out=None)
Marco Selig's avatar
Marco Selig committed
844
                if(vmax is None):
845
846
847
848
849
850
851
852
853
854
                    vmax = np.max(x, axis=None, out=None)
                if(norm == "log")and(vmin <= 0):
                    raise ValueError(about._errors.cstring(
                        "ERROR: nonpositive value(s)."))

                # not a number
                xmesh = np.nan * \
                    np.empty(self.para[::-1] + 1, dtype=np.float16, order='C')
                xmesh[4, 1] = None
                xmesh[1, 4] = None
Marco Selig's avatar
Marco Selig committed
855
                lm = 0
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
                for mm in xrange(self.para[1] + 1):
                    xmesh[mm][mm:] = x[lm:lm + self.para[0] + 1 - mm]
                    lm += self.para[0] + 1 - mm

                s_ = np.array([1, self.para[1] / self.para[0]
                               * (1.0 + 0.159 * bool(cbar))])
                fig = pl.figure(num=None, figsize=(
                    6.4 * s_[0], 6.4 * s_[1]), dpi=None, facecolor="none", edgecolor="none", frameon=False, FigureClass=pl.Figure)
                ax0 = fig.add_axes(
                    [0.06 / s_[0], 0.06 / s_[1], 1.0 - 0.12 / s_[0], 1.0 - 0.12 / s_[1]])
                ax0.set_axis_bgcolor([0.0, 0.0, 0.0, 0.0])

                xaxes = np.arange(self.para[0] + 2, dtype=np.int) - 0.5
                yaxes = np.arange(self.para[1] + 2, dtype=np.int) - 0.5
                if(norm == "log"):
                    n_ = ln(vmin=vmin, vmax=vmax)
Marco Selig's avatar
Marco Selig committed
872
873
                else:
                    n_ = None
874
875
876
877
                sub = ax0.pcolormesh(xaxes, yaxes, np.ma.masked_where(np.isnan(
                    xmesh), xmesh), cmap=cmap, norm=n_, vmin=vmin, vmax=vmax, clim=(vmin, vmax))
                ax0.set_xlim(xaxes[0], xaxes[-1])
                ax0.set_xticks([0], minor=False)
Marco Selig's avatar
Marco Selig committed
878
                ax0.set_xlabel(r"$\ell$")
879
880
                ax0.set_ylim(yaxes[0], yaxes[-1])
                ax0.set_yticks([0], minor=False)
Marco Selig's avatar
Marco Selig committed
881
882
883
                ax0.set_ylabel(r"$m$")
                ax0.set_aspect("equal")
                if(cbar):
884
885
886
887
888
889
                    if(norm == "log"):
                        f_ = lf(10, labelOnlyBase=False)
                        b_ = sub.norm.inverse(
                            np.linspace(0, 1, sub.cmap.N + 1))
                        v_ = np.linspace(
                            sub.norm.vmin, sub.norm.vmax, sub.cmap.N)
Marco Selig's avatar
Marco Selig committed
890
891
892
893
                    else:
                        f_ = None
                        b_ = None
                        v_ = None
894
895
                    fig.colorbar(sub, ax=ax0, orientation="horizontal", fraction=0.1, pad=0.05, shrink=0.75, aspect=20, ticks=[
                                 vmin, vmax], format=f_, drawedges=False, boundaries=b_, values=v_)
Marco Selig's avatar
Marco Selig committed
896
897
                ax0.set_title(title)

898
899
900
        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)
Marco Selig's avatar
Marco Selig committed
901
902
903
904
            pl.close(fig)
        else:
            fig.canvas.draw()

905
906
907
908
909
910
911
912
    def getlm(self):  # > compute all (l,m)
        index = np.arange(self.get_dim())
        n = 2 * self.paradict['lmax'] + 1
        m = np.ceil(
            (n - np.sqrt(n**2 - 8 * (index - self.paradict['lmax']))) / 2
                    ).astype(np.int)
        l = index - self.paradict['lmax'] * m + m * (m - 1) // 2
        return l, m
Marco Selig's avatar
Marco Selig committed
913
914


915
class gl_space(point_space):
Marco Selig's avatar
Marco Selig committed
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
    """
        ..                 __
        ..               /  /
        ..     ____ __  /  /
        ..   /   _   / /  /
        ..  /  /_/  / /  /_
        ..  \___   /  \___/  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``).
933
        dtype : numpy.dtype, *optional*
Marco Selig's avatar
Marco Selig committed
934
935
936
937
938
939
940
941
942
943
            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.
944
        `dtype` has to be either numpy.float64 or numpy.float32.
Marco Selig's avatar
Marco Selig committed
945
946
947
948
949
950
951
952
953
954
955
956
957
958

        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`.
959
        dtype : numpy.dtype
Marco Selig's avatar
Marco Selig committed
960
961
962
963
964
965
966
            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.
    """
967

Ultima's avatar
Ultima committed
968
    def __init__(self, nlat, nlon=None, dtype=np.dtype('float64'),
csongor's avatar
csongor committed
969
                 datamodel='not', comm=gc['default_comm']):
Marco Selig's avatar
Marco Selig committed
970
971
972
973
974
975
976
977
978
        """
            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``).
979
            dtype : numpy.dtype, *optional*
Marco Selig's avatar
Marco Selig committed
980
981
982
983
984
985
986
987
988
989
990
991
992
993
                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.

        """
994
        # check imports
Ultima's avatar
Ultima committed
995
        if not gc['use_libsharp']:
996
            raise ImportError(about._errors.cstring(
Ultima's avatar
Ultima committed
997
                "ERROR: libsharp_wrapper_gl not loaded."))
998

Ultima's avatar
Ultima committed
999
        self._cache_dict = {'check_codomain': {}}
1000
        self.paradict = gl_space_paradict(nlat=nlat, nlon=nlon)
Marco Selig's avatar
Marco Selig committed
1001

1002
1003
1004
        # check data type
        dtype = np.dtype(dtype)
        if dtype not in [np.dtype('float32'), np.dtype('float64')]:
Marco Selig's avatar
Marco Selig committed
1005
            about.warnings.cprint("WARNING: data type set to default.")
1006
1007
            dtype = np.dtype('float')
        self.dtype = dtype
1008

1009
        # set datamodel
csongor's avatar
csongor committed
1010
        if datamodel not in ['not']:
1011
1012
1013
1014
1015
1016
            about.warnings.cprint(
                "WARNING: %s is not a recommended datamodel for gl_space."
                % datamodel)
        if datamodel not in GL_DISTRIBUTION_STRATEGIES:
            raise ValueError(about._errors.cstring(
                "ERROR: %s is not a valid datamodel" % datamodel))
1017
        self.datamodel = datamodel
Marco Selig's avatar
Marco Selig committed
1018
1019

        self.discrete = False
1020
        self.harmonic = False
csongor's avatar
csongor committed
1021
        self.distances = tuple(gl.vol(self.paradict['nlat'],
1022
                                      nlon=self.paradict['nlon']
csongor's avatar
csongor committed
1023
                                      ).astype(np.float))
1024
        self.comm = self._parse_comm(comm)
1025
1026
1027

    @property
    def para(self):
1028
        temp = np.array([self.paradict['nlat'],
1029
1030
                         self.paradict['nlon']], dtype=int)
        return temp
1031

1032
1033
1034
1035
    @para.setter
    def para(self, x):
        self.paradict['nlat'] = x[0]
        self.paradict['nlon'] = x[1]
1036

1037
    def copy(self):
1038
1039
1040
1041
        return gl_space(nlat=self.paradict['nlat'],
                        nlon=self.paradict['nlon'],
                        dtype=self.dtype)

1042
    def get_shape(self):
1043
1044
1045
        return (np.int((self.paradict['nlat'] * self.paradict['nlon'])),)

    def get_dof(self, split=False):
Marco Selig's avatar
Marco Selig committed
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
        """
            Computes the number of degrees of freedom of the space.

            Returns
            -------
            dof : int
                Number of degrees of freedom of the space.

            Notes
            -----
            Since the :py:class:`gl_space` class only supports real-valued
            fields, the number of degrees of freedom is the number of pixels.
        """
Ultima's avatar
Ultima committed
1059
1060
1061
1062
        if split:
            return self.get_shape()
        else:
            return self.get_dim()
Marco Selig's avatar
Marco Selig committed
1063

1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
    def get_meta_volume(self, split=False):
        """
            Calculates the meta volumes.

            The meta volumes are the volumes associated with each component of
            a field, taking into account field components that are not
            explicitly included in the array of field values but are determined
            by symmetry conditions.

            Parameters
            ----------
            total : bool, *optional*
                Whether to return the total meta volume of the space or the
                individual ones of each field component (default: False).

            Returns
            -------
            mol : {numpy.ndarray, float}
                Meta volume of the field components or the complete space.

            Notes
            -----
            For Gauss-Legendre pixelizations, the meta volumes are the pixel
            sizes.
        """
        if not split:
            return np.float(4 * np.pi)
        else:
            mol = self.cast(1, dtype=np.float)
            return self.calc_weight(mol, power=1)

1095
    # TODO: Extend to binning/log
1096
1097
1098
1099
1100
    def enforce_power(self, spec, size=None, kindex=None):
        if kindex is None:
            kindex_size = self.paradict['nlat']
            kindex = np.arange(kindex_size,
                               dtype=np.array(self.distances).dtype)
1101
1102
1103
        return self._enforce_power_helper(spec=spec,
                                          size=size,
                                          kindex=kindex)
Marco Selig's avatar
Marco Selig committed
1104

Ultima's avatar
Ultima committed
1105
    def _check_codomain(self, codomain):
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
        """
            Checks whether a given codomain is compatible to the space or not.

            Parameters
            ----------
            codomain : nifty.space
                Space to be checked for compatibility.

            Returns
            -------
            check : bool
                Whether or not the given codomain is compatible to the space.

            Notes
            -----
            Compatible codomains are instances of :py:class:`gl_space` and
            :py:class:`lm_space`.
        """
        if codomain is None:
            return False

Ultima's avatar
Ultima committed
1127
1128
1129
        if not isinstance(codomain, space):
            raise TypeError(about._errors.cstring("ERROR: invalid input."))

1130
1131
1132
        if self.datamodel is not codomain.datamodel:
            return False

1133
1134
1135
        if self.comm is not codomain.comm:
            return False

1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
        if isinstance(codomain, lm_space):
            nlat = self.paradict['nlat']
            nlon = self.paradict['nlon']
            lmax = codomain.paradict['lmax']
            mmax = codomain.paradict['mmax']
            # nlon==2*lat-1
            # lmax==nlat-1
            # lmax==mmax
            if (nlon == 2*nlat-1) and (lmax == nlat-1) and (lmax == mmax):
                return True

        return False

    def get_codomain(self, **kwargs):
        """
            Generates a compatible codomain to which transformations are
            reasonable, i.e.\  an instance of the :py:class:`lm_space` class.

            Returns
            -------
            codomain : nifty.lm_space
                A compatible codomain.
        """
        nlat = self.paradict['nlat']
        lmax = nlat-1
        mmax = nlat-1
        # lmax,mmax = nlat-1,nlat-1
        if self.dtype == np.dtype('float32'):
1164
1165
1166
            return lm_space(lmax=lmax, mmax=mmax, dtype=np.complex64,
                            datamodel=self.datamodel,
                            comm=self.comm)
1167
        else:
1168
1169
1170
            return lm_space(lmax=lmax, mmax=mmax, dtype=np.complex128,
                            datamodel=self.datamodel,
                            comm=self.comm)
1171

1172
    def get_random_values(self, **kwargs):
Marco Selig's avatar
Marco Selig committed
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
        """
            Generates random field values according to the specifications given
            by the parameters.

            Returns
            -------
            x : numpy.ndarray
                Valid field values.

            Other parameters
            ----------------
            random : string, *optional*
                Specifies the probability distribution from which the random
                numbers are to be drawn.
                Supported distributions are:

                - "pm1" (uniform distribution over {+1,-1} or {+1,+i,-1,-i}
Ultima's avatar
Ultima committed
1190
1191
                - "gau" (normal distribution with zero-mean and a given
                standard
Marco Selig's avatar
Marco Selig committed
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
                    deviation or variance)
                - "syn" (synthesizes from a given power spectrum)
                - "uni" (uniform distribution over [vmin,vmax[)

                (default: None).
            dev : float, *optional*
                Standard deviation (default: 1).
            var : float, *optional*
                Variance, overriding `dev` if both are specified
                (default: 1).
Ultima's avatar
Ultima committed
1202
1203
            spec : {scalar, list, numpy.array, nifty.field, function},
            *optional*
Marco Selig's avatar
Marco Selig committed
1204
1205
1206
1207
1208
1209
1210
1211
                Power spectrum (default: 1).
            codomain : nifty.lm_space, *optional*
                A compatible codomain for power indexing (default: None).
            vmin : float, *optional*
                Lower limit for a uniform distribution (default: 0).
            vmax : float, *optional*
                Upper limit for a uniform distribution (default: 1).
        """
1212
        arg = random.parse_arguments(self, **kwargs)
1213

1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
#        if(arg is None):
#            x = np.zeros(self.get_shape(), dtype=self.dtype)
#
#        elif(arg['random'] == "pm1"):
#            x = random.pm1(dtype=self.dtype, shape=self.get_shape())
#
#        elif(arg['random'] == "gau"):
#            x = random.gau(dtype=self.dtype,
#                           shape=self.get_shape(),
#                           mean=arg['mean'],
#                           std=arg['std'])
#
        if(arg['random'] == "syn"):
1227
1228
1229
1230
            nlat = self.paradict['nlat']
            nlon = self.paradict['nlon']
            lmax = nlat - 1
            if self.dtype == np.dtype('float32'):
1231
1232
1233
                sample = gl.synfast_f(arg['spec'],
                                      nlat=nlat, nlon=nlon,
                                      lmax=lmax, mmax=lmax, alm=False)
Marco Selig's avatar
Marco Selig committed
1234
            else:
1235
1236
1237
                sample = gl.synfast(arg['spec'],
                                    nlat=nlat, nlon=nlon,
                                    lmax=lmax, mmax=lmax, alm=False)
1238
1239
            # weight if discrete
            if self.discrete:
1240
                sample = self.calc_weight(sample, power=0.5)
Marco Selig's avatar
Marco Selig committed
1241
1242

        else:
1243
1244
            sample = super(gl_space, self).get_random_values(**arg)

Marco Selig's avatar
Marco Selig committed
1245

1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
#        elif(arg['random'] == "uni"):
#            x = random.uni(dtype=self.dtype,
#                           shape=self.get_shape(),
#                           vmin=arg['vmin'],
#                           vmax=arg['vmax'])
#
#        else:
#            raise KeyError(about._errors.cstring(
#                "ERROR: unsupported random key '" + str(arg['random']) + "'."))
        sample = self.cast(sample)
        return sample
Marco Selig's avatar
Marco Selig committed
1257

1258
    def calc_weight(self, x, power=1):
Marco Selig's avatar
Marco Selig committed
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
        """
            Weights a given array with the pixel volumes to a given power.

            Parameters
            ----------
            x : numpy.ndarray
                Array to be weighted.
            power : float, *optional*
                Power of the pixel volumes to be used (default: 1).

            Returns
            -------
            y : numpy.ndarray
                Weighted array.
        """
theos's avatar
theos committed
1274
1275
1276
1277
1278
1279
1280
1281
        x = self.cast(x)

        if self.datamodel != 'not':
            about.warnings.cprint(
                "WARNING: Field data is consolidated to all nodes for "
                "external alm2map method!")
        np_x = x.get_full_data()

1282
        # weight
1283
1284
1285
        nlat = self.paradict['nlat']
        nlon = self.paradict['nlon']
        if self.dtype == np.dtype('float32'):
theos's avatar
theos committed
1286
1287
1288
1289
1290
            np_result = gl.weight_f(np_x,
                                    np.array(self.distances),
                                    p=np.float32(power),
                                    nlat=nlat, nlon=nlon,
                                    overwrite=False)
Marco Selig's avatar
Marco Selig committed
1291
        else:
theos's avatar
theos committed
1292