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

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

    NIFTY submodule for grids on the two-sphere.

"""
from __future__ import division
#from nifty import *
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
from nifty.keepers import about
42
from nifty.nifty_core import pi,                                             \
Marco Selig's avatar
Marco Selig committed
43
                  space,                                                     \
44
                  point_space,                                               \
Marco Selig's avatar
Marco Selig committed
45
                  field
Ultimanet's avatar
Ultimanet committed
46
from nifty.nifty_paradict import lm_space_paradict,\
47
48
                            gl_space_paradict,\
                            hp_space_paradict
Ultimanet's avatar
Ultimanet committed
49
from nifty.nifty_random import random
50

Marco Selig's avatar
Marco Selig committed
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#import libsharp_wrapper_gl as gl
try:
    import libsharp_wrapper_gl as gl
except(ImportError):
    about.infos.cprint("INFO: libsharp_wrapper_gl not available.")
    _gl_available = False
    about.warnings.cprint("WARNING: global setting 'about.lm2gl' corrected.")
    about.lm2gl.off()
else:
    _gl_available = True
#import healpy as hp
try:
    import healpy as hp
except(ImportError):
    about.infos.cprint("INFO: healpy not available.")
    _hp_available = False
else:
    _hp_available = True


##-----------------------------------------------------------------------------

73
class lm_space(point_space):
Marco Selig's avatar
Marco Selig 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
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
    """
        ..       __
        ..     /  /
        ..    /  /    __ ____ ___
        ..   /  /   /   _    _   |
        ..  /  /_  /  / /  / /  /
        ..  \___/ /__/ /__/ /__/  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`).
        datatype : 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`.
        datatype : 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.
    """
131
    def __init__(self, lmax, mmax=None, datatype=None, datamodel = 'np'):
Marco Selig's avatar
Marco Selig committed
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
        """
            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`).
            datatype : 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.

        """
159

Marco Selig's avatar
Marco Selig committed
160
161
162
        ## check imports
        if(not _gl_available)and(not _hp_available):
            raise ImportError(about._errors.cstring("ERROR: neither libsharp_wrapper_gl nor healpy available."))
163

164
        self.paradict = lm_space_paradict(lmax=lmax, mmax=mmax)
Marco Selig's avatar
Marco Selig committed
165
166
167
168
169
170
171
172

        ## check data type
        if(datatype is None):
            datatype = np.complex128
        elif(datatype not in [np.complex64,np.complex128]):
            about.warnings.cprint("WARNING: data type set to default.")
            datatype = np.complex128
        self.datatype = datatype
173

174
175
176
177
178
        ## set datamodel
        if datamodel not in ['np']:
            about.warnings.cprint("WARNING: datamodel set to default.")
            self.datamodel = 'np'
        else:
179
180
            self.datamodel = datamodel

Marco Selig's avatar
Marco Selig committed
181
        self.discrete = True
182
        self.harmonic = True
Marco Selig's avatar
Marco Selig committed
183
184
        self.vol = np.real(np.array([1],dtype=self.datatype))

185
186
    @property
    def para(self):
187
        temp = np.array([self.paradict['lmax'],
188
189
                         self.paradict['mmax']], dtype=int)
        return temp
190
191


192
193
194
195
196
    @para.setter
    def para(self, x):
        self.paradict['lmax'] = x[0]
        self.paradict['mmax'] = x[1]

197
198
199
200
    def copy(self):
        return lm_space(lmax = self.paradict['lmax'],
                        mmax = self.paradict['mmax'],
                        datatype = self.datatype)
201

Marco Selig's avatar
Marco Selig committed
202
203
204
205
206
207
208
209
210
211
212
    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    def lmax(self):
        """
            Returns the maximum quantum number :math:`\ell`.

            Returns
            -------
            lmax : int
                Maximum quantum number :math:`\ell`.
        """
213
        return self.paradict['lmax']
Marco Selig's avatar
Marco Selig committed
214
215
216
217
218
219
220
221
222
223
224

    def mmax(self):
        """
            Returns the maximum quantum number :math:`m`.

            Returns
            -------
            mmax : int
                Maximum quantum number :math:`m`.

        """
225
        return self.paradict['mmax']
Marco Selig's avatar
Marco Selig committed
226

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

232
    def get_dim(self, split=False):
Marco Selig's avatar
Marco Selig committed
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
        """
            Computes the dimension of the space, i.e.\  the number of spherical
            harmonics components that are stored.

            Parameters
            ----------
            split : bool, *optional*
                Whether to return the dimension as an array with one component
                or as a scalar (default: False).

            Returns
            -------
            dim : {int, numpy.ndarray}
                Number of spherical harmonics components.

            Notes
            -----
            Due to the symmetry assumption, only the components with
            non-negative :math:`m` are stored and only these components are
            counted here.
        """
        ## dim = (mmax+1)*(lmax-mmax/2+1)
        if(split):
256
            return self.get_shape()
257
            #return np.array([(self.para[0]+1)*(self.para[1]+1)-(self.para[1]+1)*self.para[1]//2],dtype=np.int)
Marco Selig's avatar
Marco Selig committed
258
        else:
259
            return np.prod(self.get_shape())
260
            #return (self.para[0]+1)*(self.para[1]+1)-(self.para[1]+1)*self.para[1]//2
Marco Selig's avatar
Marco Selig committed
261
262
263

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

264
    def get_dof(self):
Marco Selig's avatar
Marco Selig committed
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
        """
            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.
        """
        ## dof = 2*dim-(lmax+1) = (lmax+1)*(2*mmax+1)*(mmax+1)*mmax
        return (self.para[0]+1)*(2*self.para[1]+1)-(self.para[1]+1)*self.para[1]

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    def enforce_power(self,spec,**kwargs):
        """
            Provides a valid power spectrum array from a given object.

            Parameters
            ----------
            spec : {float, list, numpy.ndarray, nifty.field, function}
                Fiducial power spectrum from which a valid power spectrum is to
                be calculated. Scalars are interpreted as constant power
                spectra.

            Returns
            -------
            spec : numpy.ndarray
                Valid power spectrum.
        """
        if(isinstance(spec,field)):
            spec = spec.val.astype(dtype=self.datatype)
        elif(callable(spec)):
            try:
                spec = np.array(spec(np.arange(self.para[0]+1,dtype=self.vol.dtype)),dtype=self.datatype) ## prevent integer division
            except:
                raise TypeError(about._errors.cstring("ERROR: invalid power spectra function.")) ## exception in ``spec(kindex)``
        elif(np.isscalar(spec)):
            spec = np.array([spec],dtype=self.datatype)
        else:
            spec = np.array(spec,dtype=self.datatype)

        ## drop imaginary part
        spec = np.real(spec)
        ## check finiteness
        if(not np.all(np.isfinite(spec))):
            about.warnings.cprint("WARNING: infinite value(s).")
        ## check positivity (excluding null)
        if(np.any(spec<0)):
            raise ValueError(about._errors.cstring("ERROR: nonpositive value(s)."))
        elif(np.any(spec==0)):
            about.warnings.cprint("WARNING: nonpositive value(s).")

        size = self.para[0]+1 ## lmax+1
        ## extend
        if(np.size(spec)==1):
            spec = spec*np.ones(size,dtype=spec.dtype,order='C')
        ## size check
        elif(np.size(spec)<size):
            raise ValueError(about._errors.cstring("ERROR: size mismatch ( "+str(np.size(spec))+" < "+str(size)+" )."))
        elif(np.size(spec)>size):
            about.warnings.cprint("WARNING: power spectrum cut to size ( == "+str(size)+" ).")
            spec = spec[:size]

        return spec

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    def _getlm(self): ## > compute all (l,m)
339
        index = np.arange(self.get_dim(split=False))
Marco Selig's avatar
Marco Selig committed
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
        n = 2*self.para[0]+1
        m = np.ceil((n-np.sqrt(n**2-8*(index-self.para[0])))/2).astype(np.int)
        l = index-self.para[0]*m+m*(m-1)//2
        return l,m

    def set_power_indices(self,**kwargs):
        """
            Sets the (un)indexing objects for spectral indexing internally.

            Parameters
            ----------
            None

            Returns
            -------
            None

            See Also
            --------
            get_power_indices

        """
        ## check storage
        if(not hasattr(self,"power_indices")):
            ## power indices
#            about.infos.cflush("INFO: setting power indices ...")
            kindex = np.arange(self.para[0]+1,dtype=np.int)
            rho = 2*kindex+1
            if(_hp_available): ## default
                pindex = hp.Alm.getlm(self.para[0],i=None)[0] ## l of (l,m)
            else:
                pindex = self._getlm()[0] ## l of (l,m)
            pundex = np.unique(pindex,return_index=True,return_inverse=False)[1]
            ## storage
            self.power_indices = {"kindex":kindex,"pindex":pindex,"pundex":pundex,"rho":rho} ## alphabetical
#            about.infos.cprint(" done.")

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    def enforce_values(self,x,extend=True):
        """
            Computes valid field values from a given object, taking into
            account data types, size, and hermitian symmetry.

            Parameters
            ----------
            x : {float, numpy.ndarray, nifty.field}
                Object to be transformed into an array of valid field values.

            Returns
            -------
            x : numpy.ndarray
                Array containing the valid field values.

            Other parameters
            ----------------
            extend : bool, *optional*
                Whether a scalar is extented to a constant array or not
                (default: True).
        """
        if(isinstance(x,field)):
            if(self==x.domain):
                if(self.datatype is not x.domain.datatype):
                    raise TypeError(about._errors.cstring("ERROR: inequal data types ( '"+str(np.result_type(self.datatype))+"' <> '"+str(np.result_type(x.domain.datatype))+"' )."))
                else:
                    x = np.copy(x.val)
            else:
                raise ValueError(about._errors.cstring("ERROR: inequal domains."))
        else:
            if(np.size(x)==1):
                if(extend):
411
                    x = self.datatype(x)*np.ones(self.get_dim(split=True),dtype=self.datatype,order='C')
Marco Selig's avatar
Marco Selig committed
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
                else:
                    if(np.isscalar(x)):
                        x = np.array([x],dtype=self.datatype)
                    else:
                        x = np.array(x,dtype=self.datatype)
            else:
                x = self.enforce_shape(np.array(x,dtype=self.datatype))

        if(np.size(x)!=1)and(np.any(x.imag[:self.para[0]+1]!=0)):
            about.warnings.cprint("WARNING: forbidden values reset.")
            x.real[:self.para[0]+1] = np.absolute(x[:self.para[0]+1])*(np.sign(x.real[:self.para[0]+1])+(np.sign(x.real[:self.para[0]+1])==0)*np.sign(x.imag[:self.para[0]+1])).astype(np.int)
            x.imag[:self.para[0]+1] = 0 ## x.imag[l,m==0] = 0

        ## check finiteness
        if(not np.all(np.isfinite(x))):
            about.warnings.cprint("WARNING: infinite value(s).")

        return x

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    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.

            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}
                - "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[)

                (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).
        """
470
        arg = random.parse_arguments(self,**kwargs)
Marco Selig's avatar
Marco Selig committed
471
472

        if(arg is None):
473
            return np.zeros(self.get_dim(split=True),dtype=self.datatype,order='C')
Marco Selig's avatar
Marco Selig committed
474
475

        elif(arg[0]=="pm1"):
476
            x = random.pm1(datatype=self.datatype,shape=self.get_dim(split=True))
Marco Selig's avatar
Marco Selig committed
477
478

        elif(arg[0]=="gau"):
479
            x = random.gau(datatype=self.datatype,shape=self.get_dim(split=True),mean=None,dev=arg[2],var=arg[3])
Marco Selig's avatar
Marco Selig committed
480
481
482
483
484
485
486

        elif(arg[0]=="syn"):
            lmax = self.para[0] ## lmax
            if(self.datatype==np.complex64):
                if(_gl_available): ## default
                    x = gl.synalm_f(arg[1],lmax=lmax,mmax=lmax)
                else:
Marco Selig's avatar
Marco Selig committed
487
                    x = hp.synalm(arg[1].astype(np.complex128),lmax=lmax,mmax=lmax).astype(np.complex64) ## FIXME: `verbose` kwarg
Marco Selig's avatar
Marco Selig committed
488
489
            else:
                if(_hp_available): ## default
Marco Selig's avatar
Marco Selig committed
490
                    x = hp.synalm(arg[1],lmax=lmax,mmax=lmax) ## FIXME: `verbose` kwarg
Marco Selig's avatar
Marco Selig committed
491
492
493
494
495
496
                else:
                    x = gl.synalm(arg[1],lmax=lmax,mmax=lmax)

            return x

        elif(arg[0]=="uni"):
497
            x = random.uni(datatype=self.datatype,shape=self.get_dim(split=True),vmin=arg[1],vmax=arg[2])
Marco Selig's avatar
Marco Selig committed
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529

        else:
            raise KeyError(about._errors.cstring("ERROR: unsupported random key '"+str(arg[0])+"'."))

        if(np.any(x.imag[:self.para[0]+1]!=0)):
            x.real[:self.para[0]+1] = np.absolute(x[:self.para[0]+1])*(np.sign(x.real[:self.para[0]+1])+(np.sign(x.real[:self.para[0]+1])==0)*np.sign(x.imag[:self.para[0]+1])).astype(np.int)
            x.imag[:self.para[0]+1] = 0 ## x.imag[l,m==0] = 0

        return x

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    def check_codomain(self,codomain):
        """
            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`.
        """
530
531
        if codomain is None:
            return False
532

Marco Selig's avatar
Marco Selig committed
533
534
535
        if(not isinstance(codomain,space)):
            raise TypeError(about._errors.cstring("ERROR: invalid input."))

536
537
538
        if self.datamodel is not codomain.datamodel:
            return False

Marco Selig's avatar
Marco Selig committed
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
        if(self==codomain):
            return True

        elif(isinstance(codomain,gl_space)):
            ##         lmax==mmax                         nlat==lmax+1                         nlon==2*lmax+1
            if(self.para[0]==self.para[1])and(codomain.para[0]==self.para[0]+1)and(codomain.para[1]==2*self.para[0]+1):
                return True
            else:
                about.warnings.cprint("WARNING: unrecommended codomain.")

        elif(isinstance(codomain,hp_space)):
            ##         lmax==mmax                        3*nside-1==lmax
            if(self.para[0]==self.para[1])and(3*codomain.para[0]-1==self.para[0]):
                return True
            else:
                about.warnings.cprint("WARNING: unrecommended codomain.")

        return False

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    def get_codomain(self,coname=None,**kwargs):
        """
            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.
            .. [#] M. Reinecke and D. Sverre Seljebotn, 2013, "Libsharp - spherical
                   harmonic transforms revisited";
                   `arXiv:1303.4945 <http://www.arxiv.org/abs/1303.4945>`_

        """
        if(coname=="gl")or(coname is None)and(about.lm2gl.status): ## order matters
            if(self.datatype==np.complex64):
                return gl_space(self.para[0]+1,nlon=2*self.para[0]+1,datatype=np.float32) ## nlat,nlon = lmax+1,2*lmax+1
            else:
                return gl_space(self.para[0]+1,nlon=2*self.para[0]+1,datatype=np.float64) ## nlat,nlon = lmax+1,2*lmax+1

        elif(coname=="hp")or(coname is None)and(not about.lm2gl.status):
            return hp_space((self.para[0]+1)//3) ## nside = (lmax+1)/3

        else:
            raise ValueError(about._errors.cstring("ERROR: unsupported or incompatible space '"+coname+"'."))

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    def get_meta_volume(self,total=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
            -----
            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`.
        """
        if(total):
632
            return self.get_dof()
Marco Selig's avatar
Marco Selig committed
633
        else:
634
            mol = np.ones(self.get_dim(split=True),dtype=self.vol.dtype,order='C')
Marco Selig's avatar
Marco Selig committed
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
            mol[self.para[0]+1:] = 2 ## redundant in (l,m) and (l,-m)
            return mol

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    def _dotlm(self,x,y): ## > compute inner product
        dot = np.sum(x.real[:self.para[0]+1]*y.real[:self.para[0]+1],axis=None,dtype=None,out=None)
        dot += 2*np.sum(x.real[self.para[0]+1:]*y.real[:self.para[0]+1:],axis=None,dtype=None,out=None)
        dot += 2*np.sum(x.imag[self.para[0]+1:]*y.imag[:self.para[0]+1:],axis=None,dtype=None,out=None)
        return dot

    def calc_dot(self,x,y):
        """
            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.
        """
        x = self.enforce_shape(np.array(x,dtype=self.datatype))
        y = self.enforce_shape(np.array(y,dtype=self.datatype))
        ## inner product
        if(_gl_available): ## default
            if(self.datatype==np.complex64):
                return gl.dotlm_f(x,y,lmax=self.para[0],mmax=self.para[1])
            else:
                return gl.dotlm(x,y,lmax=self.para[0],mmax=self.para[1])
        else:
672
            return self._dotlm(x,y)
Marco Selig's avatar
Marco Selig committed
673

Ultima's avatar
Ultima committed
674

Marco Selig's avatar
Marco Selig committed
675
676
677
678
679
680
681
682
683
684
685
    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    def calc_transform(self,x,codomain=None,**kwargs):
        """
            Computes the transform of a given array of field values.

            Parameters
            ----------
            x : numpy.ndarray
                Array to be transformed.
            codomain : nifty.space, *optional*
686
                codomain space to which the transformation shall map
Marco Selig's avatar
Marco Selig committed
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
                (default: self).

            Returns
            -------
            Tx : numpy.ndarray
                Transformed array
        """
        x = self.enforce_shape(np.array(x,dtype=self.datatype))

        if(codomain is None):
            return x ## T == id

        ## check codomain
        self.check_codomain(codomain) ## a bit pointless

        if(self==codomain):
            return x ## T == id

        elif(isinstance(codomain,gl_space)):
            ## transform
            if(self.datatype==np.complex64):
                Tx = gl.alm2map_f(x,nlat=codomain.para[0],nlon=codomain.para[1],lmax=self.para[0],mmax=self.para[1],cl=False)
            else:
                Tx = gl.alm2map(x,nlat=codomain.para[0],nlon=codomain.para[1],lmax=self.para[0],mmax=self.para[1],cl=False)
            ## weight if discrete
            if(codomain.discrete):
                Tx = codomain.calc_weight(Tx,power=0.5)

        elif(isinstance(codomain,hp_space)):
            ## transform
Marco Selig's avatar
Marco Selig committed
717
            Tx =  hp.alm2map(x.astype(np.complex128),codomain.para[0],lmax=self.para[0],mmax=self.para[1],pixwin=False,fwhm=0.0,sigma=None,invert=False,pol=True,inplace=False) ## FIXME: `verbose` kwarg
Marco Selig's avatar
Marco Selig committed
718
719
720
721
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
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
            ## weight if discrete
            if(codomain.discrete):
                Tx = codomain.calc_weight(Tx,power=0.5)

        else:
            raise ValueError(about._errors.cstring("ERROR: unsupported transformation."))

        return Tx.astype(codomain.datatype)

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    def calc_smooth(self,x,sigma=0,**kwargs):
        """
            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.
        """
        x = self.enforce_shape(np.array(x,dtype=self.datatype))
        ## check sigma
        if(sigma==0):
            return x
        elif(sigma==-1):
            about.infos.cprint("INFO: invalid sigma reset.")
            sigma = 4.5/(self.para[0]+1) ## sqrt(2)*pi/(lmax+1)
        elif(sigma<0):
            raise ValueError(about._errors.cstring("ERROR: invalid sigma."))
        ## smooth
        if(_hp_available): ## default
            return hp.smoothalm(x,fwhm=0.0,sigma=sigma,invert=False,pol=True,mmax=self.para[1],verbose=False,inplace=False) ## no overwrite
        else:
            return gl.smoothalm(x,lmax=self.para[0],mmax=self.para[1],fwhm=0.0,sigma=sigma,overwrite=False) ## no overwrite


    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    def calc_power(self,x,**kwargs):
        """
            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.
        """
        x = self.enforce_shape(np.array(x,dtype=self.datatype))
        ## power spectrum
        if(self.datatype==np.complex64):
            if(_gl_available): ## default
                return gl.anaalm_f(x,lmax=self.para[0],mmax=self.para[1])
            else:
                return hp.alm2cl(x.astype(np.complex128),alms2=None,lmax=self.para[0],mmax=self.para[1],lmax_out=self.para[0],nspec=None).astype(np.float32)
        else:
            if(_hp_available): ## default
                return hp.alm2cl(x,alms2=None,lmax=self.para[0],mmax=self.para[1],lmax_out=self.para[0],nspec=None)
            else:
                return gl.anaalm(x,lmax=self.para[0],mmax=self.para[1])


    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    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):
        """
            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).

        """
        if(not pl.isinteractive())and(not bool(kwargs.get("save",False))):
            about.warnings.cprint("WARNING: interactive mode off.")

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

            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])

            xaxes = np.arange(self.para[0]+1,dtype=np.int)
            if(vmin is None):
                vmin = np.min(x[:mono].tolist()+(xaxes*(2*xaxes+1)*x)[1:].tolist(),axis=None,out=None)
            if(vmax is None):
                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)
            if(mono):
                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)

            if(other is not None):
                if(isinstance(other,tuple)):
                    other = list(other)
                    for ii in xrange(len(other)):
                        if(isinstance(other[ii],field)):
                            other[ii] = other[ii].power(**kwargs)
                        else:
                            other[ii] = self.enforce_power(other[ii])
                elif(isinstance(other,field)):
                    other = [other.power(**kwargs)]
                else:
                    other = [self.enforce_power(other)]
                imax = max(1,len(other)-1)
                for ii in xrange(len(other)):
                    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)
                    if(mono):
                        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)
                if(legend):
                    ax0.legend()

            ax0.set_xlim(xaxes[1],xaxes[-1])
            ax0.set_xlabel(r"$\ell$")
            ax0.set_ylim(vmin,vmax)
            ax0.set_ylabel(r"$\ell(2\ell+1) C_\ell$")
            ax0.set_title(title)

        else:
            x = self.enforce_shape(np.array(x))
            if(np.iscomplexobj(x)):
                if(title):
                    title += " "
                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)
