space.py 51.4 KB
Newer Older
1
2
# NIFTY (Numerical Information Field Theory) has been developed at the
# Max-Planck-Institute for Astrophysics.
Marco Selig's avatar
Marco Selig committed
3
##
4
# Copyright (C) 2013 Max-Planck-Society
Marco Selig's avatar
Marco Selig committed
5
##
6
7
# Author: Marco Selig
# Project homepage: <http://www.mpa-garching.mpg.de/ift/nifty/>
Marco Selig's avatar
Marco Selig committed
8
##
9
10
11
12
# 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.
Marco Selig's avatar
Marco Selig committed
13
##
14
15
16
17
# 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.
Marco Selig's avatar
Marco Selig committed
18
##
19
20
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
Marco Selig's avatar
Marco Selig committed
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

"""
    ..                  __   ____   __
    ..                /__/ /   _/ /  /_
    ..      __ ___    __  /  /_  /   _/  __   __
    ..    /   _   | /  / /   _/ /  /   /  / /  /
    ..   /  / /  / /  / /  /   /  /_  /  /_/  /
    ..  /__/ /__/ /__/ /__/    \___/  \___   /  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

"""
from __future__ import division
import numpy as np
Marco Selig's avatar
Marco Selig committed
145
import pylab as pl
146

147
148
149
from d2o import distributed_data_object,\
                STRATEGIES as DISTRIBUTION_STRATEGIES

150
from nifty_paradict import space_paradict,\
151
    point_space_paradict
Ultimanet's avatar
Ultimanet committed
152

csongor's avatar
csongor committed
153
from nifty.config import about
154

Ultimanet's avatar
Ultimanet committed
155
from nifty_random import random
Marco Selig's avatar
Marco Selig committed
156

157
POINT_DISTRIBUTION_STRATEGIES = DISTRIBUTION_STRATEGIES['global']
Marco Selig's avatar
Marco Selig committed
158

Ultimanet's avatar
Ultimanet committed
159

