nifty_core.py 444 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
41
42
43
44
## NIFTY (Numerical Information Field Theory) has been developed at the
## Max-Planck-Institute for Astrophysics.
##
## Copyright (C) 2013 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/>.

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

    .. The NIFTY project homepage is http://www.mpa-garching.mpg.de/ift/nifty/

    NIFTY [#]_, "Numerical Information Field Theory", is a versatile
    library designed to enable the development of signal inference algorithms
    that operate regardless of the underlying spatial grid and its resolution.
    Its object-oriented framework is written in Python, although it accesses
    libraries written in Cython, C++, and C for efficiency.

    NIFTY offers a toolkit that abstracts discretized representations of
    continuous spaces, fields in these spaces, and operators acting on fields
    into classes. Thereby, the correct normalization of operations on fields is
    taken care of automatically without concerning the user. This allows for an
    abstract formulation and programming of inference algorithms, including
    those derived within information field theory. Thus, NIFTY permits its user
Marco Selig's avatar
Marco Selig committed
45
    to rapidly prototype algorithms in 1D and then apply the developed code in
Marco Selig's avatar
Marco Selig committed
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
    higher-dimensional settings of real world problems. The set of spaces on
    which NIFTY operates comprises point sets, n-dimensional regular grids,
    spherical spaces, their harmonic counterparts, and product spaces
    constructed as combinations of those.

    Class & Feature Overview
    ------------------------
    The NIFTY library features three main classes: **spaces** that represent
    certain grids, **fields** that are defined on spaces, and **operators**
    that apply to fields.

    Overview of all (core) classes:

    .. - switch
    .. - notification
    .. - _about
    .. - random
    .. - space
    ..     - point_space
    ..     - rg_space
    ..     - lm_space
    ..     - gl_space
    ..     - hp_space
    ..     - nested_space
    .. - field
    .. - operator
    ..     - diagonal_operator
    ..         - power_operator
    ..     - projection_operator
    ..     - vecvec_operator
    ..     - response_operator
    .. - probing
    ..     - trace_probing
    ..     - diagonal_probing

    .. automodule:: nifty

    :py:class:`space`

    - :py:class:`point_space`
    - :py:class:`rg_space`
    - :py:class:`lm_space`
    - :py:class:`gl_space`
    - :py:class:`hp_space`
    - :py:class:`nested_space`

    :py:class:`field`

    :py:class:`operator`

    - :py:class:`diagonal_operator`
        - :py:class:`power_operator`
    - :py:class:`projection_operator`
    - :py:class:`vecvec_operator`
    - :py:class:`response_operator`

    :py:class:`probing`

    - :py:class:`trace_probing`
    - :py:class:`diagonal_probing`

    References
    ----------
Marco Selig's avatar
Marco Selig committed
109
110
    .. [#] Selig et al., "NIFTY -- Numerical Information Field Theory --
        a versatile Python library for signal inference", submitted to A&A,
Marco Selig's avatar
Marco Selig committed
111
        2013; `arXiv:1301.4499 <http://www.arxiv.org/abs/1301.4499>`_
Marco Selig's avatar
Marco Selig committed
112
113

"""
Marco Selig's avatar
Marco Selig committed
114
## standard libraries
Marco Selig's avatar
Marco Selig committed
115
116
117
118
119
from __future__ import division
import os
#import sys
from sys import stdout as so
import numpy as np
Marco Selig's avatar
Marco Selig committed
120
121
122
123
124
import pylab as pl
from matplotlib.colors import LogNorm as ln
from matplotlib.ticker import LogFormatter as lf
from multiprocessing import Pool as mp
## third party libraries
Marco Selig's avatar
Marco Selig committed
125
126
127
import gfft as gf
import healpy as hp
import libsharp_wrapper_gl as gl
Marco Selig's avatar
Marco Selig committed
128
## internal libraries
Marco Selig's avatar
Marco Selig committed
129
130
131
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
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
339
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
411
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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
import smoothing as gs
import powerspectrum as gp


pi = 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679


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

class switch(object):
    """
        ..                            __   __               __
        ..                          /__/ /  /_            /  /
        ..     _______  __     __   __  /   _/  _______  /  /___
        ..   /  _____/ |  |/\/  / /  / /  /   /   ____/ /   _   |
        ..  /_____  /  |       / /  / /  /_  /  /____  /  / /  /
        .. /_______/   |__/\__/ /__/  \___/  \______/ /__/ /__/  class

        NIFTY support class for switches.

        Parameters
        ----------
        default : bool
            Default status of the switch (default: False).

        See Also
        --------
        notification : A derived class for displaying notifications.

        Examples
        --------
        >>> option = switch()
        >>> option.status
        False
        >>> option
        OFF
        >>> print(option)
        OFF
        >>> option.on()
        >>> print(option)
        ON

        Attributes
        ----------
        status : bool
            Status of the switch.

    """
    def __init__(self,default=False):
        """
            Initilizes the switch and sets the `status`

            Parameters
            ----------
            default : bool
                Default status of the switch (default: False).

        """
        self.status = bool(default)

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

    def on(self):
        """
            Switches the `status` to True.

        """
        self.status = True

    def off(self):
        """
            Switches the `status` to False.

        """
        self.status = False


    def toggle(self):
        """
            Switches the `status`.

        """
        self.status = not self.status

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

    def __repr__(self):
        if(self.status):
            return "ON"
        else:
            return "OFF"

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

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

class notification(switch):
    """
        ..                           __     __   ____   __                       __     __
        ..                         /  /_  /__/ /   _/ /__/                     /  /_  /__/
        ..     __ ___    ______   /   _/  __  /  /_   __   _______   ____ __  /   _/  __   ______    __ ___
        ..   /   _   | /   _   | /  /   /  / /   _/ /  / /   ____/ /   _   / /  /   /  / /   _   | /   _   |
        ..  /  / /  / /  /_/  / /  /_  /  / /  /   /  / /  /____  /  /_/  / /  /_  /  / /  /_/  / /  / /  /
        .. /__/ /__/  \______/  \___/ /__/ /__/   /__/  \______/  \______|  \___/ /__/  \______/ /__/ /__/  class

        NIFTY support class for notifications.

        Parameters
        ----------
        default : bool
            Default status of the switch (default: False).
        ccode : string
            Color code as string (default: "\033[0m"). The surrounding special
            characters are added if missing.

        Notes
        -----
        The color code is a special ANSI escape code, for a list of valid codes
        see [#]_. Multiple codes can be combined by seperating them with a
        semicolon ';'.

        References
        ----------
        .. [#] Wikipedia, `ANSI escape code <http://en.wikipedia.org/wiki/ANSI_escape_code#graphics>`_.

        Examples
        --------
        >>> note = notification()
        >>> note.status
        True
        >>> note.cprint("This is noteworthy.")
        This is noteworthy.
        >>> note.cflush("12"); note.cflush('3')
        123
        >>> note.off()
        >>> note.cprint("This is noteworthy.")
        >>>

        Raises
        ------
        TypeError
            If `ccode` is no string.

        Attributes
        ----------
        status : bool
            Status of the switch.
        ccode : string
            Color code as string.

    """
    _code = "\033[0m" ## "\033[39;49m"

    def __init__(self,default=True,ccode="\033[0m"):
        """
            Initializes the notification and sets `status` and `ccode`

            Parameters
            ----------
            default : bool
                Default status of the switch (default: False).
            ccode : string
                Color code as string (default: "\033[0m"). The surrounding
                special characters are added if missing.

            Raises
            ------
            TypeError
                If `ccode` is no string.

        """
        self.status = bool(default)

        ## check colour code
        if(not isinstance(ccode,str)):
            raise TypeError(about._errors.cstring("ERROR: invalid input."))
        if(ccode[0]!="\033"):
            ccode = "\033"+ccode
        if(ccode[1]!='['):
            ccode = ccode[0]+'['+ccode[1:]
        if(ccode[-1]!='m'):
            ccode = ccode+'m'
        self.ccode = ccode

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

    def set_ccode(self,newccode=None):
        """
            Resets the the `ccode` string.

            Parameters
            ----------
            newccode : string
                Color code as string (default: "\033[0m"). The surrounding
                characters "\033", '[', and 'm' are added if missing.

            Returns
            -------
            None

            Raises
            ------
            TypeError
                If `ccode` is no string.

            Examples
            --------
            >>> note = notification()
            >>> note.set_ccode("31;1") ## "31;1" corresponds to red and bright

        """
        if(newccode is None):
            newccode = self._code
        else:
            ## check colour code
            if(not isinstance(newccode,str)):
                raise TypeError(about._errors.cstring("ERROR: invalid input."))
            if(newccode[0]!="\033"):
                newccode = "\033"+newccode
            if(newccode[1]!='['):
                newccode = newccode[0]+'['+newccode[1:]
            if(newccode[-1]!='m'):
                newccode = newccode+'m'
        self.ccode = newccode

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

    def cstring(self,subject):
        """
            Casts an object to a string and augments that with a colour code.

            Parameters
            ----------
            subject : {string, object}
                String to be augmented with a color code. A given object is
                cast to its string representation by :py:func:`str`.

            Returns
            -------
            cstring : string
                String augmented with a color code.

        """
        return self.ccode+str(subject)+self._code

    def cflush(self,subject):
        """
            Flushes an object in its colour coded sting representation to the
            standard output (*without* line break).

            Parameters
            ----------
            subject : {string, object}
                String to be flushed. A given object is
                cast to a string by :py:func:`str`.

            Returns
            -------
            None

        """
        if(self.status):
            so.write(self.cstring(subject))
            so.flush()

    def cprint(self,subject):
        """
            Flushes an object in its colour coded sting representation to the
            standard output (*with* line break).

            Parameters
            ----------
            subject : {string, object}
                String to be flushed. A given object is
                cast to a string by :py:func:`str`.

            Returns
            -------
            None

        """
        if(self.status):
            so.write(self.cstring(subject)+"\n")
            so.flush()

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

    def __repr__(self):
        if(self.status):
            return self.cstring("ON")
        else:
            return self.cstring("OFF")

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

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

class _about(object): ## nifty support class for global settings
    """
        NIFTY support class for global settings.

        .. warning::
            Turning off the `_error` notification will suppress all NIFTY error
            strings (not recommended).

        Examples
        --------
        >>> from nifty import *
        >>> about
        nifty version 0.2.0
        >>> print(about)
        nifty version 0.2.0
        - errors          = ON (immutable)
        - warnings        = ON
        - infos           = OFF
        - multiprocessing = ON
        - hermitianize    = ON
        - lm2gl           = ON
        >>> about.infos.on()
        >>> about.about.save_config()

        >>> from nifty import *
        INFO: nifty version 0.2.0
        >>> print(about)
        nifty version 0.2.0
        - errors          = ON (immutable)
        - warnings        = ON
        - infos           = ON
        - multiprocessing = ON
        - hermitianize    = ON
        - lm2gl           = ON

        Attributes
        ----------
        warnings : notification
            Notification instance controlling whether warings shall be printed.
        infos : notification
            Notification instance controlling whether information shall be
            printed.
        multiprocessing : switch
            Switch instance controlling whether multiprocessing might be
            performed.
        hermitianize : switch
            Switch instance controlling whether hermitian symmetry for certain
            :py:class:`rg_space` instances is inforced.
        lm2gl : switch
            Switch instance controlling whether default target of a
            :py:class:`lm_space` instance is a :py:class:`gl_space` or a
            :py:class:`hp_space` instance.

    """
    def __init__(self):
        """
            Initializes the _about and sets the attributes.

        """
        ## version
486
        self._version = "0.3.1"
Marco Selig's avatar
Marco Selig committed
487
488
489
490
491
492
493
494
495
496
497
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
530
531
532
533
534
535
536
537
538
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
632
633
634
635
636
637

        ## switches and notifications
        self._errors = notification(default=True,ccode=notification._code)
        self.warnings = notification(default=True,ccode=notification._code)
        self.infos =  notification(default=False,ccode=notification._code)
        self.multiprocessing = switch(default=True)
        self.hermitianize = switch(default=True)
        self.lm2gl = switch(default=True)

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

    def load_config(self,force=True):
        """
            Reads the configuration file "~/.nifty/nifty_config".

            Parameters
            ----------
            force : bool
                Whether to cause an error if the file does not exsist or not.

            Returns
            -------
            None

            Raises
            ------
            ValueError
                If the configuration file is malformed.
            OSError
                If the configuration file does not exist.

        """
        nconfig = os.path.expanduser('~')+"/.nifty/nifty_config"
        if(os.path.isfile(nconfig)):
            rawconfig = []
            with open(nconfig,'r') as configfile:
                for ll in configfile:
                    if(not ll.startswith('#')):
                        rawconfig += ll.split()
            try:
                self._errors = notification(default=True,ccode=rawconfig[0])
                self.warnings = notification(default=int(rawconfig[1]),ccode=rawconfig[2])
                self.infos =  notification(default=int(rawconfig[3]),ccode=rawconfig[4])
                self.multiprocessing = switch(default=int(rawconfig[5]))
                self.hermitianize = switch(default=int(rawconfig[6]))
                self.lm2gl = switch(default=int(rawconfig[7]))
            except(IndexError):
                raise ValueError(about._errors.cstring("ERROR: '"+nconfig+"' damaged."))
        elif(force):
            raise OSError(about._errors.cstring("ERROR: '"+nconfig+"' nonexisting."))

    def save_config(self):
        """
            Writes to the configuration file "~/.nifty/nifty_config".

            Returns
            -------
            None

        """
        rawconfig = [self._errors.ccode[2:-1],str(int(self.warnings.status)),self.warnings.ccode[2:-1],str(int(self.infos.status)),self.infos.ccode[2:-1],str(int(self.multiprocessing.status)),str(int(self.hermitianize.status)),str(int(self.lm2gl.status))]

        nconfig = os.path.expanduser('~')+"/.nifty/nifty_config"
        if(os.path.isfile(nconfig)):
            rawconfig = [self._errors.ccode[2:-1],str(int(self.warnings.status)),self.warnings.ccode[2:-1],str(int(self.infos.status)),self.infos.ccode[2:-1],str(int(self.multiprocessing.status)),str(int(self.hermitianize.status)),str(int(self.lm2gl.status))]
            nconfig = os.path.expanduser('~')+"/.nifty/nifty_config"

            with open(nconfig,'r') as sourcefile:
                with open(nconfig+"_",'w') as targetfile:
                    for ll in sourcefile:
                        if(ll.startswith('#')):
                            targetfile.write(ll)
                        else:
                            ll = ll.replace(ll.split()[0],rawconfig[0]) ## one(!) per line
                            rawconfig = rawconfig[1:]
                            targetfile.write(ll)
            os.rename(nconfig+"_",nconfig) ## overwrite old congiguration
        else:
            if(not os.path.exists(os.path.expanduser('~')+"/.nifty")):
                os.makedirs(os.path.expanduser('~')+"/.nifty")
            with open(nconfig,'w') as targetfile:
                for rr in rawconfig:
                    targetfile.write(rr+"\n") ## one(!) per line

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

    def __repr__(self):
        return "nifty version "+self._version

    def __str__(self):
        return "nifty version "+self._version+"\n- errors          = "+self._errors.cstring("ON")+" (immutable)\n- warnings        = "+str(self.warnings)+"\n- infos           = "+str(self.infos)+"\n- multiprocessing = "+str(self.multiprocessing)+"\n- hermitianize    = "+str(self.hermitianize)+"\n- lm2gl           = "+str(self.lm2gl)

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

## set global instance
about = _about()
about.load_config(force=False)
about.infos.cprint("INFO: "+about.__repr__())





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

class random(object):
    """
        ..                                          __
        ..                                        /  /
        ..       _____   ____ __   __ ___    ____/  /  ______    __ ____ ___
        ..     /   __/ /   _   / /   _   | /   _   / /   _   | /   _    _   |
        ..    /  /    /  /_/  / /  / /  / /  /_/  / /  /_/  / /  / /  / /  /
        ..   /__/     \______| /__/ /__/  \______|  \______/ /__/ /__/ /__/  class

        NIFTY (static) class for pseudo random number generators.

    """
    __init__ = None

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

    @staticmethod
    def arguments(domain,**kwargs):
        """
            Analyses the keyword arguments for supported or necessary ones.

            Parameters
            ----------
            domain : space
                Space wherein the random field values live.
            random : string, *optional*
                Specifies a certain distribution to be drwan from using a
                pseudo random number generator. 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[)

            dev : {scalar, list, ndarray, field}, *optional*
                Standard deviation of the normal distribution if
                ``random == "gau"`` (default: None).
            var : {scalar, list, ndarray, field}, *optional*
                Variance of the normal distribution (outranks the standard
                deviation) if ``random == "gau"`` (default: None).
            spec : {scalar, list, ndarray, field}, *optional*
                Power spectrum for ``random == "syn"`` (default: 1).
            size : integer, *optional*
                Number of irreducible bands for ``random == "syn"``
                (default: None).
638
639
640
641
642
            pindex : numpy.ndarray, *optional*
                Indexing array giving the power spectrum index of each band
                (default: None).
            kindex : numpy.ndarray, *optional*
                Scale of each irreducible band (default: None).
Marco Selig's avatar
Marco Selig committed
643
644
645
646
647
648
649
650
651
652
            vmax : {scalar, list, ndarray, field}, *optional*
                Upper limit of the uniform distribution if ``random == "uni"``
                (default: 1).

            Returns
            -------
            arg : list
                Ordered list of arguments (to be processed in
                ``get_random_values`` of the domain).

653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
            Other Parameters
            ----------------
            codomain : nifty.space, *optional*
                A compatible codomain for power indexing (default: None).
            log : bool, *optional*
                Flag specifying if the spectral binning is performed on logarithmic
                scale or not; if set, the number of used bins is set
                automatically (if not given otherwise); by default no binning
                is done (default: None).
            nbin : integer, *optional*
                Number of used spectral bins; if given `log` is set to ``False``;
                integers below the minimum of 3 induce an automatic setting;
                by default no binning is done (default: None).
            binbounds : {list, array}, *optional*
                User specific inner boundaries of the bins, which are preferred
                over the above parameters; by default no binning is done
                (default: None).            vmin : {scalar, list, ndarray, field}, *optional*
                Lower limit of the uniform distribution if ``random == "uni"``
                (default: 0).

Marco Selig's avatar
Marco Selig committed
673
674
675
676
677
678
            Raises
            ------
            KeyError
                If the `random` key is not supporrted.

        """
Marco Selig's avatar
Marco Selig committed
679
        if("random" in kwargs):
Marco Selig's avatar
Marco Selig committed
680
681
682
683
684
685
686
687
            key = kwargs.get("random")
        else:
            return None

        if(key=="pm1"):
            return [key]

        elif(key=="gau"):
Marco Selig's avatar
Marco Selig committed
688
            if("mean" in kwargs):
Marco Selig's avatar
Marco Selig committed
689
690
691
                mean = domain.enforce_values(kwargs.get("mean"),extend=False)
            else:
                mean = None
Marco Selig's avatar
Marco Selig committed
692
            if("dev" in kwargs):
Marco Selig's avatar
Marco Selig committed
693
694
695
                dev = domain.enforce_values(kwargs.get("dev"),extend=False)
            else:
                dev = None
Marco Selig's avatar
Marco Selig committed
696
            if("var" in kwargs):
Marco Selig's avatar
Marco Selig committed
697
698
699
700
701
702
                var = domain.enforce_values(kwargs.get("var"),extend=False)
            else:
                var = None
            return [key,mean,dev,var]

        elif(key=="syn"):
703
            size = kwargs.get("size",None)
704
            kpack = None
705
            ## explicit power indices
Marco Selig's avatar
Marco Selig committed
706
            if("pindex" in kwargs)and("kindex" in kwargs):
707
708
                kpack = [kwargs.get("pindex"),kwargs.get("kindex")]
                size = len(kpack[1])
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
            else:
            ## implicit power indices
                try:
                    domain.set_power_indices(**kwargs)
                except:
                    if("codomain" in kwargs):
                        codomain = kwargs.get("codomain")
                        domain.check_codomain(codomain)
                        codomain.set_power_indices(**kwargs)
                        kpack = [codomain.power_indices.get("pindex"),codomain.power_indices.get("kindex")]
                        size = len(kpack[1])
                else:
                    kpack = [domain.power_indixes.get("pindex"),domain.power_indixes.get("kindex")]
                    size = len(kpack[1])
            return [key,domain.enforce_power(kwargs.get("spec",1),size=size),kpack]
Marco Selig's avatar
Marco Selig committed
724
725

        elif(key=="uni"):
Marco Selig's avatar
Marco Selig committed
726
            if("vmin" in kwargs):
Marco Selig's avatar
Marco Selig committed
727
728
729
                vmin = domain.enforce_values(kwargs.get("vmin"),extend=False)
            else:
                vmin = 0
Marco Selig's avatar
Marco Selig committed
730
            if("vmax" in kwargs):
Marco Selig's avatar
Marco Selig committed
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
                vmax = domain.enforce_values(kwargs.get("vmax"),extend=False)
            else:
                vmax = 1
            return [key,vmin,vmax]

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

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

    @staticmethod
    def pm1(datatype=np.int,shape=1):
        """
            Generates random field values according to an uniform distribution
            over {+1,-1} or {+1,+i,-1,-i}, respectively.

            Parameters
            ----------
            datatype : type, *optional*
                Data type of the field values (default: np.int).
            shape : {integer, tuple, list, ndarray}, *optional*
                Split up dimension of the space (default: 1).

            Returns
            -------
            x : ndarray
                Random field values (with correct dtype and shape).

        """
        size = np.prod(shape,axis=0,dtype=np.int,out=None)

        if(datatype in [np.complex64,np.complex128]):
            x = np.array([1+0j,0+1j,-1+0j,0-1j],dtype=datatype)[np.random.randint(4,high=None,size=size)]
        else:
            x = 2*np.random.randint(2,high=None,size=size)-1

        return x.astype(datatype).reshape(shape,order='C')

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

    @staticmethod
    def gau(datatype=np.float64,shape=1,mean=None,dev=None,var=None):
        """
            Generates random field values according to a normal distribution.

            Parameters
            ----------
            datatype : type, *optional*
                Data type of the field values (default: np.float64).
            shape : {integer, tuple, list, ndarray}, *optional*
                Split up dimension of the space (default: 1).
            mean : {scalar, ndarray}, *optional*
                Mean of the normal distribution (default: 0).
            dev : {scalar, ndarray}, *optional*
                Standard deviation of the normal distribution (default: 1).
            var : {scalar, ndarray}, *optional*
                Variance of the normal distribution (outranks the standard
                deviation) (default: None).

            Returns
            -------
            x : ndarray
                Random field values (with correct dtype and shape).

            Raises
            ------
            ValueError
                If the array dimension of `mean`, `dev` or `var` mismatch with
                `shape`.

        """
        size = np.prod(shape,axis=0,dtype=np.int,out=None)

        if(datatype in [np.complex64,np.complex128]):
            x = np.empty(size,dtype=datatype,order='C')
            x.real = np.random.normal(loc=0,scale=np.sqrt(0.5),size=size)
            x.imag = np.random.normal(loc=0,scale=np.sqrt(0.5),size=size)
        else:
            x = np.random.normal(loc=0,scale=1,size=size)

        if(var is not None):
            if(np.size(var)==1):
                x *= np.sqrt(np.abs(var))
            elif(np.size(var)==size):
                x *= np.sqrt(np.absolute(var).flatten(order='C'))
            else:
                raise ValueError(about._errors.cstring("ERROR: dimension mismatch ( "+str(np.size(var))+" <> "+str(size)+" )."))
        elif(dev is not None):
            if(np.size(dev)==1):
                x *= np.abs(dev)
            elif(np.size(dev)==size):
                x *= np.absolute(dev).flatten(order='C')
            else:
                raise ValueError(about._errors.cstring("ERROR: dimension mismatch ( "+str(np.size(dev))+" <> "+str(size)+" )."))
        if(mean is not None):
            if(np.size(mean)==1):
                x += mean
            elif(np.size(mean)==size):
                x += np.array(mean).flatten(order='C')
            else:
                raise ValueError(about._errors.cstring("ERROR: dimension mismatch ( "+str(np.size(mean))+" <> "+str(size)+" )."))

        return x.astype(datatype).reshape(shape,order='C')

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

    @staticmethod
    def uni(datatype=np.float64,shape=1,vmin=0,vmax=1):
        """
            Generates random field values according to an uniform distribution
            over [vmin,vmax[.

            Parameters
            ----------
            datatype : type, *optional*
                Data type of the field values (default: np.float64).
            shape : {integer, tuple, list, ndarray}, *optional*
                Split up dimension of the space (default: 1).

            vmin : {scalar, list, ndarray, field}, *optional*
                Lower limit of the uniform distribution (default: 0).
            vmax : {scalar, list, ndarray, field}, *optional*
                Upper limit of the uniform distribution (default: 1).

            Returns
            -------
            x : ndarray
                Random field values (with correct dtype and shape).

        """
        size = np.prod(shape,axis=0,dtype=np.int,out=None)
        if(np.size(vmin)>1):
            vmin = np.array(vmin).flatten(order='C')
        if(np.size(vmax)>1):
            vmax = np.array(vmax).flatten(order='C')

        if(datatype in [np.complex64,np.complex128]):
            x = np.empty(size,dtype=datatype,order='C')
            x.real = (vmax-vmin)*np.random.random(size=size)+vmin
            x.imag = (vmax-vmin)*np.random.random(size=size)+vmin
        elif(datatype in [np.int8,np.int16,np.int32,np.int64]):
            x = np.random.randint(min(vmin,vmax),high=max(vmin,vmax),size=size)
        else:
            x = (vmax-vmin)*np.random.random(size=size)+vmin

        return x.astype(datatype).reshape(shape,order='C')

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

    def __repr__(self):
        return "<nifty.random>"

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





##=============================================================================

class space(object):
    """
        ..     _______   ______    ____ __   _______   _______
        ..   /  _____/ /   _   | /   _   / /   ____/ /   __  /
        ..  /_____  / /  /_/  / /  /_/  / /  /____  /  /____/
        .. /_______/ /   ____/  \______|  \______/  \______/  class
        ..          /__/

        NIFTY base class for spaces and their discretizations.

        The base NIFTY space class is an abstract class from which other
        specific space subclasses, including those preimplemented in NIFTY
        (e.g. the regular grid class) must be derived.

        Parameters
        ----------
        para : {single object, list of objects}, *optional*
            This is a freeform list of parameters that derivatives of the space
            class can use (default: 0).
        datatype : numpy.dtype, *optional*
            Data type of the field values for a field defined on this space
            (default: numpy.float64).

        See Also
        --------
        point_space :  A class for unstructured lists of numbers.
        rg_space : A class for regular cartesian grids in arbitrary dimensions.
        hp_space : A class for the HEALPix discretization of the sphere
            [#]_.
        gl_space : A class for the Gauss-Legendre discretization of the sphere
            [#]_.
        lm_space : A class for spherical harmonic components.
        nested_space : A class for product spaces.

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

        Attributes
        ----------
        para : {single object, list of objects}
            This is a freeform list of parameters that derivatives of the space class can use.
        datatype : numpy.dtype
            Data type of the field values for a field defined on this space.
        discrete : bool
            Whether the space is inherently discrete (true) or a discretization
            of a continuous space (false).
        vol : numpy.ndarray
            An array of pixel volumes, only one component if the pixels all
            have the same volume.
    """
    def __init__(self,para=0,datatype=None):
        """
            Sets the attributes for a space class instance.

            Parameters
            ----------
            para : {single object, list of objects}, *optional*
                This is a freeform list of parameters that derivatives of the
                space class can use (default: 0).
            datatype : numpy.dtype, *optional*
                Data type of the field values for a field defined on this space
                (default: numpy.float64).

            Returns
            -------
            None
        """
        if(np.isscalar(para)):
            para = np.array([para],dtype=np.int)
        else:
            para = np.array(para,dtype=np.int)
        self.para = para

        ## check data type
        if(datatype is None):
            datatype = np.float64
        elif(datatype not in [np.int8,np.int16,np.int32,np.int64,np.float16,np.float32,np.float64,np.complex64,np.complex128]):
            about.warnings.cprint("WARNING: data type set to default.")
            datatype = np.float64
        self.datatype = datatype

        self.discrete = True
        self.vol = np.real(np.array([1],dtype=self.datatype))

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

    def dim(self,split=False):
        """
            Computes the dimension of the space, i.e.\  the number of pixels.

            Parameters
            ----------
            split : bool, *optional*
                Whether to return the dimension split up, i.e. the numbers of
                pixels in each direction, or not (default: False).

            Returns
            -------
            dim : {int, numpy.ndarray}
                Dimension(s) of the space.
        """
998
        raise NotImplementedError(about._errors.cstring("ERROR: no generic instance method 'dim'."))
Marco Selig's avatar
Marco Selig committed
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010

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

    def dof(self):
        """
            Computes the number of degrees of freedom of the space.

            Returns
            -------
            dof : int
                Number of degrees of freedom of the space.
        """
1011
        raise NotImplementedError(about._errors.cstring("ERROR: no generic instance method 'dof'."))
Marco Selig's avatar
Marco Selig committed
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034

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

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

            Parameters
            ----------
            spec : {float, numpy.ndarray, nifty.field}
                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.

            Other parameters
            ----------------
            size : int, *optional*
                Number of bands the power spectrum shall have (default: None).
1035
1036
            kindex : numpy.ndarray, *optional*
                Scale of each band.
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
            codomain : nifty.space, *optional*
                A compatible codomain for power indexing (default: None).
            log : bool, *optional*
                Flag specifying if the spectral binning is performed on logarithmic
                scale or not; if set, the number of used bins is set
                automatically (if not given otherwise); by default no binning
                is done (default: None).
            nbin : integer, *optional*
                Number of used spectral bins; if given `log` is set to ``False``;
                integers below the minimum of 3 induce an automatic setting;
                by default no binning is done (default: None).
            binbounds : {list, array}, *optional*
                User specific inner boundaries of the bins, which are preferred
                over the above parameters; by default no binning is done
                (default: None).            vmin : {scalar, list, ndarray, field}, *optional*
                Lower limit of the uniform distribution if ``random == "uni"``
                (default: 0).
1054

Marco Selig's avatar
Marco Selig committed
1055
        """
1056
        raise NotImplementedError(about._errors.cstring("ERROR: no generic instance method 'enforce_power'."))
Marco Selig's avatar
Marco Selig committed
1057
1058
1059

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

1060
    def get_power_index(self,irreducible=False): ## TODO: remove in future version
Marco Selig's avatar
Marco Selig committed
1061
1062
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
        """
            Provides the indexing array of the power spectrum.

            Provides either an array giving for each component of a field the
            corresponding index of a power spectrum (if ``irreducible==False``)
            or two arrays containing the scales of the modes and the numbers of
            modes with this scale (if ``irreducible==True``).

            Parameters
            ----------
            irreducible : bool, *optional*
                Whether to return two arrays containing the scales and
                corresponding number of represented modes (if True) or the
                indexing array (if False) (default: False).

            Returns
            -------
            kindex : numpy.ndarray
                Scale of each band, returned only if ``irreducible==True``.
            rho : numpy.ndarray
                Number of modes per scale represented in the discretization,
                returned only if ``irreducible==True``.
            pindex : numpy.ndarray
                Indexing array giving the power spectrum index for each
                represented mode, returned only if ``irreducible==False``.

            Notes
            -----
            The indexing array is of the same shape as a field living in this
            space and contains the indices of the associated bands.
            kindex and rho are each one-dimensional arrays.
        """
1093
        about.warnings.cprint("WARNING: 'get_power_index' is deprecated.")
1094
        raise NotImplementedError(about._errors.cstring("ERROR: no generic instance method 'get_power_index'."))
Marco Selig's avatar
Marco Selig committed
1095

1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
    def get_power_undex(self,pindex=None):
        """
            Provides the unindexing list for an indexed power spectrum.

            Parameters
            ----------
            pindex : numpy.ndarray, *optional*
                Indexing array giving the power spectrum index for each
                represented mode.

            Returns
            -------
            pundex : list
                Unindexing list undoing power indexing.

            Notes
            -----
            Indexing with the unindexing list undoes the indexing with the
            indexing array; i.e., ``x == x[pindex][pundex]``.

            See also
            --------
            get_power_index

        """
1121
        about.warnings.cprint("WARNING: 'get_power_undex' is deprecated.")
1122
1123
1124
1125
        if(pindex is None):
            pindex = self.get_power_index(irreducible=False)
        return list(np.unravel_index(np.unique(pindex,return_index=True,return_inverse=False)[1],pindex.shape,order='C'))

1126
    def set_power_indices(self,**kwargs):
Marco Selig's avatar
Marco Selig committed
1127
        """
1128
1129
1130
1131
1132
1133
            Sets the (un)indexing objects for spectral indexing internally.

            Parameters
            ----------
            log : bool
                Flag specifying if the binning is performed on logarithmic
1134
1135
1136
                scale or not; if set, the number of used bins is set
                automatically (if not given otherwise); by default no binning
                is done (default: None).
1137
            nbin : integer
1138
1139
                Number of used bins; if given `log` is set to ``False``;
                integers below the minimum of 3 induce an automatic setting;
1140
1141
                by default no binning is done (default: None).
            binbounds : {list, array}
1142
1143
1144
                User specific inner boundaries of the bins, which are preferred
                over the above parameters; by default no binning is done
                (default: None).
1145
1146
1147
1148
1149
1150
1151
1152

            Returns
            -------
            None

            See also
            --------
            get_power_indices
Marco Selig's avatar
Marco Selig committed
1153
1154

        """
1155
        raise NotImplementedError(about._errors.cstring("ERROR: no generic instance method 'set_power_indices'."))
1156

1157
1158
1159
    def get_power_indices(self,**kwargs):
        """
            Provides the (un)indexing objects for spectral indexing.
1160

1161
1162
1163
1164
1165
1166
1167
1168
1169
            Provides one-dimensional arrays containing the scales of the
            spectral bands and the numbers of modes per scale, and an array
            giving for each component of a field the corresponding index of a
            power spectrum as well as an unindexing list.

            Parameters
            ----------
            log : bool
                Flag specifying if the binning is performed on logarithmic
1170
1171
1172
                scale or not; if set, the number of used bins is set
                automatically (if not given otherwise); by default no binning
                is done (default: None).
1173
            nbin : integer
1174
1175
                Number of used bins; if given `log` is set to ``False``;
                integers below the minimum of 3 induce an automatic setting;
1176
1177
                by default no binning is done (default: None).
            binbounds : {list, array}
1178
1179
1180
                User specific inner boundaries of the bins, which are preferred
                over the above parameters; by default no binning is done
                (default: None).
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

            Returns
            -------
            kindex : numpy.ndarray
                Scale of each spectral band.
            rho : numpy.ndarray
                Number of modes per scale represented in the discretization.
            pindex : numpy.ndarray
                Indexing array giving the power spectrum index for each
                represented mode.
            pundex : list
                Unindexing list undoing power spectrum indexing.

            Notes
            -----
            The ``kindex`` and ``rho`` are each one-dimensional arrays.
            The indexing array is of the same shape as a field living in this
            space and contains the indices of the associated bands.
            Indexing with the unindexing list undoes the indexing with the
            indexing array; i.e., ``power == power[pindex][pundex]``.

            See also
            --------
            set_power_indices

        """
        self.set_power_indices(**kwargs)
        return self.power_indices.get("kindex"),self.power_indices.get("rho"),self.power_indices.get("pindex"),self.power_indices.get("pundex")
1209

Marco Selig's avatar
Marco Selig committed
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
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
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
1315
1316
1317
    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    def enforce_shape(self,x):
        """
            Shapes an array of valid field values correctly, according to the
            specifications of the space instance.

            Parameters
            ----------
            x : numpy.ndarray
                Array containing the field values to be put into shape.

            Returns
            -------
            y : numpy.ndarray
                Correctly shaped array.
        """
        x = np.array(x)

        if(np.size(x)!=self.dim(split=False)):
            raise ValueError(about._errors.cstring("ERROR: dimension mismatch ( "+str(np.size(x))+" <> "+str(self.dim(split=False))+" )."))
#        elif(not np.all(np.array(np.shape(x))==self.dim(split=True))):
#            about.warnings.cprint("WARNING: reshaping forced.")

        return x.reshape(self.dim(split=True),order='C')

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

    def enforce_values(self,x,extend=True):
        """
            Computes valid field values from a given object, according to the
            constraints from the space instance.

            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 = x.val
            else:
                raise ValueError(about._errors.cstring("ERROR: inequal domains."))
        else:
            if(np.size(x)==1):
                if(extend):
                    x = self.datatype(x)*np.ones(self.dim(split=True),dtype=self.datatype,order='C')
                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))

        ## 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.

            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 : {float, numpy.ndarray}, *optional*
                Power spectrum (default: 1).
1318
1319
1320
1321
1322
            pindex : numpy.ndarray, *optional*
                Indexing array giving the power spectrum index of each band
                (default: None).
            kindex : numpy.ndarray, *optional*
                Scale of each band (default: None).
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
            codomain : nifty.space, *optional*
                A compatible codomain with power indices (default: None).
            log : bool, *optional*
                Flag specifying if the spectral binning is performed on logarithmic
                scale or not; if set, the number of used bins is set
                automatically (if not given otherwise); by default no binning
                is done (default: None).
            nbin : integer, *optional*
                Number of used spectral bins; if given `log` is set to ``False``;
                integers below the minimum of 3 induce an automatic setting;
                by default no binning is done (default: None).
            binbounds : {list, array}, *optional*
                User specific inner boundaries of the bins, which are preferred
                over the above parameters; by default no binning is done
                (default: None).            vmin : {scalar, list, ndarray, field}, *optional*
                Lower limit of the uniform distribution if ``random == "uni"``
                (default: 0).
Marco Selig's avatar
Marco Selig committed
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
1383
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
1411
1412
            vmin : float, *optional*
                Lower limit for a uniform distribution (default: 0).
            vmax : float, *optional*
                Upper limit for a uniform distribution (default: 1).
        """
        arg = random.arguments(self,**kwargs)

        if(arg is None):
            x = np.zeros(self.dim(split=True),dtype=self.datatype,order='C')

        elif(arg[0]=="pm1"):
            x = random.pm1(datatype=self.datatype,shape=self.dim(split=True))

        elif(arg[0]=="gau"):
            x = random.gau(datatype=self.datatype,shape=self.dim(split=True),mean=None,dev=arg[2],var=arg[3])

        elif(arg[0]=="uni"):
            x = random.uni(datatype=self.datatype,shape=self.dim(split=True),vmin=arg[1],vmax=arg[2])

        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.
        """
        if(not isinstance(codomain,space)):
            raise TypeError(about._errors.cstring("ERROR: invalid input."))

        if(self==codomain):
            return True

        return False

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

    def get_codomain(self,**kwargs):
        """
            Generates a compatible codomain to which transformations are
            reasonable, usually either the position basis or the basis of
            harmonic eigenmodes.

            Parameters
            ----------
            coname : string, *optional*
                String specifying a desired codomain (default: None).
            cozerocenter : {bool, numpy.ndarray}, *optional*
                Whether or not the grid is zerocentered for each axis or not
                (default: None).
            conest : list, *optional*
                List of nested spaces of the codomain (default: None).
            coorder : list, *optional*
                Permutation of the list of nested spaces (default: None).

            Returns
            -------
            codomain : nifty.space
                A compatible codomain.
        """
1413
        raise NotImplementedError(about._errors.cstring("ERROR: no generic instance method 'get_codomain'."))
Marco Selig's avatar
Marco Selig committed
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436

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

    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.
        """
1437
        raise NotImplementedError(about._errors.cstring("ERROR: no generic instance method 'get_meta_volume'."))
Marco Selig's avatar
Marco Selig committed
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

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

    def calc_weight(self,x,power=1):
        """
            Weights a given array of field values with the pixel volumes (not
            the meta 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
        return x*self.vol**power

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

    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 : float
                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
        return np.dot(np.conjugate(x),y,out=None)

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

    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*
                Target space to which the transformation shall map
                (default: self).

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

            Other parameters
            ----------------
            iter : int, *optional*
                Number of iterations performed in specific transformations.
        """
        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

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

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

    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 (default: 0).

            Returns
            -------
            Gx : numpy.ndarray
                Smoothed array.

            Other parameters
            ----------------
            iter : int, *optional*
                Number of iterations (default: 0).
        """
1549
        raise NotImplementedError(about._errors.cstring("ERROR: no generic instance method 'calc_smooth'."))
Marco Selig's avatar
Marco Selig committed
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572

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

    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.

            Other parameters
            ----------------
            pindex : numpy.ndarray, *optional*
                Indexing array assigning the input array components to
                components of the power spectrum (default: None).
1573
1574
1575
            kindex : numpy.ndarray, *optional*
                Scale corresponding to each band in the power spectrum
                (default: None).
Marco Selig's avatar
Marco Selig committed
1576
1577
            rho : numpy.ndarray, *optional*
                Number of degrees of freedom per band (default: None).
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
            codomain : nifty.space, *optional*
                A compatible codomain for power indexing (default: None).
            log : bool, *optional*
                Flag specifying if the spectral binning is performed on logarithmic
                scale or not; if set, the number of used bins is set
                automatically (if not given otherwise); by default no binning
                is done (default: None).
            nbin : integer, *optional*
                Number of used spectral bins; if given `log` is set to ``False``;
                integers below the minimum of 3 induce an automatic setting;
                by default no binning is done (default: None).
            binbounds : {list, array}, *optional*
                User specific inner boundaries of the bins, which are preferred
                over the above parameters; by default no binning is done
                (default: None).            vmin : {scalar, list, ndarray, field}, *optional*
                Lower limit of the uniform distribution if ``random == "uni"``
                (default: 0).

Marco Selig's avatar
Marco Selig committed
1596
        """
1597
        raise NotImplementedError(about._errors.cstring("ERROR: no generic instance method 'calc_power'."))
Marco Selig's avatar
Marco Selig committed
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

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

    def get_plot(self,x,**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).
            error : {float, numpy.ndarray, nifty.field}, *optional*
                Object indicating some confidence interval to be plotted
                (default: None).
            kindex : numpy.ndarray, *optional*
                Scale corresponding to each band in the power spectrum
                (default: None).
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
            codomain : nifty.space, *optional*
                A compatible codomain for power indexing (default: None).
            log : bool, *optional*
                Flag specifying if the spectral binning is performed on logarithmic
                scale or not; if set, the number of used bins is set
                automatically (if not given otherwise); by default no binning
                is done (default: None).
            nbin : integer, *optional*
                Number of used spectral bins; if given `log` is set to ``False``;
                integers below the minimum of 3 induce an automatic setting;
                by default no binning is done (default: None).
            binbounds : {list, array}, *optional*
                User specific inner boundaries of the bins, which are preferred
                over the above parameters; by default no binning is done
                (default: None).            vmin : {scalar, list, ndarray, field}, *optional*
                Lower limit of the uniform distribution if ``random == "uni"``
                (default: 0).
Marco Selig's avatar
Marco Selig committed
1664
1665
            iter : int, *optional*
                Number of iterations (default: 0).
1666

Marco Selig's avatar
Marco Selig committed
1667
        """
1668
        raise NotImplementedError(about._errors.cstring("ERROR: no generic instance method 'get_plot'."))
Marco Selig's avatar
Marco Selig committed
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685

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

    def __repr__(self):
        return "<nifty.space>"

    def __str__(self):
        return "nifty.space instance\n- para     = "+str(self.para)+"\n- datatype = numpy."+str(np.result_type(self.datatype))

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

    def __len__(self):
        return int(self.dim(split=False))

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

    def _meta_vars(self): ## > captures all nonstandard properties
1686
        mars = np.array([ii[1] for ii in vars(self).iteritems() if ii[0] not in ["para","datatype","discrete","vol","power_indices"]],dtype=np.object)
Marco Selig's avatar
Marco Selig committed
1687
1688
1689
1690
1691
1692
1693
        if(np.size(mars)==0):
            return None
        else:
            return mars

    def __eq__(self,x): ## __eq__ : self == x
        if(isinstance(x,space)):
1694
            if(isinstance(x,type(self)))and(np.all(self.para==x.para))and(self.discrete==x.discrete)and(np.all(self.vol==x.vol))and(np.all(self._meta_vars()==x._meta_vars())): ## data types are ignored
Marco Selig's avatar
Marco Selig committed
1695
1696
1697
1698
1699
                return True
        return False

    def __ne__(self,x): ## __ne__ : self <> x
        if(isinstance(x,space)):
1700
            if(not isinstance(x,type(self)))or(np.any(self.para!=x.para))or(self.discrete!=x.discrete)or(np.any(self.vol!=x.vol))or(np.any(self._meta_vars()!=x._meta_vars())): ## data types are ignored
Marco Selig's avatar
Marco Selig committed
1701
1702
1703
1704
1705
                return True
        return False

    def __lt__(self,x): ## __lt__ : self < x
        if(isinstance(x,space)):
1706
            if(not isinstance(x,type(self)))or(np.size(self.para)!=np.size(x.para))or(np.size(self.vol)!=np.size(x.vol)):
Marco Selig's avatar
Marco Selig committed
1707
                raise ValueError(about._errors.cstring("ERROR: incomparable spaces."))
1708
            elif(self.discrete==x.discrete): ## data types are ignored
Marco Selig's avatar
Marco Selig committed
1709
1710
1711
1712
1713
                for ii in range(np.size(self.para)):
                    if(self.para[ii]<x.para[ii]):
                        return True
                    elif(self.para[ii]>x.para[ii]):
                        return False
1714
1715
1716
1717
1718
                for ii in range(np.size(self.vol)):
                    if(self.vol[ii]<x.vol[ii]):
                        return True
                    elif(self.vol[ii]>x.vol[ii]):
                        return False
Marco Selig's avatar
Marco Selig committed
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
                s_mars = self._meta_vars()
                x_mars = x._meta_vars()
                for ii in range(np.size(s_mars)):
                    if(np.all(s_mars[ii]<x_mars[ii])):
                        return True
                    elif(np.any(s_mars[ii]>x_mars[ii])):
                        break
        return False

    def __le__(self,x): ## __le__ : self <= x
        if(isinstance(x,space)):
1730
            if(not isinstance(x,type(self)))or(np.size(self.para)!=np.size(x.para))or(np.size(self.vol)!=np.size(x.vol)):
Marco Selig's avatar
Marco Selig committed
1731
1732
1733
1734
1735
1736
1737
                raise ValueError(about._errors.cstring("ERROR: incomparable spaces."))
            elif(self.discrete==x.discrete): ## data types are ignored
                for ii in range(np.size(self.para)):
                    if(self.para[ii]<x.para[ii]):
                        return True
                    if(self.para[ii]>x.para[ii]):
                        return False
1738
1739
1740
1741
1742
                for ii in range(np.size(self.vol)):
                    if(self.vol[ii]<x.vol[ii]):
                        return True
                    if(self.vol[ii]>x.vol[ii]):
                        return False
Marco Selig's avatar
Marco Selig committed
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
                s_mars = self._meta_vars()
                x_mars = x._meta_vars()
                for ii in range(np.size(s_mars)):
                    if(np.all(s_mars[ii]<x_mars[ii])):
                        return True
                    elif(np.any(s_mars[ii]>x_mars[ii])):
                        return False
                return True
        return False

    def __gt__(self,x): ## __gt__ : self > x
        if(isinstance(x,space)):
1755
            if(not isinstance(x,type(self)))or(np.size(self.para)!=np.size(x.para))or(np.size(self.vol)!=np.size(x.vol)):
Marco Selig's avatar
Marco Selig committed
1756
1757
1758
1759
1760
1761
1762
                raise ValueError(about._errors.cstring("ERROR: incomparable spaces."))
            elif(self.discrete==x.discrete): ## data types are ignored
                for ii in range(np.size(self.para)):
                    if(self.para[ii]>x.para[ii]):
                        return True
                    elif(self.para[ii]<x.para[ii]):
                        break
1763
1764
1765
1766
1767
                for ii in range(np.size(self.vol)):
                    if(self.vol[ii]>x.vol[ii]):
                        return True
                    elif(self.vol[ii]<x.vol[ii]):
                        break
Marco Selig's avatar
Marco Selig committed
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
                s_mars = self._meta_vars()
                x_mars = x._meta_vars()
                for ii in range(np.size(s_mars)):
                    if(np.all(s_mars[ii]>x_mars[ii])):
                        return True
                    elif(np.any(s_mars[ii]<x_mars[ii])):
                        break
        return False

    def __ge__(self,x): ## __ge__ : self >= x
        if(isinstance(x,space)):
1779
            if(not isinstance(x,type(self)))or(np.size(self.para)!=np.size(x.para))or(np.size(self.vol)!=np.size(x.vol)):
Marco Selig's avatar
Marco Selig committed
1780
1781
1782
1783
1784
1785
1786
                raise ValueError(about._errors.cstring("ERROR: incomparable spaces."))
            elif(self.discrete==x.discrete): ## data types are ignored
                for ii in range(np.size(self.para)):
                    if(self.para[ii]>x.para[ii]):
                        return True
                    if(self.para[ii]<x.para[ii]):
                        return False
1787
1788
1789
1790
1791
                for ii in range(np.size(self.vol)):
                    if(self.vol[ii]>x.vol[ii]):
                        return True
                    if(self.vol[ii]<x.vol[ii]):
                        return False
Marco Selig's avatar
Marco Selig committed
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
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
                s_mars = self._meta_vars()
                x_mars = x._meta_vars()
                for ii in range(np.size(s_mars)):
                    if(np.all(s_mars[ii]>x_mars[ii])):
                        return True
                    elif(np.any(s_mars[ii]<x_mars[ii])):
                        return False
                return True
        return False

##=============================================================================



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

class point_space(space):
    """
        ..                            __             __
        ..                          /__/           /  /_
        ..      ______    ______    __   __ ___   /   _/
        ..    /   _   | /   _   | /  / /   _   | /  /
        ..   /  /_/  / /  /_/  / /  / /  / /  / /  /_
        ..  /   ____/  \______/ /__/ /__/ /__/  \___/  space class
        .. /__/

        NIFTY subclass for unstructured spaces.

        Unstructured spaces are lists of values without any geometrical
        information.

        Parameters
        ----------
        num : int
            Number of points.
        datatype : numpy.dtype, *optional*
            Data type of the field values (default: None).

        Attributes
        ----------
        para : numpy.ndarray
            Array containing the number of points.
        datatype : numpy.dtype
            Data type of the field values.
        discrete : bool
            Parameter captioning the fact that a :py:class:`point_space` is
            always discrete.
        vol : numpy.ndarray
            Pixel volume of the :py:class:`point_space`, which is always 1.
    """
    def __init__(self,num,datatype=None):
        """
            Sets the attributes for a point_space class instance.

            Parameters
            ----------
            num : int
                Number of points.
            datatype : numpy.dtype, *optional*
                Data type of the field values (default: numpy.float64).

            Returns
            -------
            None.
        """
        ## check parameter
        if(num<1):
            raise ValueError(about._errors.cstring("ERROR: nonpositive number."))
        self.para = np.array([num],dtype=np.int)

        ## check datatype
        if(datatype is None):
            datatype = np.float64
        elif(datatype not in [np.int8,np.int16,np.int32,np.int64,np.float16,np.float32,np.float64,np.complex64,np.complex128]):
            about.warnings.cprint("WARNING: data type set to default.")
            datatype = np.float64
        self.datatype = datatype

        self.discrete = True
        self.vol = np.real(np.array([1],dtype=self.datatype))

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

    def num(self):
        """
            Returns the number of points.

            Returns
            -------
            num : int
                Number of points.
        """
        return self.para[0]

    def dim(self,split=False):
        """
            Computes the dimension of the space, i.e.\  the number of points.

            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(s) of the space.
        """
        ## dim = num
        if(split):
            return np.array([self.para[0]],dtype=np.int)
        else:
            return self.para[0]

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

    def dof(self):
        """
            Computes the number of degrees of freedom of the space, i.e./  the
            number of points for real-valued fields and twice that number for
            complex-valued fields.

            Returns
            -------
            dof : int
                Number of degrees of freedom of the space.
        """
        ## dof ~ dim
        if(self.datatype in [np.complex64,np.complex128]):
            return 2*self.para[0]
        else:
            return self.para[0]

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

    def enforce_power(self,spec,**kwargs):
        """
            Raises an error since the power spectrum is ill-defined for point
            spaces.
        """
        raise AttributeError(about._errors.cstring("ERROR: power spectra ill-defined for (unstructured) point spaces."))

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

1937
    def get_power_index(self,irreducible=False): ## TODO: remove in future version
Marco Selig's avatar
Marco Selig committed
1938
1939
1940
1941
        """
            Raises an error since the power spectrum is ill-defined for point
            spaces.
        """
1942
        about.warnings.cprint("WARNING: 'get_power_index' is deprecated.")
Marco Selig's avatar
Marco Selig committed
1943
1944
        raise AttributeError(about._errors.cstring("ERROR: power spectra ill-defined for (unstructured) point spaces."))

1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
    def set_power_indices(self,**kwargs):
        """
            Raises
            ------
            AttributeError
                Always. -- The power spectrum is ill-defined for point spaces.

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

Marco Selig's avatar
Marco Selig committed
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    def get_codomain(self,**kwargs):
        """
            Generates a compatible codomain to which transformations are
            reasonable, in this case another instance of
            :py:class:`point_space` with the same properties.

            Returns
            -------
            codomain : nifty.point_space
                A compatible codomain.
        """
        return point_space(self.para[0],datatype=self.datatype) ## == self

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

    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
            -----
            Since point spaces are unstructured, the meta volume of each
            component is one, the total meta volume of the space is the number
            of points.
        """
        if(total):
            return self.dim(split=False)
        else:
            return np.ones(self.dim(split=True),dtype=self.vol.dtype,order='C')

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

    def calc_smooth(self,x,**kwargs):
        """
            Raises an error since smoothing is ill-defined on an unstructured
            space.
        """
        raise AttributeError(about._errors.cstring("ERROR: smoothing ill-defined for (unstructured) point space."))

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

    def calc_power(self,x,**kwargs):
        """
            Raises an error since the power spectrum is ill-defined for point
            spaces.
        """
        raise AttributeError(about._errors.cstring("ERROR: power spectra ill-defined for (unstructured) point space."))

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

    def get_plot(self,x,title="",vmin=None,vmax=None,unit="",norm=None,other=None,legend=False,**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)``).
            unit : string, *optional*
                Unit of the field values (default: "").
            norm : string, *optional*
                Scaling of the field values before plotting (default: None).
            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).
        """
        if(not pl.isinteractive()):
            about.warnings.cprint("WARNING: interactive mode off.")

        x = self.enforce_shape(np.array(x,dtype=self.datatype))

        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):
            if(np.iscomplexobj(x)):
                vmin = min(np.min(np.absolute(x),axis=None,out=None),np.min(np.real(x),axis=None,out=None),np.min(np.imag(x),axis=None,out=None))
            else:
                vmin = np.min(x,axis=None,out=None)
        if(vmax is None):
            if(np.iscomplexobj(x)):
                vmax = max(np.max(np.absolute(x),axis=None,out=None),np.max(np.real(x),axis=None,out=None),np.max(np.imag(x),axis=None,out=None))
            else:
                vmax = np.max(x,axis=None,out=None)

        if(norm=="log")and(vmin<=0):
            raise ValueError(about._errors.cstring("ERROR: nonpositive value(s)."))

        if(np.iscomplexobj(x)):
            ax0.scatter(xaxes,np.absolute(x),s=20,color=[0.0,0.5,0.0],marker='o',cmap=None,norm=None,vmin=None,vmax=None,alpha=None,label="graph (absolute)",linewidths=None,verts=None,zorder=1)
            ax0.scatter(xaxes,np.real(x),s=20,color=[0.0,0.5,0.0],marker='s',cmap=None,norm=None,vmin=None,vmax=None,alpha=None,label="graph (real part)",linewidths=None,verts=None,facecolor="none",zorder=1)
            ax0.scatter(xaxes,np.imag(x),s=20,color=[0.0,0.5,0.0],marker='D',cmap=None,norm=None,vmin=None,vmax=None,alpha=None,label="graph (imaginary part)",linewidths=None,verts=None,facecolor="none",zorder=1)
            if(legend):
                ax0.legend()
        elif(other is not None):
            ax0.scatter(xaxes,x,s=20,color=[0.0,0.5,0.0],marker='o',cmap=None,norm=None,vmin=None,vmax=None,alpha=None,label="graph 0",linewidths=None,verts=None,zorder=1)
            if(isinstance(other,tuple)):
                other = [self.enforce_values(xx,extend=True) for xx in other]
            else:
                other = [self.enforce_values(other,extend=True)]
            imax = max(1,len(other)-1)
            for ii in range(len(other)):
                ax0.scatter(xaxes,other[ii],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,label="graph "+str(ii),linewidths=None,verts=None,zorder=-ii)
            if(legend):
                ax0.legend()
        else:
            ax0.scatter(xaxes,x,s=20,color=[0.0,0.5,0.0],marker='o',cmap=None,norm=None,vmin=None,vmax=None,alpha=None,label="graph 0",linewidths=None,verts=None,zorder=1)

        ax0.set_xlim(xaxes[0],xaxes[-1])
        ax0.set_xlabel("index")
        ax0.set_ylim(vmin,vmax)
        if(norm=="log"):
            ax0.set_yscale('log')

        if(unit):
            unit = " ["+unit+"]"
        ax0.set_ylabel("values"+unit)
        ax0.set_title(title)


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

    def __repr__(self):
        return "<nifty.point_space>"

    def __str__(self):
        return "nifty.point_space instance\n- num      = "+str(self.para[0])+"\n- datatype = numpy."+str(np.result_type(self.datatype))

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



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

class rg_space(space):
    """
        ..      _____   _______
        ..    /   __/ /   _   /
        ..   /  /    /  /_/  /
        ..  /__/     \____  /  space class
        ..           /_____/

        NIFTY subclass for spaces of regular Cartesian grids.

        Parameters
        ----------
        num : {int, numpy.ndarray}
            Number of gridpoints or numbers of gridpoints along each axis.
        naxes : int, *optional*
            Number of axes (default: None).
        zerocenter : {bool, numpy.ndarray}, *optional*
            Whether the Fourier zero-mode is located in the center of the grid
            (or the center of each axis speparately) or not (default: True).
        hermitian : bool, *optional*
            Whether the fields living in the space follow hermitian symmetry or
            not (default: True).
        purelyreal : bool, *optional*
            Whether the field values are purely real (default: True).
        dist : {float, numpy.ndarray}, *optional*
            Distance between two grid points along each axis (default: None).
        fourier : bool, *optional*
            Whether the space represents a Fourier or a position grid
            (default: False).

        Notes
        -----
        Only even numbers of grid points per axis are supported.

        Attributes
        ----------
        para : numpy.ndarray
            One-dimensional array containing information on the axes of the
            space in the following form: The first entries give the grid-points
            along each axis in reverse order; the next entry is 0 if the
            fields defined on the space are purely real-valued, 1 if they are
            hermitian and complex, and 2 if they are not hermitian, but
            complex-valued; the last entries hold the information on whether
            the axes are centered on zero or not, containing a one for each
            zero-centered axis and a zero for each other one, in reverse order.
        datatype : numpy.dtype
            Data type of the field values for a field defined on this space,
            either ``numpy.float64`` or ``numpy.complex128``.
        discrete : bool
            Whether or not the underlying space is discrete, always ``False``
            for regular grids.
        vol : numpy.ndarray
            One-dimensional array containing the distances between two grid
            points along each axis, in reverse order. By default, the total
            length of each axis is assumed to be one.
        fourier : bool
            Whether or not the grid represents a Fourier basis.
    """
    epsilon = 0.0001 ## relative precision for comparisons

    def __init__(self,num,naxes=None,zerocenter=True,hermitian=True,purelyreal=True,dist=None,fourier=False):
        """
            Sets the attributes for an rg_space class instance.

            Parameters
            ----------
            num : {int, numpy.ndarray}
                Number of gridpoints or numbers of gridpoints along each axis.
            naxes : int, *optional*
                Number of axes (default: None).
            zerocenter : {bool, numpy.ndarray}, *optional*
                Whether the Fourier zero-mode is located in the center of the
                grid (or the center of each axis speparately) or not
                (default: True).
            hermitian : bool, *optional*
                Whether the fields living in the space follow hermitian
                symmetry or not (default: True).
            purelyreal : bool, *optional*
                Whether the field values are purely real (default: True).
            dist : {float, numpy.ndarray}, *optional*
                Distance between two grid points along each axis
                (default: None).
            fourier : bool, *optional*
                Whether the space represents a Fourier or a position grid
                (default: False).

            Returns
            -------
            None
        """
        ## check parameters
        para = np.array([],dtype=np.int)
        if(np.isscalar(num)):
            num = np.array([num],dtype=np.int)
        else:
            num = np.array(num,dtype=np.int)
        if(np.any(num%2)): ## module restriction
            raise ValueError(about._errors.cstring("ERROR: unsupported odd number of grid points."))
        if(naxes is None):
            naxes = np.size(num)
        elif(np.size(num)==1):
            num = num*np.ones(naxes,dtype=np.int,order='C')
        elif(np.size(num)!=naxes):
            raise ValueError(about._errors.cstring("ERROR: size mismatch ( "+str(np.size(num))+" <> "+str(naxes)+" )."))
        para = np.append(para,num[::-1],axis=None)
        para = np.append(para,2-(bool(hermitian) or bool(purelyreal))-bool(purelyreal),axis=None) ## {0,1,2}
        if(np.isscalar(zerocenter)):
            zerocenter = bool(zerocenter)*np.ones(naxes,dtype=np.int,order='C')
        else:
            zerocenter = np.array(zerocenter,dtype=np.bool)
            if(np.size(zerocenter)==1):
                zerocenter = zerocenter*np.ones(naxes,dtype=np.int,order='C')
            elif(np.size(zerocenter)!=naxes):
                raise ValueError(about._errors.cstring("ERROR: size mismatch ( "+str(np.size(zerocenter))+" <> "+str(naxes)+" )."))
        para = np.append(para,zerocenter[::-1]*-1,axis=None) ## -1 XOR 0 (centered XOR not)

        self.para = para

        ## set data type
        if(not self.para[naxes]):
            self.datatype = np.float64
        else:
            self.datatype = np.complex128

        self.discrete = False

        ## set volume
        if(dist is None):
            dist = 1/num.astype(self.datatype)
        elif(np.isscalar(dist)):
            dist = self.datatype(dist)*np.ones(naxes,dtype=self.datatype,order='C')
        else:
            dist = np.array(dist,dtype=self.datatype)
            if(np.size(dist)==1):
                dist = dist*np.ones(naxes,dtype=self.datatype,order='C')
            if(np.size(dist)!=naxes):
                raise ValueError(about._errors.cstring("ERROR: size mismatch ( "+str(np.size(dist))+" <> "+str(naxes)+" )."))
        if(np.any(dist<=0)):
            raise ValueError(about._errors.cstring("ERROR: nonpositive distance(s)."))
        self.vol = np.real(dist)[::-1]

        self.fourier = bool(fourier)

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

    def naxes(self):
        """
            Returns the number of axes of the grid.

            Returns
            -------
            naxes : int
                Number of axes of the regular grid.
        """
        return (np.size(self.para)-1)//2

    def zerocenter(self):
        """
            Returns information on the centering of the axes.

            Returns
            -------
            zerocenter : numpy.ndarray
                Whether the grid is centered on zero for each axis or not.
        """
        return self.para[-(np.size(self.para)-1)//2:][::-1].astype(np.bool)

    def dist(self):
        """
            Returns the distances between grid points along each axis.

            Returns
            -------
            dist : np.ndarray
                Distances between two grid points on each axis.
        """
        return self.vol[::-1]

    def dim(self,split=False):
        """
            Computes the dimension of the space, i.e.\  the number of pixels.

            Parameters
            ----------
            split : bool, *optional*
                Whether to return the dimension split up, i.e. the numbers of
                pixels along each axis, or their product (default: False).

            Returns
            -------
            dim : {int, numpy.ndarray}
                Dimension(s) of the space. If ``split==True``, a
                one-dimensional array with an entry for each axis is returned.
        """
        ## dim = product(n)
        if(split):
            return self.para[:(np.size(self.para)-1)//2]
        else:
            return np.prod(self.para[:(np.size(self.para)-1)//2],axis=0,dtype=None,out=None)

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

    def dof(self):
        """
            Computes the number of degrees of freedom of the space, i.e.\  the
            number of grid points multiplied with one or two, depending on
            complex-valuedness and hermitian symmetry of the fields.

            Returns
            -------
            dof : int
                Number of degrees of freedom of the space.
        """
        ## dof ~ dim
        if(self.para[(np.size(self.para)-1)//2]<2):
            return np.prod(self.para[:(np.size(self.para)-1)//2],axis=0,dtype=None,out=None)
        else:
            return 2*np.prod(self.para[:(np.size(self.para)-1)//2],axis=0,dtype=None,out=None)

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

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

            Parameters
            ----------
            spec : {float, numpy.ndarray, nifty.field}
                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.

            Other parameters
            ----------------
            size : int, *optional*
                Number of bands the power spectrum shall have (default: None).
2365
2366
            kindex : numpy.ndarray, *optional*
                Scale of each band.
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
            codomain : nifty.space, *optional*
                A compatible codomain for power indexing (default: None).
            log : bool, *optional*
                Flag specifying if the spectral binning is performed on logarithmic
                scale or not; if set, the number of used bins is set
                automatically (if not given otherwise); by default no binning
                is done (default: None).
            nbin : integer, *optional*
                Number of used spectral bins; if given `log` is set to ``False``;
                integers below the minimum of 3 induce an automatic setting;
                by default no binning is done (default: None).
            binbounds : {list, array}, *optional*
                User specific inner boundaries of the bins, which are preferred
                over the above parameters; by default no binning is done
                (default: None).            vmin : {scalar, list, ndarray, field}, *optional*
                Lower limit of the uniform distribution if ``random == "uni"``
                (default: 0).
2384

Marco Selig's avatar
Marco Selig committed
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
        """
        if(isinstance(spec,field)):
            spec = spec.val.astype(self.datatype)
        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)