#                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
                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
            else:
                if(vmin is None):
                    vmin = np.min(x,axis=None,out=None)
                if(vmax is None):
                    vmax = np.max(x,axis=None,out=None)
                if(norm=="log")and(vmin<=0):
                    raise ValueError(about._errors.cstring("ERROR: nonpositive value(s)."))

                xmesh = np.nan*np.empty(self.para[::-1]+1,dtype=np.float16,order='C') ## not a number
                xmesh[4,1] = None
                xmesh[1,4] = None
                lm = 0
                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)
                else:
                    n_ = None
                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)
                ax0.set_xlabel(r"$\ell$")
                ax0.set_ylim(yaxes[0],yaxes[-1])
                ax0.set_yticks([0],minor=False)
                ax0.set_ylabel(r"$m$")
                ax0.set_aspect("equal")
                if(cbar):
                    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)
                    else:
                        f_ = None
                        b_ = None
                        v_ = None
                    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_)
                ax0.set_title(title)

        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)
            pl.close(fig)
        else:
            fig.canvas.draw()

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    def __repr__(self):
        return "<nifty_lm.lm_space>"

    def __str__(self):
        return "nifty_lm.lm_space instance\n- lmax     = "+str(self.para[0])+"\n- mmax     = "+str(self.para[1])+"\n- datatype = numpy."+str(np.result_type(self.datatype))