theos's avatar
theos 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
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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
#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
#        ----------
#        dtype : numpy.dtype, *optional*
#            Data type of the field values for a field defined on this space
#            (default: numpy.float64).
#        datamodel :
#
#        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.
#        .. [#] M. Reinecke and D. Sverre Seljebotn, 2013, "Libsharp - spherical
#               harmonic transforms revisited";
#               `arXiv:1303.4945 <http://www.arxiv.org/abs/1303.4945>`_
#
#        Attributes
#        ----------
#        para : {single object, list of objects}
#            This is a freeform list of parameters that derivatives of the space
#            class can use.
#        dtype : 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):
#        """
#            Sets the attributes for a space class instance.
#
#            Parameters
#            ----------
#            dtype : numpy.dtype, *optional*
#                Data type of the field values for a field defined on this space
#                (default: numpy.float64).
#            datamodel :
#
#            Returns
#            -------
#            None
#        """
#        self.paradict = space_paradict()
#
#    @property
#    def para(self):
#        return self.paradict['default']
#
#    @para.setter
#    def para(self, x):
#        self.paradict['default'] = x
#
#    def __hash__(self):
#        return hash(())
#
#    def _identifier(self):
#        """
#        _identiftier returns an object which contains all information needed
#        to uniquely idetnify a space. It returns a (immutable) tuple which
#        therefore can be compared.
#        """
#        return tuple(sorted(vars(self).items()))
#
#    def __eq__(self, x):
#        if isinstance(x, type(self)):
#            return self._identifier() == x._identifier()
#        else:
#            return False
#
#    def __ne__(self, x):
#        return not self.__eq__(x)
#
#    def __len__(self):
#        return int(self.dim)
#
#    def copy(self):
#        return space(para=self.para,
#                     dtype=self.dtype)
#
#    def getitem(self, data, key):
#        raise NotImplementedError(about._errors.cstring(
#            "ERROR: no generic instance method 'getitem'."))
#
#    def setitem(self, data, update, key):
#        raise NotImplementedError(about._errors.cstring(
#            "ERROR: no generic instance method 'getitem'."))
#
#    def apply_scalar_function(self, x, function, inplace=False):
#        raise NotImplementedError(about._errors.cstring(
#            "ERROR: no generic instance method 'apply_scalar_function'."))
#
#    @property
#    def shape(self):
#        raise NotImplementedError(about._errors.cstring(
#            "ERROR: no generic instance method 'shape'."))
#
#    @property
#    def dim(self):
#        """
#            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.
#        """
#        raise NotImplementedError(about._errors.cstring(
#            "ERROR: no generic instance method 'dim'."))
#
#    @property
#    def dof(self):
#        """
#            Computes the number of degrees of freedom of the space.
#
#            Returns
#            -------
#            dof : int
#                Number of degrees of freedom of the space.
#        """
#        raise NotImplementedError(about._errors.cstring(
#            "ERROR: no generic instance method 'dof'."))
#
#    @property
#    def dof_split(self):
#        """
#            Computes the number of degrees of freedom of the space.
#
#            Returns
#            -------
#            dof : int
#                Number of degrees of freedom of the space.
#        """
#        raise NotImplementedError(about._errors.cstring(
#            "ERROR: no generic instance method 'dof_split'."))
#
#    def complement_cast(self, x, axis=None):
#        return x
#
#    # TODO: Move enforce power into power_indices class
#    def enforce_power(self, spec, **kwargs):
#        """
#            Provides a valid power spectrum array from a given object.
#
#            Parameters
#            ----------
#            spec : {scalar, list, numpy.ndarray, nifty.field, function}
#                Fiducial power spectrum from which a valid power spectrum is to
#                be calculated. Scalars are interpreted as constant power
#                spectra.
#
#            Returns
#            -------
#            spec : numpy.ndarray
#                Valid power spectrum.
#
#            Other parameters
#            ----------------
#            size : int, *optional*
#                Number of bands the power spectrum shall have (default: None).
#            kindex : numpy.ndarray, *optional*
#                Scale of each band.
#            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).
#
#        """
#        raise NotImplementedError(about._errors.cstring(
#            "ERROR: no generic instance method 'enforce_power'."))
#
#    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 codomain is None:
#            return False
#        else:
#            raise NotImplementedError(about._errors.cstring(
#                "ERROR: no generic instance method 'check_codomain'."))
#
#    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.
#        """
#        raise NotImplementedError(about._errors.cstring(
#            "ERROR: no generic instance method 'get_codomain'."))
#
#    def get_random_values(self, **kwargs):
#        """
#            Generates random field values according to the specifications given
#            by the parameters.
#
#            Returns
#            -------
#            x : numpy.ndarray
#                Valid field values.
#
#            Other parameters
#            ----------------
#            random : string, *optional*
#                Specifies the probability distribution from which the random
#                numbers are to be drawn.
#                Supported distributions are:
#
#                - "pm1" (uniform distribution over {+1,-1} or {+1,+i,-1,-i}
#                - "gau" (normal distribution with zero-mean and a given
#                    standard deviation or variance)
#                - "syn" (synthesizes from a given power spectrum)
#                - "uni" (uniform distribution over [vmin,vmax[)
#
#                (default: None).
#            dev : float, *optional*
#                Standard deviation (default: 1).
#            var : float, *optional*
#                Variance, overriding `dev` if both are specified
#                (default: 1).
#            spec : {scalar, list, numpy.ndarray, nifty.field, function},
#                    *optional*
#                Power spectrum (default: 1).
#            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).
#            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).
#            vmin : float, *optional*
#                Lower limit for a uniform distribution (default: 0).
#            vmax : float, *optional*
#                Upper limit for a uniform distribution (default: 1).
#        """
#        raise NotImplementedError(about._errors.cstring(
#            "ERROR: no generic instance method 'get_random_values'."))
#
#    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.
#        """
#        raise NotImplementedError(about._errors.cstring(
#            "ERROR: no generic instance method 'calc_weight'."))
#
#    def get_weight(self, power=1):
#        raise NotImplementedError(about._errors.cstring(
#            "ERROR: no generic instance method 'get_weight'."))
#
#    def calc_norm(self, x, q):
#        raise NotImplementedError(about._errors.cstring(
#            "ERROR: no generic instance method 'norm'."))
#
#    def dot_contraction(self, x, axes):
#        """
#            Computes the discrete inner product of two given arrays of field
#            values.
#
#            Parameters
#            ----------
#            x : numpy.ndarray
#                First array
#            y : numpy.ndarray
#                Second array
#
#            Returns
#            -------
#            dot : scalar
#                Inner product of the two arrays.
#        """
#        raise NotImplementedError(about._errors.cstring(
#            "ERROR: no generic instance method 'dot'."))
#
#    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*
#                codomain 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.
#        """
#        raise NotImplementedError(about._errors.cstring(
#            "ERROR: no generic instance method 'calc_transform'."))
#
#    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).
#        """
#        raise NotImplementedError(about._errors.cstring(
#            "ERROR: no generic instance method 'calc_smooth'."))
#
#    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).
#            kindex : numpy.ndarray, *optional*
#                Scale corresponding to each band in the power spectrum
#                (default: None).
#            rho : numpy.ndarray, *optional*
#                Number of degrees of freedom per band (default: None).
#            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).
#
#        """
#        raise NotImplementedError(about._errors.cstring(
#            "ERROR: no generic instance method 'calc_power'."))
#
#    def calc_real_Q(self, x):
#        raise NotImplementedError(about._errors.cstring(
#            "ERROR: no generic instance method 'calc_real_Q'."))
#
#    def calc_bincount(self, x, weights=None, minlength=None):
#        raise NotImplementedError(about._errors.cstring(
#            "ERROR: no generic instance method 'calc_bincount'."))
#
#    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).
#            save : string, *optional*
#                Valid file name where the figure is to be stored, by default
#                the figure is not saved (default: False).
#            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).
#            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).
#            iter : int, *optional*
#                Number of iterations (default: 0).
#
#        """
#        raise NotImplementedError(about._errors.cstring(
#            "ERROR: no generic instance method 'get_plot'."))
#
#    def __repr__(self):
#        string = ""
#        string += str(type(self)) + "\n"
#        string += "paradict: " + str(self.paradict) + "\n"
#        return string
#
#    def __str__(self):
#        return self.__repr__()


