nifty_core.py 435 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
    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.

51
52
53
54
55
56
57
    References
    ----------
    .. [#] Selig et al., "NIFTY -- Numerical Information Field Theory --
        a versatile Python library for signal inference",
        `A&A, vol. 554, id. A26 <http://dx.doi.org/10.1051/0004-6361/201321236>`_,
        2013; `arXiv:1301.4499 <http://www.arxiv.org/abs/1301.4499>`_

Marco Selig's avatar
Marco Selig committed
58
59
60
61
62
63
    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.

64
65
    .. Overview of all (core) classes:
    ..
Marco Selig's avatar
Marco Selig committed
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
    .. - 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

88
89
    Overview of the main classes and functions:

Marco Selig's avatar
Marco Selig committed
90
91
    .. automodule:: nifty

92
93
94
95
96
97
98
99
100
101
102
103
104
105
    - :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`
Marco Selig's avatar
Marco Selig committed
106

107
        .. currentmodule:: nifty.nifty_tools
Marco Selig's avatar
Marco Selig committed
108

109
110
        - :py:class:`invertible_operator`
        - :py:class:`propagator_operator`
Marco Selig's avatar
Marco Selig committed
111

112
        .. currentmodule:: nifty.nifty_explicit
Marco Selig's avatar
Marco Selig committed
113

114
        - :py:class:`explicit_operator`
Marco Selig's avatar
Marco Selig committed
115

116
    .. automodule:: nifty
Marco Selig's avatar
Marco Selig committed
117

118
119
120
    - :py:class:`probing`
        - :py:class:`trace_probing`
        - :py:class:`diagonal_probing`
Marco Selig's avatar
Marco Selig committed
121

122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
        .. currentmodule:: nifty.nifty_explicit

        - :py:class:`explicit_probing`

    .. currentmodule:: nifty.nifty_tools

    - :py:class:`conjugate_gradient`
    - :py:class:`steepest_descent`

    .. currentmodule:: nifty.nifty_explicit

    - :py:func:`explicify`

    .. currentmodule:: nifty.nifty_power

    - :py:func:`weight_power`,
      :py:func:`smooth_power`,
      :py:func:`infer_power`,
      :py:func:`interpolate_power`
Marco Selig's avatar
Marco Selig committed
141
142
143
144
145
146

"""
from __future__ import division
import os
from sys import stdout as so
import numpy as np
Marco Selig's avatar
Marco Selig committed
147
148
import pylab as pl
from multiprocessing import Pool as mp
149
150
from multiprocessing import Value as mv
from multiprocessing import Array as ma
ultimanet's avatar
ultimanet committed
151
from nifty_mpi_data import distributed_data_object
152
153
154
from nifty_paradict import space_paradict,\
                            point_space_paradict,\
                            nested_space_paradict
155
__version__ = "1.0.7"
Marco Selig's avatar
Marco Selig committed
156

Marco Selig's avatar
Marco Selig committed
157

Marco Selig's avatar
Marco Selig committed
158
pi = 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679
159

Marco Selig's avatar
Marco Selig committed
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510

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

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
511
        self._version = str(__version__)
Marco Selig's avatar
Marco Selig committed
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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657

        ## 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).
Marco Selig's avatar
Marco Selig committed
658
            spec : {scalar, list, array, field, function}, *optional*
Marco Selig's avatar
Marco Selig committed
659
660
661
662
                Power spectrum for ``random == "syn"`` (default: 1).
            size : integer, *optional*
                Number of irreducible bands for ``random == "syn"``
                (default: None).
663
664
665
666
667
            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
668
669
670
671
672
673
674
675
676
677
            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).

678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
            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
698
699
700
701
702
703
            Raises
            ------
            KeyError
                If the `random` key is not supporrted.

        """
Marco Selig's avatar
Marco Selig committed
704
        if("random" in kwargs):
Marco Selig's avatar
Marco Selig committed
705
706
707
708
709
710
711
712
            key = kwargs.get("random")
        else:
            return None

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

        elif(key=="gau"):
Marco Selig's avatar
Marco Selig committed
713
            if("mean" in kwargs):
Marco Selig's avatar
Marco Selig committed
714
715
716
                mean = domain.enforce_values(kwargs.get("mean"),extend=False)
            else:
                mean = None
Marco Selig's avatar
Marco Selig committed
717
            if("dev" in kwargs):
Marco Selig's avatar
Marco Selig committed
718
719
720
                dev = domain.enforce_values(kwargs.get("dev"),extend=False)
            else:
                dev = None
Marco Selig's avatar
Marco Selig committed
721
            if("var" in kwargs):
Marco Selig's avatar
Marco Selig committed
722
723
724
725
726
727
                var = domain.enforce_values(kwargs.get("var"),extend=False)
            else:
                var = None
            return [key,mean,dev,var]

        elif(key=="syn"):
728
            ## explicit power indices
Marco Selig's avatar
Marco Selig committed
729
            if("pindex" in kwargs)and("kindex" in kwargs):
730
731
732
733
734
735
736
737
738
739
740
                kindex = kwargs.get("kindex")
                if(kindex is None):
                    spec = domain.enforce_power(kwargs.get("spec",1),size=kwargs.get("size",None))
                    kpack = None
                else:
                    spec = domain.enforce_power(kwargs.get("spec",1),size=len(kindex),kindex=kindex)
                    pindex = kwargs.get("pindex",None)
                    if(pindex is None):
                        kpack = None
                    else:
                        kpack = [pindex,kindex]
741
            ## implicit power indices
742
            else:
743
744
745
                try:
                    domain.set_power_indices(**kwargs)
                except:
746
747
748
749
750
                    codomain = kwargs.get("codomain",None)
                    if(codomain is None):
                        spec = domain.enforce_power(kwargs.get("spec",1),size=kwargs.get("size",None))
                        kpack = None
                    else:
751
752
                        domain.check_codomain(codomain)
                        codomain.set_power_indices(**kwargs)
753
754
755
                        kindex = codomain.power_indices.get("kindex")
                        spec = domain.enforce_power(kwargs.get("spec",1),size=len(kindex),kindex=kindex,codomain=codomain)
                        kpack = [codomain.power_indices.get("pindex"),kindex]
756
                else:
757
                    kindex = domain.power_indices.get("kindex")
758
                    spec = domain.enforce_power(kwargs.get("spec",1),size=len(kindex),kindex=kindex)
759
                    kpack = [domain.power_indices.get("pindex"),kindex]
760
            return [key,spec,kpack]
Marco Selig's avatar
Marco Selig committed
761
762

        elif(key=="uni"):
Marco Selig's avatar
Marco Selig committed
763
            if("vmin" in kwargs):
Marco Selig's avatar
Marco Selig committed
764
765
766
                vmin = domain.enforce_values(kwargs.get("vmin"),extend=False)
            else:
                vmin = 0
Marco Selig's avatar
Marco Selig committed
767
            if("vmax" in kwargs):
Marco Selig's avatar
Marco Selig committed
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
                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)

799
        if(issubclass(datatype,np.complexfloating)):
Marco Selig's avatar
Marco Selig committed
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
            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)

841
        if(issubclass(datatype,np.complexfloating)):
Marco Selig's avatar
Marco Selig committed
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
            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):
918
        return "<nifty_core.random>"
Marco Selig's avatar
Marco Selig committed
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966

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





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

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

        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
        """
1001
        self.paradict = space_paradict(default=para)        
Marco Selig's avatar
Marco Selig committed
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012

        ## 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))
1013
        
1014
1015
1016
1017
1018
1019
1020
1021
    @property
    def para(self):
        return self.paradict['default']
    
    @para.setter
    def para(self, x):
        self.paradict['default'] = x

1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    def _freeze_config(self, dictionary):
        """
            a helper function which forms a hashable identifying object from 
            a dictionary which can be used as key of a dict
        """        
        return frozenset(dictionary.items())



    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1033
    def getitem(self, data, key):
1034
1035
        raise NotImplementedError(about._errors.cstring("ERROR: no generic instance method 'getitem'."))
        
Marco Selig's avatar
Marco Selig committed
1036
1037

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1038
    def setitem(self, data, key):
1039
1040
1041
1042
1043
1044
1045
1046
1047
        raise NotImplementedError(about._errors.cstring("ERROR: no generic instance method 'getitem'."))
        
    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++            
    def unary_operation(self, x, op=None):
        raise NotImplementedError(about._errors.cstring("ERROR: no generic instance method 'unary_operation'."))

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++            
    def binary_operation(self, x, y, op=None):
        raise NotImplementedError(about._errors.cstring("ERROR: no generic instance method 'binary_operation'."))
Marco Selig's avatar
Marco Selig committed
1048

1049
1050
1051
1052
    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++            
    def norm(self, x, q):
        raise NotImplementedError(about._errors.cstring("ERROR: no generic instance method 'norm'."))

1053
1054
    def shape(self):
        raise NotImplementedError(about._errors.cstring("ERROR: no generic instance method 'shape'."))
1055
1056

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Marco Selig's avatar
Marco Selig committed
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
    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.
        """
1072
        raise NotImplementedError(about._errors.cstring("ERROR: no generic instance method 'dim'."))
Marco Selig's avatar
Marco Selig committed
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084

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

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

            Returns
            -------
            dof : int
                Number of degrees of freedom of the space.
        """
1085
        raise NotImplementedError(about._errors.cstring("ERROR: no generic instance method 'dof'."))
Marco Selig's avatar
Marco Selig committed
1086
1087
1088
1089
1090
1091
1092
1093
1094

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

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

            Parameters
            ----------
Marco Selig's avatar
Marco Selig committed
1095
            spec : {scalar, list, numpy.ndarray, nifty.field, function}
Marco Selig's avatar
Marco Selig committed
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
                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).
1109
1110
            kindex : numpy.ndarray, *optional*
                Scale of each band.
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
            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).
1128

Marco Selig's avatar
Marco Selig committed
1129
        """
1130
        raise NotImplementedError(about._errors.cstring("ERROR: no generic instance method 'enforce_power'."))
Marco Selig's avatar
Marco Selig committed
1131
1132
1133

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

1134
    def set_power_indices(self,**kwargs):
Marco Selig's avatar
Marco Selig committed
1135
        """
1136
1137
1138
1139
1140
1141
            Sets the (un)indexing objects for spectral indexing internally.

            Parameters
            ----------
            log : bool
                Flag specifying if the binning is performed on logarithmic
1142
1143
1144
                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).
1145
            nbin : integer
1146
1147
                Number of used bins; if given `log` is set to ``False``;
                integers below the minimum of 3 induce an automatic setting;
1148
1149
                by default no binning is done (default: None).
            binbounds : {list, array}
1150
1151
1152
                User specific inner boundaries of the bins, which are preferred
                over the above parameters; by default no binning is done
                (default: None).
1153
1154
1155
1156
1157

            Returns
            -------
            None

1158
            See Also
1159
1160
            --------
            get_power_indices
Marco Selig's avatar
Marco Selig committed
1161
1162

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

1165
1166
1167
    def get_power_indices(self,**kwargs):
        """
            Provides the (un)indexing objects for spectral indexing.
1168

1169
1170
1171
            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
Marco Selig's avatar
Marco Selig committed
1172
            power spectrum as well as an Unindexing array.
1173
1174
1175
1176
1177

            Parameters
            ----------
            log : bool
                Flag specifying if the binning is performed on logarithmic
1178
1179
1180
                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).
1181
            nbin : integer
1182
1183
                Number of used bins; if given `log` is set to ``False``;
                integers below the minimum of 3 induce an automatic setting;
1184
1185
                by default no binning is done (default: None).
            binbounds : {list, array}
1186
1187
1188
                User specific inner boundaries of the bins, which are preferred
                over the above parameters; by default no binning is done
                (default: None).
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198

            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.
Marco Selig's avatar
Marco Selig committed
1199
1200
            pundex : numpy.ndarray
                Unindexing array undoing power spectrum indexing.
1201
1202
1203
1204
1205
1206

            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.
Marco Selig's avatar
Marco Selig committed
1207
1208
            Indexing with the unindexing array undoes the indexing with the
            indexing array; i.e., ``power == power[pindex].flatten()[pundex]``.
1209

1210
            See Also
1211
1212
1213
1214
            --------
            set_power_indices

        """
1215
1216
1217
1218
        raise NotImplementedError(about._errors.cstring("ERROR: no generic instance method 'get_power_indices'."))

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
    def cast(self, x, verbose=False):
        """
            Computes valid field values from a given object, trying
            to translate the given data into a valid form. Thereby it is as 
            benevolent as possible. 

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

            Returns
            -------
            x : numpy.ndarray, distributed_data_object
                Array containing the field values, which are compatible to the
                space.

            Other parameters
            ----------------
            verbose : bool, *optional*
                Whether the method should raise a warning if information is 
                lost during casting (default: False).
        """
        return self.enforce_values(x, extend=True)
1243

Marco Selig's avatar
Marco Selig committed
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    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.
        """
1261
        raise NotImplementedError(about._errors.cstring("ERROR: no generic instance method 'enforce_shape'."))
Marco Selig's avatar
Marco Selig committed
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285

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

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


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

    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).
Marco Selig's avatar
Marco Selig committed
1320
            spec : {scalar, list, numpy.ndarray, nifty.field, function}, *optional*
Marco Selig's avatar
Marco Selig committed
1321
                Power spectrum (default: 1).
1322
1323
1324
1325
1326
            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).
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
            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
1344
1345
1346
1347
1348
            vmin : float, *optional*
                Lower limit for a uniform distribution (default: 0).
            vmax : float, *optional*
                Upper limit for a uniform distribution (default: 1).
        """
1349
        raise NotImplementedError(about._errors.cstring("ERROR: no generic instance method 'get_random_values'."))
Marco Selig's avatar
Marco Selig committed
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366

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

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

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

    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.
        """
1394
        raise NotImplementedError(about._errors.cstring("ERROR: no generic instance method 'get_codomain'."))
Marco Selig's avatar
Marco Selig committed
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417

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

    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.
        """
1418
        raise NotImplementedError(about._errors.cstring("ERROR: no generic instance method 'get_meta_volume'."))
Marco Selig's avatar
Marco Selig committed
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438

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

    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.
        """
1439
        raise NotImplementedError(about._errors.cstring("ERROR: no generic instance method 'calc_weight'."))
Marco Selig's avatar
Marco Selig committed
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456

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

    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
            -------
1457
            dot : scalar
Marco Selig's avatar
Marco Selig committed
1458
1459
                Inner product of the two arrays.
        """
1460
1461
1462
1463
        raise NotImplementedError(about._errors.cstring(\
            "ERROR: no generic instance method 'dot'."))


Marco Selig's avatar
Marco Selig committed
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

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

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

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

    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).
        """
1516
        raise NotImplementedError(about._errors.cstring("ERROR: no generic instance method 'calc_smooth'."))
Marco Selig's avatar
Marco Selig committed
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539

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

    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).
1540
1541
1542
            kindex : numpy.ndarray, *optional*
                Scale corresponding to each band in the power spectrum
                (default: None).
Marco Selig's avatar
Marco Selig committed
1543
1544
            rho : numpy.ndarray, *optional*
                Number of degrees of freedom per band (default: None).
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
            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
1563
        """
1564
        raise NotImplementedError(about._errors.cstring("ERROR: no generic instance method 'calc_power'."))
Marco Selig's avatar
Marco Selig committed
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607

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

    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).
1608
1609
1610
            save : string, *optional*
                Valid file name where the figure is to be stored, by default
                the figure is not saved (default: False).
Marco Selig's avatar
Marco Selig committed
1611
1612
1613
1614
1615
1616
            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).
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
            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
1634
1635
            iter : int, *optional*
                Number of iterations (default: 0).
1636

Marco Selig's avatar
Marco Selig committed
1637
        """
1638
        raise NotImplementedError(about._errors.cstring("ERROR: no generic instance method 'get_plot'."))
Marco Selig's avatar
Marco Selig committed
1639
1640
1641
1642

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

    def __repr__(self):
1643
        return "<nifty_core.space>"
Marco Selig's avatar
Marco Selig committed
1644
1645

    def __str__(self):
1646
        return "nifty_core.space instance\n- para     = "+str(self.para)+"\n- datatype = numpy."+str(np.result_type(self.datatype))
Marco Selig's avatar
Marco Selig committed
1647
1648
1649
1650
1651
1652

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

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

ultimanet's avatar
ultimanet committed
1653
1654
1655
1656
1657
1658
    ## __identiftier__ returns an object which contains all information needed 
    ## to uniquely idetnify a space. It returns a (immutable) tuple which therefore
    ## can be compored. 
    def __identifier__(self):
        return tuple(sorted(vars(self).items()))

Marco Selig's avatar
Marco Selig committed
1659
1660
1661
    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    def _meta_vars(self): ## > captures all nonstandard properties
1662
        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
1663
1664
1665
1666
1667
1668
1669
        if(np.size(mars)==0):
            return None
        else:
            return mars

    def __eq__(self,x): ## __eq__ : self == x
        if(isinstance(x,space)):
1670
            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
1671
1672
1673
1674
1675
                return True
        return False

    def __ne__(self,x): ## __ne__ : self <> x
        if(isinstance(x,space)):
1676
            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
1677
1678
1679
1680
1681
                return True
        return False

    def __lt__(self,x): ## __lt__ : self < x
        if(isinstance(x,space)):
1682
            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
1683
                raise ValueError(about._errors.cstring("ERROR: incomparable spaces."))
1684
            elif(self.discrete==x.discrete): ## data types are ignored
1685
                for ii in xrange(np.size(self.para)):
Marco Selig's avatar
Marco Selig committed
1686
1687
1688
1689
                    if(self.para[ii]<x.para[ii]):
                        return True
                    elif(self.para[ii]>x.para[ii]):
                        return False
1690
                for ii in xrange(np.size(self.vol)):
1691
1692
1693
1694
                    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
1695
1696
                s_mars = self._meta_vars()
                x_mars = x._meta_vars()
1697
                for ii in xrange(np.size(s_mars)):
Marco Selig's avatar
Marco Selig committed
1698
1699
1700
1701
1702
1703
1704
1705
                    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)):
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
1708
                raise ValueError(about._errors.cstring("ERROR: incomparable spaces."))
            elif(self.discrete==x.discrete): ## data types are ignored
1709
                for ii in xrange(np.size(self.para)):
Marco Selig's avatar
Marco Selig committed
1710
1711
1712
1713
                    if(self.para[ii]<x.para[ii]):
                        return True
                    if(self.para[ii]>x.para[ii]):
                        return False
1714
                for ii in xrange(np.size(self.vol)):
1715
1716
1717
1718
                    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
1719
1720
                s_mars = self._meta_vars()
                x_mars = x._meta_vars()
1721
                for ii in xrange(np.size(s_mars)):
Marco Selig's avatar
Marco Selig committed
1722
1723
1724
1725
1726
1727
1728
1729
1730
                    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)):
1731
            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
1732
1733
                raise ValueError(about._errors.cstring("ERROR: incomparable spaces."))
            elif(self.discrete==x.discrete): ## data types are ignored
1734
                for ii in xrange(np.size(self.para)):
Marco Selig's avatar
Marco Selig committed
1735
1736
1737
1738
                    if(self.para[ii]>x.para[ii]):
                        return True
                    elif(self.para[ii]<x.para[ii]):
                        break
1739
                for ii in xrange(np.size(self.vol)):
1740
1741
1742
1743
                    if(self.vol[ii]>x.vol[ii]):
                        return True
                    elif(self.vol[ii]<x.vol[ii]):
                        break
Marco Selig's avatar
Marco Selig committed
1744
1745
                s_mars = self._meta_vars()
                x_mars = x._meta_vars()
1746
                for ii in xrange(np.size(s_mars)):
Marco Selig's avatar
Marco Selig committed
1747
1748
1749
1750
1751
1752
1753
1754
                    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)):
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
                raise ValueError(about._errors.cstring("ERROR: incomparable spaces."))
            elif(self.discrete==x.discrete): ## data types are ignored
1758
                for ii in xrange(np.size(self.para)):
Marco Selig's avatar
Marco Selig committed
1759
1760
1761
1762
                    if(self.para[ii]>x.para[ii]):
                        return True
                    if(self.para[ii]<x.para[ii]):
                        return False
1763
                for ii in xrange(np.size(self.vol)):
1764
1765
1766
1767
                    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
1768
1769
                s_mars = self._meta_vars()
                x_mars = x._meta_vars()
1770
                for ii in xrange(np.size(s_mars)):
Marco Selig's avatar
Marco Selig committed
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
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
                    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.
        """
1833
1834
        self.paradict = point_space_paradict(num=num)       
        
Marco Selig's avatar
Marco Selig committed
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
        ## 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))


1847
1848
1849
1850
1851
1852
1853
1854
1855
    @property
    def para(self):
        temp = np.array([self.paradict['num']], dtype=int)
        return temp
    
    @para.setter
    def para(self, x):
        self.paradict['num'] = x
        
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    def getitem(self, data, key):
        return data[key]
        

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    def setitem(self, data, update, key):
        data[key]=update
           
    
    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++          
    
    
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
    def unary_operation(self, x, op='None', **kwargs):
        """
        x must be a numpy array which is compatible with the space!
        Valid operations are
        
        """
                                
        def _argmin(z, **kwargs):
            ind = np.argmin(z, **kwargs)
            if np.isscalar(ind):
                ind = np.unravel_index(ind, z.shape, order='C')
                if(len(ind)==1):
                    return ind[0]
            return ind         

        def _argmax(z, **kwargs):
            ind = np.argmax(z, **kwargs)
            if np.isscalar(ind):
                ind = np.unravel_index(ind, z.shape, order='C')
                if(len(ind)==1):
                    return ind[0]
            return ind         
        
        
        translation = {"pos" : lambda y: getattr(y, '__pos__')(),
                        "neg" : lambda y: getattr(y, '__neg__')(),
                        "abs" : lambda y: getattr(y, '__abs__')(),
                        "nanmin" : np.nanmin,  
                        "min" : np.amin,
                        "nanmax" : np.nanmax,
                        "max" : np.amax,
                        "med" : np.median,
                        "mean" : np.mean,
                        "std" : np.std,
                        "var" : np.var,
                        "argmin" : _argmin,
                        "argmin_flat" : np.argmin,
                        "argmax" : _argmax, 
                        "argmax_flat" : np.argmax,
                        "conjugate" : np.conjugate,
                        "None" : lambda y: y}

                
        return translation[op](x, **kwargs)      

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++            
    def binary_operation(self, x, y, op='None', cast=0):
        
        translation = {"add" : lambda z: getattr(z, '__add__'),
                        "iadd" : lambda z: getattr(z, '__iadd__'),
                        "sub" : lambda z: getattr(z, '__sub__'),
                        "rsub" : lambda z: getattr(z, '__rsub__'),
                        "isub" : lambda z: getattr(z, '__isub__'),
                        "mul" : lambda z: getattr(z, '__mul__'),
                        "imul" : lambda z: getattr(z, '__imul__'),
                        "div" : lambda z: getattr(z, '__div__'),
                        "rdiv" : lambda z: getattr(z, '__rdiv__'),
                        "idiv" : lambda z: getattr(z, '__idiv__'),
                        "pow" : lambda z: getattr(z, '__pow__'),
                        "rpow" : lambda z: getattr(z, '__rpow__'),
                        "ipow" : lambda z: getattr(z, '__ipow__'),
                        "None" : lambda z: lambda u: u}
        
        if (cast & 1) != 0:
            x = self.cast(x)
        if (cast & 2) != 0:
            y = self.cast(y)        
        
        return translation[op](x)(y)

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++            
    def norm(self, x, q=2):
        """
            Computes the Lq-norm of field values.

            Parameters
            ----------
            x : np.ndarray 
                The data array 
            q : scalar
                Parameter q of the Lq-norm (default: 2).

            Returns
            -------
            norm : scalar
                The Lq-norm of the field values.

        """

        
        if(q == 2):
            result = self.calc_dot(x,x)
        else:
            y = x**(q-1)        
            result = self.calc_dot(x,y)
        
        result = result**(1./q)
        return result 



    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Marco Selig's avatar
Marco Selig committed
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
    def num(self):
        """
            Returns the number of points.

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

1982
1983
1984
1985
    def shape(self):
        return np.array([self.paradict['num']])

        
Marco Selig's avatar
Marco Selig committed
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
    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):