##-----------------------------------------------------------------------------



##-----------------------------------------------------------------------------

970
class gl_space(point_space):
Marco Selig's avatar
Marco Selig committed
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
    """
        ..                 __
        ..               /  /
        ..     ____ __  /  /
        ..   /   _   / /  /
        ..  /  /_/  / /  /_
        ..  \___   /  \___/  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``).
        datatype : 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.
        `datatype` 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`.
        datatype : 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.
    """
1022
    def __init__(self, nlat, nlon=None, datatype=None, datamodel='np'):
Marco Selig's avatar
Marco Selig committed
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
        """
            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``).
            datatype : 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 _gl_available):
            raise ImportError(about._errors.cstring("ERROR: libsharp_wrapper_gl not available."))
1050

1051
1052

        self.paradict = gl_space_paradict(nlat=nlat, nlon=nlon)
Marco Selig's avatar
Marco Selig committed
1053
1054
1055
1056
1057
1058
1059
1060

        ## check data type
        if(datatype is None):
            datatype = np.float64
        elif(datatype not in [np.float32,np.float64]):
            about.warnings.cprint("WARNING: data type set to default.")
            datatype = np.float64
        self.datatype = datatype
1061

1062
1063
1064
1065
1066
        ## set datamodel
        if datamodel not in ['np']:
            about.warnings.cprint("WARNING: datamodel set to default.")
            self.datamodel = 'np'
        else:
1067
            self.datamodel = datamodel
Marco Selig's avatar
Marco Selig committed
1068
1069

        self.discrete = False
1070
        self.harmonic = False
1071
        self.vol = gl.vol(self.paradict['nlat'],nlon=self.paradict['nlon']).astype(self.datatype)
Marco Selig's avatar
Marco Selig committed
1072

1073
1074
1075

    @property
    def para(self):
1076
        temp = np.array([self.paradict['nlat'],
1077
1078
                         self.paradict['nlon']], dtype=int)
        return temp
1079
1080


1081
1082
1083
1084
    @para.setter
    def para(self, x):
        self.paradict['nlat'] = x[0]
        self.paradict['nlon'] = x[1]
1085

Marco Selig's avatar
Marco Selig committed
1086
1087
    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

1088
1089
1090
1091
    def copy(self):
        return gl_space(nlat = self.paradict['nlat'],
                        nlon = self.paradict['nlon'],
                        datatype = self.datatype)
Marco Selig's avatar
Marco Selig committed
1092
1093
1094
1095
1096
1097
1098
1099
1100
    def nlat(self):
        """
            Returns the number of latitudinal bins.

            Returns
            -------
            nlat : int
                Number of latitudinal bins, or rings.
        """
1101
        return self.paradict['nlat']
Marco Selig's avatar
Marco Selig committed
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111

    def nlon(self):
        """
            Returns the number of longitudinal bins.

            Returns
            -------
            nlon : int
                Number of longitudinal bins.
        """
1112
        return self.paradict['nlon']
Marco Selig's avatar
Marco Selig committed
1113

1114
    def get_shape(self):
1115
1116
        return np.array([(self.paradict['nlat']*self.paradict['nlon'])], dtype=np.int)

1117
    def get_dim(self,split=False):
Marco Selig's avatar
Marco Selig committed
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
        """
            Computes the dimension of the space, i.e.\  the number of pixels.

            Parameters
            ----------
            split : bool, *optional*
                Whether to return the dimension as an array with one component
                or as a scalar (default: False).

            Returns
            -------
            dim : {int, numpy.ndarray}
                Dimension of the space.
        """
        ## dim = nlat*nlon
        if(split):
1134
            return self.get_shape()
1135
            #return np.array([self.para[0]*self.para[1]],dtype=np.int)
Marco Selig's avatar
Marco Selig committed
1136
        else:
1137
            return np.prod(self.get_shape())
1138
            #return self.para[0]*self.para[1]
Marco Selig's avatar
Marco Selig committed
1139
1140
1141

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

1142
    def get_dof(self):
Marco Selig's avatar
Marco Selig committed
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
        """
            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.
        """
        ## dof = dim
        return self.para[0]*self.para[1]

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    def enforce_power(self,spec,**kwargs):
        """
            Provides a valid power spectrum array from a given object.

            Parameters
            ----------
            spec : {float, list, numpy.ndarray, nifty.field, function}
                Fiducial power spectrum from which a valid power spectrum is to
                be calculated. Scalars are interpreted as constant power
                spectra.

            Returns
            -------
            spec : numpy.ndarray
                Valid power spectrum.
        """
        if(isinstance(spec,field)):
            spec = spec.val.astype(self.datatype)
        elif(callable(spec)):
            try:
                spec = np.array(spec(np.arange(self.para[0],dtype=np.int)),dtype=self.datatype)
            except:
                raise TypeError(about._errors.cstring("ERROR: invalid power spectra function.")) ## exception in ``spec(kindex)``
        elif(np.isscalar(spec)):
            spec = np.array([spec],dtype=self.datatype)
        else:
            spec = np.array(spec,dtype=self.datatype)

        ## check finiteness
        if(not np.all(np.isfinite(spec))):
            about.warnings.cprint("WARNING: infinite value(s).")
        ## check positivity (excluding null)
        if(np.any(spec<0)):
            raise ValueError(about._errors.cstring("ERROR: nonpositive value(s)."))
        elif(np.any(spec==0)):
            about.warnings.cprint("WARNING: nonpositive value(s).")

        size = self.para[0] ## nlat
        ## extend
        if(np.size(spec)==1):
            spec = spec*np.ones(size,dtype=spec.dtype,order='C')
        ## size check
        elif(np.size(spec)<size):
            raise ValueError(about._errors.cstring("ERROR: size mismatch ( "+str(np.size(spec))+" < "+str(size)+" )."))
        elif(np.size(spec)>size):
            about.warnings.cprint("WARNING: power spectrum cut to size ( == "+str(size)+" ).")
            spec = spec[:size]

        return spec

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    def set_power_indices(self,**kwargs):
        """
            Raises
            ------
            AttributeError
                Always. -- The power spectrum for a field on the sphere
            is defined by its spherical harmonics components and not its
            position space representation.

        """
        raise AttributeError(about._errors.cstring("ERROR: power spectra indexing ill-defined."))

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    def get_random_values(self,**kwargs):
        """
            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}
                - "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[)

                (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).
            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).
        """
1265
        arg = random.parse_arguments(self,**kwargs)
Marco Selig's avatar
Marco Selig committed
1266
1267

        if(arg is None):
1268
            x = np.zeros(self.get_dim(split=True),dtype=self.datatype,order='C')
Marco Selig's avatar
Marco Selig committed
1269
1270

        elif(arg[0]=="pm1"):
1271
            x = random.pm1(datatype=self.datatype,shape=self.get_dim(split=True))
Marco Selig's avatar
Marco Selig committed
1272
1273

        elif(arg[0]=="gau"):
1274
            x = random.gau(datatype=self.datatype,shape=self.get_dim(split=True),mean=None,dev=arg[2],var=arg[3])
Marco Selig's avatar
Marco Selig committed
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286

        elif(arg[0]=="syn"):
            lmax = self.para[0]-1 ## nlat-1
            if(self.datatype==np.float32):
                x = gl.synfast_f(arg[1],nlat=self.para[0],nlon=self.para[1],lmax=lmax,mmax=lmax,alm=False)
            else:
                x = gl.synfast(arg[1],nlat=self.para[0],nlon=self.para[1],lmax=lmax,mmax=lmax,alm=False)
            ## weight if discrete
            if(self.discrete):
                x = self.calc_weight(x,power=0.5)

        elif(arg[0]=="uni"):
1287
            x = random.uni(datatype=self.datatype,shape=self.get_dim(split=True),vmin=arg[1],vmax=arg[2])
Marco Selig's avatar
Marco Selig committed
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314

        else:
            raise KeyError(about._errors.cstring("ERROR: unsupported random key '"+str(arg[0])+"'."))

        return x

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    def check_codomain(self,codomain):
        """
            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`.
        """
1315
1316
        if codomain is None:
            return False
1317

Marco Selig's avatar
Marco Selig committed
1318
1319
1320
        if(not isinstance(codomain,space)):
            raise TypeError(about._errors.cstring("ERROR: invalid input."))

1321
1322
1323
        if self.datamodel is not codomain.datamodel:
            return False

Marco Selig's avatar
Marco Selig committed
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
        if(self==codomain):
            return True

        if(isinstance(codomain,lm_space)):
            ##         nlon==2*lat-1                          lmax==nlat-1                         lmax==mmax
            if(self.para[1]==2*self.para[0]-1)and(codomain.para[0]==self.para[0]-1)and(codomain.para[0]==codomain.para[1]):
                return True
            else:
                about.warnings.cprint("WARNING: unrecommended codomain.")

        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.
        """
        if(self.datatype==np.float32):
            return lm_space(self.para[0]-1,mmax=self.para[0]-1,datatype=np.complex64) ## lmax,mmax = nlat-1,nlat-1
        else:
            return lm_space(self.para[0]-1,mmax=self.para[0]-1,datatype=np.complex128) ## lmax,mmax = nlat-1,nlat-1

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    def get_meta_volume(self,total=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(total):
            return self.datatype(4*pi)
        else:
1383
            mol = np.ones(self.get_dim(split=True),dtype=self.datatype,order='C')
Marco Selig's avatar
Marco Selig committed
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
            return self.calc_weight(mol,power=1)

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    def calc_weight(self,x,power=1):
        """
            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.
        """
        x = self.enforce_shape(np.array(x,dtype=self.datatype))
        ## weight
        if(self.datatype==np.float32):
            return gl.weight_f(x,self.vol,p=np.float32(power),nlat=self.para[0],nlon=self.para[1],overwrite=False)
        else:
            return gl.weight(x,self.vol,p=np.float64(power),nlat=self.para[0],nlon=self.para[1],overwrite=False)

1411
1412
1413
1414
1415
1416
1417
    def get_weight(self, power = 1):
        ## TODO: Check if this function is compatible to the rest of the nifty code
        ## TODO: Can this be done more efficiently?
        dummy = self.enforce_values(1)
        weighted_dummy = self.calc_weight(dummy, power = power)
        return weighted_dummy/dummy

Marco Selig's avatar
Marco Selig committed
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    def calc_transform(self,x,codomain=None,**kwargs):
        """
            Computes the transform of a given array of field values.

            Parameters
            ----------
            x : numpy.ndarray
                Array to be transformed.
            codomain : nifty.space, *optional*
1429
                codomain space to which the transformation shall map
Marco Selig's avatar
Marco Selig committed
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
                (default: self).

            Returns
            -------
            Tx : numpy.ndarray
                Transformed array

            Notes
            -----
            Only instances of the :py:class:`lm_space` or :py:class:`gl_space`
            classes are allowed as `codomain`.
        """
        x = self.enforce_shape(np.array(x,dtype=self.datatype))

        if(codomain is None):
            return x ## T == id

        ## check codomain
        self.check_codomain(codomain) ## a bit pointless

        if(self==codomain):
            return x ## T == id

        if(isinstance(codomain,lm_space)):
            ## weight if discrete
            if(self.discrete):
                x = self.calc_weight(x,power=-0.5)
            ## transform
            if(self.datatype==np.float32):
                Tx = gl.map2alm_f(x,nlat=self.para[0],nlon=self.para[1],lmax=codomain.para[0],mmax=codomain.para[1])
            else:
                Tx = gl.map2alm(x,nlat=self.para[0],nlon=self.para[1],lmax=codomain.para[0],mmax=codomain.para[1])

        else:
            raise ValueError(about._errors.cstring("ERROR: unsupported transformation."))

        return Tx.astype(codomain.datatype)

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    def calc_smooth(self,x,sigma=0,**kwargs):
        """
            Smoothes an array of field values by convolution with a Gaussian
            kernel.

            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.
        """
        x = self.enforce_shape(np.array(x,dtype=self.datatype))
        ## check sigma
        if(sigma==0):
            return x
        elif(sigma==-1):
            about.infos.cprint("INFO: invalid sigma reset.")
            sigma = 4.5/self.para[0] ## sqrt(2)*pi/(lmax+1)
        elif(sigma<0):
            raise ValueError(about._errors.cstring("ERROR: invalid sigma."))
        ## smooth
        return gl.smoothmap(x,nlat=self.para[0],nlon=self.para[1],lmax=self.para[0]-1,mmax=self.para[0]-1,fwhm=0.0,sigma=sigma)

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    def calc_power(self,x,**kwargs):
        """
            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.
        """
        x = self.enforce_shape(np.array(x,dtype=self.datatype))
        ## weight if discrete
        if(self.discrete):
            x = self.calc_weight(x,power=-0.5)
        ## power spectrum
        if(self.datatype==np.float32):
            return gl.anafast_f(x,nlat=self.para[0],nlon=self.para[1],lmax=self.para[0]-1,mmax=self.para[0]-1,alm=False)
        else:
            return gl.anafast(x,nlat=self.para[0],nlon=self.para[1],lmax=self.para[0]-1,mmax=self.para[0]-1,alm=False)

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    def get_plot(self,x,title="",vmin=None,vmax=None,power=False,unit="",norm=None,cmap=None,cbar=True,other=None,legend=False,mono=True,**kwargs):
        """
            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: False).
            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).

        """
        if(not pl.isinteractive())and(not bool(kwargs.get("save",False))):
            about.warnings.cprint("WARNING: interactive mode off.")

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

            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])

            xaxes = np.arange(self.para[0],dtype=np.int)
            if(vmin is None):
                vmin = np.min(x[:mono].tolist()+(xaxes*(2*xaxes+1)*x)[1:].tolist(),axis=None,out=None)
            if(vmax is None):
                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)
            if(mono):
                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)

            if(other is not None):
                if(isinstance(other,tuple)):
                    other = list(other)
                    for ii in xrange(len(other)):
                        if(isinstance(other[ii],field)):
                            other[ii] = other[ii].power(**kwargs)
                        else:
                            other[ii] = self.enforce_power(other[ii])
                elif(isinstance(other,field)):
                    other = [other.power(**kwargs)]
                else:
                    other = [self.enforce_power(other)]
                imax = max(1,len(other)-1)
                for ii in xrange(len(other)):
                    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)
                    if(mono):
                        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)
                if(legend):
                    ax0.legend()

            ax0.set_xlim(xaxes[1],xaxes[-1])
            ax0.set_xlabel(r"$l$")
            ax0.set_ylim(vmin,vmax)
            ax0.set_ylabel(r"$l(2l+1) C_l$")
            ax0.set_title(title)

        else:
            x = self.enforce_shape(np.array(x,dtype=self.datatype))
            if(vmin is None):
                vmin = np.min(x,axis=None,out=None)
            if(vmax is None):
                vmax = np.max(x,axis=None,out=None)
            if(norm=="log")and(vmin<=0):
                raise ValueError(about._errors.cstring("ERROR: nonpositive value(s)."))

            fig = pl.figure(num=None,figsize=(8.5,5.4),dpi=None,facecolor="none",edgecolor="none",frameon=False,FigureClass=pl.Figure)
            ax0 = fig.add_axes([0.02,0.05,0.96,0.9])

            lon,lat = gl.bounds(self.para[0],nlon=self.para[1])
            lon = (lon-pi)*180/pi
            lat = (lat-pi/2)*180/pi
            if(norm=="log"):
                n_ = ln(vmin=vmin,vmax=vmax)
            else:
                n_ = None
            sub = ax0.pcolormesh(lon,lat,np.roll(x.reshape((self.para[0],self.para[1]),order='C'),self.para[1]//2,axis=1)[::-1,::-1],cmap=cmap,norm=n_,vmin=vmin,vmax=vmax)
            ax0.set_xlim(-180,180)
            ax0.set_ylim(-90,90)
            ax0.set_aspect("equal")
            ax0.axis("off")
            if(cbar):
                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)
                else:
                    f_ = None
                    b_ = None
                    v_ = None
                cb0 = fig.colorbar(sub,ax=ax0,orientation="horizontal",fraction=0.1,pad=0.05,shrink=0.5,aspect=25,ticks=[vmin,vmax],format=f_,drawedges=False,boundaries=b_,values=v_)
                cb0.ax.text(0.5,-1.0,unit,fontdict=None,withdash=False,transform=cb0.ax.transAxes,horizontalalignment="center",verticalalignment="center")
            ax0.set_title(title)

        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)
            pl.close(fig)
        else:
            fig.canvas.draw()

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    def __repr__(self):
        return "<nifty_lm.gl_space>"

    def __str__(self):
        return "nifty_lm.gl_space instance\n- nlat     = "+str(self.para[0])+"\n- nlon     = "+str(self.para[1])+"\n- datatype = numpy."+str(np.result_type(self.datatype))

##-----------------------------------------------------------------------------



##-----------------------------------------------------------------------------

1676
class hp_space(point_space):
Marco Selig's avatar
Marco Selig committed
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
    """
        ..        __
        ..      /  /
        ..     /  /___    ______
        ..    /   _   | /   _   |
        ..   /  / /  / /  /_/  /
        ..  /__/ /__/ /   ____/  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`.
        datatype : 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.
    """
    niter = 0 ## default number of iterations used for transformations

1727
    def __init__(self, nside, datamodel = 'np'):
Marco Selig's avatar
Marco Selig committed
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
        """
            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 _hp_available):
            raise ImportError(about._errors.cstring("ERROR: healpy not available."))