class Space(object):
Marco Selig's avatar
Marco Selig committed
736
    """
Ultimanet's avatar
Ultimanet committed
737
738
739
740
741
742
743
        ..                            __             __
        ..                          /__/           /  /_
        ..      ______    ______    __   __ ___   /   _/
        ..    /   _   | /   _   | /  / /   _   | /  /
        ..   /  /_/  / /  /_/  / /  / /  / /  / /  /_
        ..  /   ____/  \______/ /__/ /__/ /__/  \___/  space class
        .. /__/
Marco Selig's avatar
Marco Selig committed
744

Ultimanet's avatar
Ultimanet committed
745
        NIFTY subclass for unstructured spaces.
Marco Selig's avatar
Marco Selig committed
746

Ultimanet's avatar
Ultimanet committed
747
748
        Unstructured spaces are lists of values without any geometrical
        information.
Marco Selig's avatar
Marco Selig committed
749
750
751

        Parameters
        ----------
Ultimanet's avatar
Ultimanet committed
752
753
        num : int
            Number of points.
754
        dtype : numpy.dtype, *optional*
Ultimanet's avatar
Ultimanet committed
755
            Data type of the field values (default: None).
Marco Selig's avatar
Marco Selig committed
756

Ultimanet's avatar
Ultimanet committed
757
        Attributes
Marco Selig's avatar
Marco Selig committed
758
        ----------
Ultimanet's avatar
Ultimanet committed
759
760
        para : numpy.ndarray
            Array containing the number of points.
761
        dtype : numpy.dtype
Ultimanet's avatar
Ultimanet committed
762
763
764
765
766
767
            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.
Marco Selig's avatar
Marco Selig committed
768
    """
769

csongor's avatar
csongor committed
770
    def __init__(self, num, dtype=np.dtype('float')):
Ultimanet's avatar
Ultimanet committed
771
772
        """
            Sets the attributes for a point_space class instance.
Marco Selig's avatar
Marco Selig committed
773

Ultimanet's avatar
Ultimanet committed
774
775
776
777
            Parameters
            ----------
            num : int
                Number of points.
778
            dtype : numpy.dtype, *optional*
Ultimanet's avatar
Ultimanet committed
779
                Data type of the field values (default: numpy.float64).
Marco Selig's avatar
Marco Selig committed
780

Ultimanet's avatar
Ultimanet committed
781
782
783
784
            Returns
            -------
            None.
        """
Ultima's avatar
Ultima committed
785
        self._cache_dict = {'check_codomain': {}}
786
787
        self.paradict = point_space_paradict(num=num)

788
789
        # parse dtype
        dtype = np.dtype(dtype)