1752
1753
        ## check parameters
        self.paradict = hp_space_paradict(nside=nside)
Marco Selig's avatar
Marco Selig committed
1754
1755

        self.datatype = np.float64
1756

1757
1758
1759
1760
1761
        ## set datamodel
        if datamodel not in ['np']:
            about.warnings.cprint("WARNING: datamodel set to default.")
            self.datamodel = 'np'
        else:
1762
1763
            self.datamodel = datamodel

Marco Selig's avatar
Marco Selig committed
1764
        self.discrete = False
1765
        self.harmonic = False
1766
        self.vol = np.array([4*pi/(12*self.paradict['nside']**2)],dtype=self.datatype)
Marco Selig's avatar
Marco Selig committed
1767

1768
1769
1770
1771
    @property
    def para(self):
        temp = np.array([self.paradict['nside']], dtype=int)
        return temp
1772
1773


1774
1775
1776
    @para.setter
    def para(self, x):
        self.paradict['nside'] = x[0]
1777
1778


Marco Selig's avatar
Marco Selig committed
1779
1780
    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

1781
1782
    def copy(self):
        return hp_space(nside = self.paradict['nside'])
1783

Marco Selig's avatar
Marco Selig committed
1784
1785
1786
1787
1788
1789
1790
1791
1792
    def nside(self):
        """
            Returns the resolution parameter.

            Returns
            -------
            nside : int
                HEALPix resolution parameter.
        """