Ultima's avatar
Ultima committed
790
791
792
793
794
795
796
797
798
        if dtype not in [np.dtype('bool'),
                         np.dtype('int16'),
                         np.dtype('int32'),
                         np.dtype('int64'),
                         np.dtype('float32'),
                         np.dtype('float64'),
                         np.dtype('complex64'),
                         np.dtype('complex128')]:
            raise ValueError(about._errors.cstring(
799
                             "WARNING: incompatible dtype: " + str(dtype)))
Ultima's avatar
Ultima committed
800
        self.dtype = dtype
801

Ultimanet's avatar
Ultimanet committed
802
        self.discrete = True
Ultima's avatar
Ultima committed
803
#        self.harmonic = False
804
        self.distances = (np.float(1),)
Marco Selig's avatar
Marco Selig committed
805

Ultimanet's avatar
Ultimanet committed
806
807
808
809
    @property
    def para(self):
        temp = np.array([self.paradict['num']], dtype=int)
        return temp
810

Ultimanet's avatar
Ultimanet committed
811
812
    @para.setter
    def para(self, x):
Ultima's avatar
Ultima committed
813
        self.paradict['num'] = x[0]
814

Ultima's avatar
Ultima committed
815
816
817
818
    def __hash__(self):
        # Extract the identifying parts from the vars(self) dict.
        result_hash = 0
        for (key, item) in vars(self).items():
Ultima's avatar
Ultima committed
819
820
            if key in ['_cache_dict']:
                continue
Ultima's avatar
Ultima committed
821
822
823
            result_hash ^= item.__hash__() * hash(key)
        return result_hash

824
825
826
827
828
    def _identifier(self):
        # Extract the identifying parts from the vars(self) dict.
        temp = [(ii[0],
                 ((lambda x: x[1].__hash__() if x[0] == 'comm' else x)(ii)))
                for ii in vars(self).iteritems()
Ultima's avatar
Ultima committed
829
                if ii[0] not in ['_cache_dict']
830
831
832
833
                ]
        # Return the sorted identifiers as a tuple.
        return tuple(sorted(temp))

834
    def copy(self):
835
        return point_space(num=self.paradict['num'],
csongor's avatar
csongor committed
836
                           dtype=self.dtype)
837

Ultimanet's avatar
Ultimanet committed
838
839
    def getitem(self, data, key):
        return data[key]
Marco Selig's avatar
Marco Selig committed
840

Ultimanet's avatar
Ultimanet committed
841
    def setitem(self, data, update, key):
842
        data[key] = update
Marco Selig's avatar
Marco Selig committed
843

Ultimanet's avatar
Ultimanet committed
844
    def apply_scalar_function(self, x, function, inplace=False):
845
        return x.apply_scalar_function(function, inplace=inplace)
846

847
848
    @property
    def shape(self):
849
        return (self.paradict['num'],)
Marco Selig's avatar
Marco Selig committed
850

851
852
    @property
    def dim(self):
Ultimanet's avatar
Ultimanet committed
853
854
        """
            Computes the dimension of the space, i.e.\  the number of points.
Marco Selig's avatar
Marco Selig committed
855

Ultimanet's avatar
Ultimanet committed
856
857
858
859
860
            Parameters
            ----------
            split : bool, *optional*
                Whether to return the dimension as an array with one component
                or as a scalar (default: False).
Marco Selig's avatar
Marco Selig committed
861

Ultimanet's avatar
Ultimanet committed
862
863
864
865
866
            Returns
            -------
            dim : {int, numpy.ndarray}
                Dimension(s) of the space.
        """
867
        return np.prod(self.shape)
Marco Selig's avatar
Marco Selig committed
868

869
870
    @property
    def dof(self):
Ultimanet's avatar
Ultimanet committed
871
872
873
874
        """
            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.
Marco Selig's avatar
Marco Selig committed
875

Ultimanet's avatar
Ultimanet committed
876
877
878
879
880
            Returns
            -------
            dof : int
                Number of degrees of freedom of the space.
        """
881
882
883
        dof = self.dim
        if issubclass(self.dtype.type, np.complexfloating):
            dof = dof * 2