1793
        return self.paradict['nside']
Marco Selig's avatar
Marco Selig committed
1794

1795
    def get_shape(self):
1796
        return np.array([12*self.paradict['nside']**2], dtype=np.int)
Marco Selig's avatar
Marco Selig committed
1797

1798
    def get_dim(self,split=False):
Marco Selig's avatar
Marco Selig committed
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
        """
            Computes the dimension of the space, i.e.\  the number of pixels.

            Parameters
            ----------
            split : bool, *optional*
                Whether to return the dimension as an array with one component
                or as a scalar (default: False).

            Returns
            -------
            dim : {int, numpy.ndarray}
                Dimension of the space.
        """
        ## dim = 12*nside**2
        if(split):
1815
            return self.get_shape()
1816
            #return np.array([12*self.para[0]**2],dtype=np.int)
Marco Selig's avatar
Marco Selig committed
1817
        else:
1818
            return np.prod(self.get_shape())
1819
            #return 12*self.para[0]**2
Marco Selig's avatar
Marco Selig committed
1820
1821
1822

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

1823
    def get_dof(self):
Marco Selig's avatar
Marco Selig committed
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
        """
            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:`hp_space` class only supports real-valued
            fields, the number of degrees of freedom is the number of pixels.
        """
        ## dof = dim
        return 12*self.para[0]**2

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    def enforce_power(self,spec,**kwargs):
        """
            Provides a valid power spectrum array from a given object.

            Parameters
            ----------
            spec : {float, list, numpy.ndarray, nifty.field, function}
                Fiducial power spectrum from which a valid power spectrum is to
                be calculated. Scalars are interpreted as constant power
                spectra.

            Returns
            -------
            spec : numpy.ndarray
                Valid power spectrum.
        """
        if(isinstance(spec,field)):
            spec = spec.val.astype(self.datatype)
        elif(callable(spec)):
            try:
                spec = np.array(spec(np.arange(3*self.para[0],dtype=np.int)),dtype=self.datatype)
            except:
                raise TypeError(about._errors.cstring("ERROR: invalid power spectra function.")) ## exception in ``spec(kindex)``
        elif(np.isscalar(spec)):
            spec = np.array([spec],dtype=self.datatype)
        else:
            spec = np.array(spec,dtype=self.datatype)

        ## check finiteness
        if(not np.all(np.isfinite(spec))):
            about.warnings.cprint("WARNING: infinite value(s).")
        ## check positivity (excluding null)
        if(np.any(spec<0)):
            raise ValueError(about._errors.cstring("ERROR: nonpositive value(s)."))
        elif(np.any(spec==0)):
            about.warnings.cprint("WARNING: nonpositive value(s).")

        size = 3*self.para[0] ## 3*nside
        ## extend
        if(np.size(spec)==1):
            spec = spec*np.ones(size,dtype=spec.dtype,order='C')
        ## size check
        elif(np.size(spec)<size):
            raise ValueError(about._errors.cstring("ERROR: size mismatch ( "+str(np.size(spec))+" < "+str(size)+" )."))
        elif(np.size(spec)>size):
            about.warnings.cprint("WARNING: power spectrum cut to size ( == "+str(size)+" ).")
            spec = spec[:size]

        return spec

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    def set_power_indices(self,**kwargs):
        """
            Raises
            ------
            AttributeError
                Always. -- The power spectrum for a field on the sphere
            is defined by its spherical harmonics components and not its
            position space representation.

        """
        raise AttributeError(about._errors.cstring("ERROR: power spectra indexing ill-defined."))

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    def get_random_values(self,**kwargs):
        """
            Generates random field values according to the specifications given
            by the parameters.

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

            Other parameters