Ultima's avatar
Ultima committed
884
        return dof
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
    @property
    def dof_split(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 = self.shape
        if issubclass(self.dtype.type, np.complexfloating):
            dof = tuple(np.array(dof)*2)
        return dof

    @property
    def vol(self, split=False):
        return np.prod(self.distances)

    @property
    def vol_split(self):
        return self.distances
Marco Selig's avatar
Marco Selig committed
910

911
912
    @property
    def meta_volume(self):
Marco Selig's avatar
Marco Selig committed
913
        """
914
            Calculates the meta volumes.
Ultimanet's avatar
Ultimanet committed
915

916
917
918
919
920
            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. In the case of an :py:class:`rg_space`, the
            meta volumes are simply the pixel volumes.
Marco Selig's avatar
Marco Selig committed
921
922
923

            Parameters
            ----------
924
925
926
            total : bool, *optional*
                Whether to return the total meta volume of the space or the
                individual ones of each pixel (default: False).
Marco Selig's avatar
Marco Selig committed
927
928
929

            Returns
            -------
930
931
            mol : {numpy.ndarray, float}
                Meta volume of the pixels or the complete space.
Ultimanet's avatar
Ultimanet committed
932
        """
933
934
935
936
937
938
        return self.dim() * self.vol()

    @property
    def meta_volume_split(self):
        mol = self.cast(1, dtype=np.dtype('float'))
        return self.calc_weight(mol, power=1)
939

940
941
942
943
    def enforce_power(self, spec, **kwargs):
        """
            Raises an error since the power spectrum is ill-defined for point
            spaces.
Marco Selig's avatar
Marco Selig committed
944
        """
945
946
947
        raise AttributeError(about._errors.cstring(
            "ERROR: the definition of power spectra is ill-defined for " +
            "(unstructured) point spaces."))
Ultimanet's avatar
Ultimanet committed
948

949
    def _enforce_power_helper(self, spec, size, kindex):
950
951
952
953
        # TODO: Resolve this import by splitting nifty_core into nifty_space
        # and nifty_point_space
        from nifty_field import field

954
955
956
        # Now it's about to extract a powerspectrum from spec
        # First of all just extract a numpy array. The shape is cared about
        # later.
957
        dtype = np.dtype('float')
958
959
960
961
        # Case 1: spec is a function
        if callable(spec):
            # Try to plug in the kindex array in the function directly
            try:
962
                spec = np.array(spec(kindex), dtype=dtype)
963
964
965
966
967
            except:
                # Second try: Use a vectorized version of the function.
                # This is slower, but better than nothing
                try:
                    spec = np.array(np.vectorize(spec)(kindex),
968
                                    dtype=dtype)
969
970
971
972
973
974
975
976
977
978
                except:
                    raise TypeError(about._errors.cstring(
                        "ERROR: invalid power spectra function."))

        # Case 2: spec is a field:
        elif isinstance(spec, field):
            try:
                spec = spec.val.get_full_data()
            except AttributeError:
                spec = spec.val
979
            spec = spec.astype(dtype).flatten()
Marco Selig's avatar
Marco Selig committed
980

981
982
        # Case 3: spec is a scalar or something else:
        else:
983
            spec = np.array(spec, dtype=dtype).flatten()
984
985
986
987
988

        # Make some sanity checks
        # check finiteness
        if not np.all(np.isfinite(spec)):
            about.warnings.cprint("WARNING: infinite value(s).")
Marco Selig's avatar
Marco Selig committed
989

990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
        # check positivity (excluding null)
        if np.any(spec < 0):
            raise ValueError(about._errors.cstring(
                "ERROR: nonpositive value(s)."))
        if np.any(spec == 0):
            about.warnings.cprint("WARNING: nonpositive value(s).")

        # Set the size parameter
        if size is None:
            size = len(kindex)

        # Fix the size of the spectrum
        # If spec is singlevalued, expand it
        if np.size(spec) == 1:
            spec = spec * np.ones(size, dtype=spec.dtype)
        # If the size does not fit at all, throw an exception
        elif np.size(spec) < size:
            raise ValueError(about._errors.cstring("ERROR: size mismatch ( " +
                                                   str(np.size(spec)) + " < " +
                                                   str(size) + " )."))
        elif np.size(spec) > size:
            about.warnings.cprint("WARNING: power spectrum cut to size ( == " +
                                  str(size) + " ).")
            spec = spec[:size]

        return spec
Ultimanet's avatar
Ultimanet committed
1016

1017
    def check_codomain(self, codomain):
Ultima's avatar
Ultima committed
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
        check_dict = self._cache_dict['check_codomain']
        temp_id = id(codomain)
        if temp_id in check_dict:
            return check_dict[temp_id]
        else:
            temp_result = self._check_codomain(codomain)
            check_dict[temp_id] = temp_result
            return temp_result

    def _check_codomain(self, codomain):
Marco Selig's avatar
Marco Selig committed
1028
        """
1029
            Checks whether a given codomain is compatible to the space or not.
Marco Selig's avatar
Marco Selig committed
1030
1031
1032

            Parameters
            ----------
1033
1034
            codomain : nifty.space
                Space to be checked for compatibility.
Marco Selig's avatar
Marco Selig committed
1035
1036
1037

            Returns
            -------
1038
1039
            check : bool
                Whether or not the given codomain is compatible to the space.
Marco Selig's avatar
Marco Selig committed
1040
        """
1041
1042
        if codomain is None:
            return False
1043

1044
1045
        if not isinstance(codomain, space):
            raise TypeError(about._errors.cstring(
Ultima's avatar
Ultima committed
1046
                "ERROR: invalid input. The given input is not a nifty space."))
Ultimanet's avatar
Ultimanet committed
1047

1048
1049
1050
1051
        if codomain == self:
            return True
        else:
            return False
Ultimanet's avatar
Ultimanet committed
1052

1053
1054
1055
1056
1057
    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.
Marco Selig's avatar
Marco Selig committed
1058

1059
1060
1061
1062
1063
1064
            Returns
            -------
            codomain : nifty.point_space
                A compatible codomain.
        """
        return self.copy()
Marco Selig's avatar
Marco Selig committed
1065

1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
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
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
#    def get_random_values(self, **kwargs):
#        """
#            Generates random field values according to the specifications given
#            by the parameters.
#
#            Returns
#            -------
#            x : numpy.ndarray
#                Valid field values.
#
#            Other parameters
#            ----------------
#            random : string, *optional*
#                Specifies the probability distribution from which the random
#                numbers are to be drawn.
#                Supported distributions are:
#
#                - "pm1" (uniform distribution over {+1,-1} or {+1,+i,-1,-i}
#                - "gau" (normal distribution with zero-mean and a given
#                standard
#                    deviation or variance)
#                - "syn" (synthesizes from a given power spectrum)
#                - "uni" (uniform distribution over [vmin,vmax[)
#
#                (default: None).
#            dev : float, *optional*
#                Standard deviation (default: 1).
#            var : float, *optional*
#                Variance, overriding `dev` if both are specified
#                (default: 1).
#            spec : {scalar, list, numpy.ndarray, nifty.field, function},
#            *optional*
#                Power spectrum (default: 1).
#            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).
#            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).
#            vmin : float, *optional*
#                Lower limit for a uniform distribution (default: 0).
#            vmax : float, *optional*
#                Upper limit for a uniform distribution (default: 1).
#        """
#
#        arg = random.parse_arguments(self, **kwargs)
#
#        if arg is None:
#            return self.cast(0)
#
#        # Prepare the empty distributed_data_object
#        sample = distributed_data_object(
#                                    global_shape=self.shape,
#                                    dtype=self.dtype)
#
#        # Case 1: uniform distribution over {-1,+1}/{1,i,-1,-i}
#        if arg['random'] == 'pm1':
#            sample.apply_generator(lambda s: random.pm1(dtype=self.dtype,
#                                                        shape=s))
#
#        # Case 2: normal distribution with zero-mean and a given standard
#        #         deviation or variance
#        elif arg['random'] == 'gau':
#            std = arg['std']
#            if np.isscalar(std) or std is None:
#                processed_std = std
#            else:
#                try:
#                    processed_std = sample.distributor. \
#                        extract_local_data(std)
#                except(AttributeError):
#                    processed_std = std
#
#            sample.apply_generator(lambda s: random.gau(dtype=self.dtype,
#                                                        shape=s,
#                                                        mean=arg['mean'],
#                                                        std=processed_std))
#
#        # Case 3: uniform distribution
#        elif arg['random'] == 'uni':
#            sample.apply_generator(lambda s: random.uni(dtype=self.dtype,
#                                                        shape=s,
#                                                        vmin=arg['vmin'],
#                                                        vmax=arg['vmax']))
#        return sample
1170

1171
    def calc_weight(self, x, power=1):
Marco Selig's avatar
Marco Selig committed
1172
        """
Ultimanet's avatar
Ultimanet committed
1173
1174
            Weights a given array of field values with the pixel volumes (not
            the meta volumes) to a given power.
Marco Selig's avatar
Marco Selig committed
1175
1176
1177

            Parameters
            ----------
Ultimanet's avatar
Ultimanet committed
1178
1179
1180
1181
            x : numpy.ndarray
                Array to be weighted.
            power : float, *optional*
                Power of the pixel volumes to be used (default: 1).
Marco Selig's avatar
Marco Selig committed
1182
1183

            Returns
Ultimanet's avatar
Ultimanet committed
1184
1185
1186
            -------
            y : numpy.ndarray
                Weighted array.
Marco Selig's avatar
Marco Selig committed
1187
        """
1188
1189
1190
        # weight
        return x * self.get_weight(power=power)

1191
    def get_weight(self, power=1, split=False):
1192
1193
1194
1195
1196
        splitted_weight = tuple(np.array(self.distances)**np.array(power))
        if not split:
            return np.prod(splitted_weight)
        else:
            return splitted_weight
Marco Selig's avatar
Marco Selig committed
1197

Ultima's avatar
Ultima committed
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
    def calc_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

1224
    def dot_contraction(self, x, axes):
Ultimanet's avatar
Ultimanet committed
1225
1226
1227
        """
            Computes the discrete inner product of two given arrays of field
            values.
Marco Selig's avatar
Marco Selig committed
1228

Ultimanet's avatar
Ultimanet committed
1229
1230
1231
1232
1233
1234
            Parameters
            ----------
            x : numpy.ndarray
                First array
            y : numpy.ndarray
                Second array
Marco Selig's avatar
Marco Selig committed
1235

Ultimanet's avatar
Ultimanet committed
1236
1237
1238
1239
1240
            Returns
            -------
            dot : scalar
                Inner product of the two arrays.
        """
1241
        return x.sum(axis=axes)
1242

1243
    def calc_transform(self, x, codomain=None, **kwargs):
Marco Selig's avatar
Marco Selig committed
1244
        """
Ultimanet's avatar
Ultimanet committed
1245
            Computes the transform of a given array of field values.
Marco Selig's avatar
Marco Selig committed
1246
1247
1248

            Parameters
            ----------
Ultimanet's avatar
Ultimanet committed
1249
1250
1251
            x : numpy.ndarray
                Array to be transformed.
            codomain : nifty.space, *optional*
1252
                codomain space to which the transformation shall map
Ultimanet's avatar
Ultimanet committed
1253
                (default: self).
Marco Selig's avatar
Marco Selig committed
1254
1255
1256

            Returns
            -------
Ultimanet's avatar
Ultimanet committed
1257
1258
            Tx : numpy.ndarray
                Transformed array
1259

Ultimanet's avatar
Ultimanet committed
1260
            Other parameters
1261
            ----------------
1262
1263
            iter : int, *optional*
                Number of iterations performed in specific transformations.
Marco Selig's avatar
Marco Selig committed
1264
        """
1265
1266
1267
        raise AttributeError(about._errors.cstring(
            "ERROR: fourier-transformation is ill-defined for " +
            "(unstructured) point space."))
1268

1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
    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 calc_real_Q(self, x):
        try:
            return x.isreal().all()
1289
        except AttributeError:
1290
            return np.all(np.isreal(x))
Marco Selig's avatar
Marco Selig committed
1291

1292
    def calc_bincount(self, x, weights=None, minlength=None):
1293
1294
1295
1296
1297
1298
        try:
            complex_weights_Q = issubclass(weights.dtype.type,
                                           np.complexfloating)
        except AttributeError:
            complex_weights_Q = False

1299
1300
1301
1302
1303
1304
        if complex_weights_Q:
            real_bincount = x.bincount(weights=weights.real,
                                       minlength=minlength)
            imag_bincount = x.bincount(weights=weights.imag,
                                       minlength=minlength)
            return real_bincount + imag_bincount
1305
        else:
1306
            return x.bincount(weights=weights, minlength=minlength)
Marco Selig's avatar
Marco Selig committed
1307

1308
1309
    def get_plot(self, x, title="", vmin=None, vmax=None, unit=None,
                 norm=None, other=None, legend=False, save=None, **kwargs):
Marco Selig's avatar
Marco Selig committed
1310
        """
1311
1312
            Creates a plot of field values according to the specifications
            given by the parameters.
Marco Selig's avatar
Marco Selig committed
1313
1314
1315

            Parameters
            ----------
Ultimanet's avatar
Ultimanet committed
1316
            x : numpy.ndarray
1317
                Array containing the field values.
Marco Selig's avatar
Marco Selig committed
1318
1319
1320

            Returns
            -------
1321
            None
1322

Ultimanet's avatar
Ultimanet committed
1323
            Other parameters
1324
            ----------------
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
            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).
            save : string, *optional*
                Valid file name where the figure is to be stored, by default
                the figure is not saved (default: False).

Ultimanet's avatar
Ultimanet committed
1344
        """
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
        if not pl.isinteractive() and save is not None:
            about.warnings.cprint("WARNING: interactive mode off.")

        x = self.cast(x)

        fig = pl.figure(num=None,
                        figsize=(6.4, 4.8),
                        dpi=None,
                        facecolor="none",
                        edgecolor="none",
                        frameon=False,
                        FigureClass=pl.Figure)

        ax0 = fig.add_axes([0.12, 0.12, 0.82, 0.76])
        xaxes = np.arange(self.para[0], dtype=np.dtype('int'))

1361
        if (norm == "log") and (vmin <= 0):
1362
1363
1364
1365
1366
1367
1368
1369
            raise ValueError(about._errors.cstring(
                "ERROR: nonpositive value(s)."))

        if issubclass(self.dtype.type, np.complexfloating):
            if vmin is None:
                vmin = min(x.real.min(), x.imag.min(), abs(x).min())
            if vmax is None:
                vmax = min(x.real.max(), x.imag.max(), abs(x).max())
Ultimanet's avatar
Ultimanet committed
1370
        else:
1371
1372
1373
1374
            if vmin is None:
                vmin = x.min()
            if vmax is None:
                vmax = x.max()
Ultimanet's avatar
Ultimanet committed
1375

1376
1377
1378
        ax0.set_xlim(xaxes[0], xaxes[-1])
        ax0.set_xlabel("index")
        ax0.set_ylim(vmin, vmax)
1379

1380
1381
        if(norm == "log"):
            ax0.set_yscale('log')
Marco Selig's avatar
Marco Selig committed
1382

1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
        if issubclass(self.dtype.type, np.complexfloating):
            ax0.scatter(xaxes, self.unary_operation(x, op='abs'),
                        color=[0.0, 0.5, 0.0], marker='o',
                        label="graph (absolute)", facecolor="none", zorder=1)
            ax0.scatter(xaxes, self.unary_operation(x, op='real'),
                        color=[0.0, 0.5, 0.0], marker='s',
                        label="graph (real part)", facecolor="none", zorder=1)
            ax0.scatter(xaxes, self.unary_operation(x, op='imag'),
                        color=[0.0, 0.5, 0.0], marker='D',
                        label="graph (imaginary part)", facecolor="none",
                        zorder=1)
        else:
            ax0.scatter(xaxes, x, color=[0.0, 0.5, 0.0], marker='o',
                        label="graph 0", zorder=1)
Marco Selig's avatar
Marco Selig committed
1397

1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
        if other is not None:
            if not isinstance(other, tuple):
                other = (other, )
            imax = max(1, len(other) - 1)
            for ii in xrange(len(other)):
                ax0.scatter(xaxes, self.dtype(other[ii]),
                            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', label="'other' graph " + str(ii),
                            zorder=-ii)
Ultimanet's avatar
Ultimanet committed
1410

1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
        if legend:
            ax0.legend()

        if unit is not None:
            unit = " [" + unit + "]"
        else:
            unit = ""

        ax0.set_ylabel("values" + unit)
        ax0.set_title(title)

        if save is not None:
            fig.savefig(str(save), dpi=None,
                        facecolor="none", edgecolor="none")
            pl.close(fig)
        else:
            fig.canvas.draw()
Marco Selig's avatar
Marco Selig committed
1428

1429
    def __repr__(self):
Ultima's avatar
Ultima committed
1430
1431
        string = ""
        string += str(type(self)) + "\n"
Ultima's avatar
Ultima committed
1432
        string += "paradict: " + str(self.paradict) + "\n"
Ultima's avatar
Ultima committed
1433
1434
1435
1436
        string += 'dtype: ' + str(self.dtype) + "\n"
        string += 'discrete: ' + str(self.discrete) + "\n"
        string += 'distances: ' + str(self.distances) + "\n"
        return string