nifty_core.py 116 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
from nifty_paradict import space_paradict,\
148
    point_space_paradict
Ultimanet's avatar
Ultimanet committed
149

150
from keepers import about,\
151
152
153
    global_configuration as gc,\
    global_dependency_injector as gdi

Ultimanet's avatar
Ultimanet committed
154
from nifty_random import random
155
from nifty.nifty_mpi_data import distributed_data_object,\
156
    STRATEGIES as DISTRIBUTION_STRATEGIES
157

158
import nifty.nifty_utilities as utilities
Marco Selig's avatar
Marco Selig committed
159

160
POINT_DISTRIBUTION_STRATEGIES = DISTRIBUTION_STRATEGIES['global']
Marco Selig's avatar
Marco Selig committed
161

162
163
#pi = 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679

164

Marco Selig's avatar
Marco Selig committed
165

Ultimanet's avatar
Ultimanet committed
166
167

class space(object):
Marco Selig's avatar
Marco Selig committed
168
    """
Ultimanet's avatar
Ultimanet committed
169
170
171
172
173
174
175
        ..     _______   ______    ____ __   _______   _______
        ..   /  _____/ /   _   | /   _   / /   ____/ /   __  /
        ..  /_____  / /  /_/  / /  /_/  / /  /____  /  /____/
        .. /_______/ /   ____/  \______|  \______/  \______/  class
        ..          /__/

        NIFTY base class for spaces and their discretizations.
Marco Selig's avatar
Marco Selig committed
176

Ultimanet's avatar
Ultimanet committed
177
178
179
        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.
Marco Selig's avatar
Marco Selig committed
180
181
182

        Parameters
        ----------
183
        dtype : numpy.dtype, *optional*
Ultimanet's avatar
Ultimanet committed
184
185
            Data type of the field values for a field defined on this space
            (default: numpy.float64).
186
        datamodel :
Marco Selig's avatar
Marco Selig committed
187
188
189

        See Also
        --------
Ultimanet's avatar
Ultimanet committed
190
191
192
193
194
195
196
197
        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.
Marco Selig's avatar
Marco Selig committed
198

Ultimanet's avatar
Ultimanet committed
199
200
201
202
203
204
205
206
        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>`_
Marco Selig's avatar
Marco Selig committed
207
208
209

        Attributes
        ----------
Ultimanet's avatar
Ultimanet committed
210
        para : {single object, list of objects}
211
212
213
            This is a freeform list of parameters that derivatives of the space
            class can use.
        dtype : numpy.dtype
Ultimanet's avatar
Ultimanet committed
214
215
216
217
218
219
220
            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.
Marco Selig's avatar
Marco Selig committed
221
    """
222

223
    def __init__(self, dtype=np.dtype('float'), datamodel='np'):
Marco Selig's avatar
Marco Selig committed
224
        """
Ultimanet's avatar
Ultimanet committed
225
            Sets the attributes for a space class instance.
Marco Selig's avatar
Marco Selig committed
226
227
228

            Parameters
            ----------
229
            dtype : numpy.dtype, *optional*
Ultimanet's avatar
Ultimanet committed
230
231
                Data type of the field values for a field defined on this space
                (default: numpy.float64).
232
            datamodel :
Marco Selig's avatar
Marco Selig committed
233

Ultimanet's avatar
Ultimanet committed
234
235
236
            Returns
            -------
            None
Marco Selig's avatar
Marco Selig committed
237
        """
238
239
240
241
242
243
        self.paradict = space_paradict()
#        self.datamodel = str(datamodel)
#        self.dtype = np.dtype(dtype)
#        self.discrete = False
#        self.harmonic = False
#        self.distances = np.real(np.array([1], dtype=self.dtype))
244

Ultimanet's avatar
Ultimanet committed
245
246
247
    @property
    def para(self):
        return self.paradict['default']
248

Ultimanet's avatar
Ultimanet committed
249
250
251
    @para.setter
    def para(self, x):
        self.paradict['default'] = x
Marco Selig's avatar
Marco Selig committed
252

253
    def _identifier(self):
Marco Selig's avatar
Marco Selig committed
254
        """
255
256
257
        _identiftier returns an object which contains all information needed
        to uniquely idetnify a space. It returns a (immutable) tuple which
        therefore can be compared.
258
        """
259
260
261
262
263
264
265
266
267
268
269
270
271
        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.get_dim(split=False))
Marco Selig's avatar
Marco Selig committed
272

273
    def copy(self):
274
        return space(para=self.para,
275
                     dtype=self.dtype)
Marco Selig's avatar
Marco Selig committed
276

Ultimanet's avatar
Ultimanet committed
277
    def getitem(self, data, key):
278
        raise NotImplementedError(about._errors.cstring(
Ultimanet's avatar
Ultimanet committed
279
            "ERROR: no generic instance method 'getitem'."))
Marco Selig's avatar
Marco Selig committed
280

Ultimanet's avatar
Ultimanet committed
281
    def setitem(self, data, key):
282
        raise NotImplementedError(about._errors.cstring(
Ultimanet's avatar
Ultimanet committed
283
            "ERROR: no generic instance method 'getitem'."))
284

Ultimanet's avatar
Ultimanet committed
285
    def apply_scalar_function(self, x, function, inplace=False):
286
        raise NotImplementedError(about._errors.cstring(
Ultimanet's avatar
Ultimanet committed
287
            "ERROR: no generic instance method 'apply_scalar_function'."))
Marco Selig's avatar
Marco Selig committed
288

Ultimanet's avatar
Ultimanet committed
289
    def unary_operation(self, x, op=None):
290
        raise NotImplementedError(about._errors.cstring(
Ultimanet's avatar
Ultimanet committed
291
            "ERROR: no generic instance method 'unary_operation'."))
292

Ultimanet's avatar
Ultimanet committed
293
    def binary_operation(self, x, y, op=None):
294
        raise NotImplementedError(about._errors.cstring(
Ultimanet's avatar
Ultimanet committed
295
            "ERROR: no generic instance method 'binary_operation'."))
Marco Selig's avatar
Marco Selig committed
296

297
    def get_norm(self, x, q):
298
        raise NotImplementedError(about._errors.cstring(
Ultimanet's avatar
Ultimanet committed
299
            "ERROR: no generic instance method 'norm'."))
Marco Selig's avatar
Marco Selig committed
300

301
    def get_shape(self):
302
        raise NotImplementedError(about._errors.cstring(
Ultimanet's avatar
Ultimanet committed
303
            "ERROR: no generic instance method 'shape'."))
Marco Selig's avatar
Marco Selig committed
304

305
    def get_dim(self, split=False):
Marco Selig's avatar
Marco Selig committed
306
        """
Ultimanet's avatar
Ultimanet committed
307
            Computes the dimension of the space, i.e.\  the number of pixels.
Marco Selig's avatar
Marco Selig committed
308
309
310

            Parameters
            ----------
Ultimanet's avatar
Ultimanet committed
311
312
313
            split : bool, *optional*
                Whether to return the dimension split up, i.e. the numbers of
                pixels in each direction, or not (default: False).
Marco Selig's avatar
Marco Selig committed
314

Ultimanet's avatar
Ultimanet committed
315
316
317
318
            Returns
            -------
            dim : {int, numpy.ndarray}
                Dimension(s) of the space.
Marco Selig's avatar
Marco Selig committed
319
        """
320
        raise NotImplementedError(about._errors.cstring(
321
            "ERROR: no generic instance method 'dim'."))
Marco Selig's avatar
Marco Selig committed
322

323
    def get_dof(self):
Marco Selig's avatar
Marco Selig committed
324
        """
Ultimanet's avatar
Ultimanet committed
325
            Computes the number of degrees of freedom of the space.
Marco Selig's avatar
Marco Selig committed
326
327
328

            Returns
            -------
Ultimanet's avatar
Ultimanet committed
329
330
            dof : int
                Number of degrees of freedom of the space.
Marco Selig's avatar
Marco Selig committed
331
        """
332
        raise NotImplementedError(about._errors.cstring(
333
            "ERROR: no generic instance method 'dof'."))
Marco Selig's avatar
Marco Selig committed
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
    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.
        """
        raise NotImplementedError(about._errors.cstring(
            "ERROR: no generic instance method 'get_meta_volume'."))

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

384
    # TODO: Move enforce power into power_indices class
385
    def enforce_power(self, spec, **kwargs):
Marco Selig's avatar
Marco Selig committed
386
        """
Ultimanet's avatar
Ultimanet committed
387
            Provides a valid power spectrum array from a given object.
Marco Selig's avatar
Marco Selig committed
388
389
390

            Parameters
            ----------
Ultimanet's avatar
Ultimanet committed
391
392
393
394
            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.
Marco Selig's avatar
Marco Selig committed
395
396
397

            Returns
            -------
Ultimanet's avatar
Ultimanet committed
398
399
400
401
402
403
404
405
406
407
408
409
            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*
410
411
                Flag specifying if the spectral binning is performed on
                logarithmic
Ultimanet's avatar
Ultimanet committed
412
413
414
415
                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*
416
417
                Number of used spectral bins; if given `log` is set to
                ``False``;
Ultimanet's avatar
Ultimanet committed
418
419
420
421
422
                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
423
424
                (default: None).
            vmin : {scalar, list, ndarray, field}, *optional*
Ultimanet's avatar
Ultimanet committed
425
426
                Lower limit of the uniform distribution if ``random == "uni"``
                (default: 0).
Marco Selig's avatar
Marco Selig committed
427
428

        """
429
        raise NotImplementedError(about._errors.cstring(
430
            "ERROR: no generic instance method 'enforce_power'."))
Marco Selig's avatar
Marco Selig committed
431

432
    def check_codomain(self, codomain):
Marco Selig's avatar
Marco Selig committed
433
        """
434
            Checks whether a given codomain is compatible to the space or not.
Marco Selig's avatar
Marco Selig committed
435
436
437

            Parameters
            ----------
438
439
            codomain : nifty.space
                Space to be checked for compatibility.
Marco Selig's avatar
Marco Selig committed
440
441
442

            Returns
            -------
443
444
            check : bool
                Whether or not the given codomain is compatible to the space.
Marco Selig's avatar
Marco Selig committed
445
        """
446
        raise NotImplementedError(about._errors.cstring(
447
            "ERROR: no generic instance method 'check_codomain'."))
Marco Selig's avatar
Marco Selig committed
448

449
    def get_codomain(self, **kwargs):
Marco Selig's avatar
Marco Selig committed
450
        """
451
452
453
            Generates a compatible codomain to which transformations are
            reasonable, usually either the position basis or the basis of
            harmonic eigenmodes.
Marco Selig's avatar
Marco Selig committed
454
455
456

            Parameters
            ----------
457
458
459
460
            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
Ultimanet's avatar
Ultimanet committed
461
                (default: None).
462
463
464
465
            conest : list, *optional*
                List of nested spaces of the codomain (default: None).
            coorder : list, *optional*
                Permutation of the list of nested spaces (default: None).
Marco Selig's avatar
Marco Selig committed
466
467
468

            Returns
            -------
469
470
            codomain : nifty.space
                A compatible codomain.
Ultimanet's avatar
Ultimanet committed
471
        """
472
        raise NotImplementedError(about._errors.cstring(
473
            "ERROR: no generic instance method 'get_codomain'."))
Marco Selig's avatar
Marco Selig committed
474

475
    def get_random_values(self, **kwargs):
Marco Selig's avatar
Marco Selig committed
476
        """
Ultimanet's avatar
Ultimanet committed
477
478
            Generates random field values according to the specifications given
            by the parameters.
Marco Selig's avatar
Marco Selig committed
479

Ultimanet's avatar
Ultimanet committed
480
481
482
483
484
485
486
            Returns
            -------
            x : numpy.ndarray
                Valid field values.

            Other parameters
            ----------------
Marco Selig's avatar
Marco Selig committed
487
            random : string, *optional*
Ultimanet's avatar
Ultimanet committed
488
489
490
                Specifies the probability distribution from which the random
                numbers are to be drawn.
                Supported distributions are:
Marco Selig's avatar
Marco Selig committed
491
492

                - "pm1" (uniform distribution over {+1,-1} or {+1,+i,-1,-i}
493
494
                - "gau" (normal distribution with zero-mean and a given
                    standard deviation or variance)
Marco Selig's avatar
Marco Selig committed
495
496
497
498
                - "syn" (synthesizes from a given power spectrum)
                - "uni" (uniform distribution over [vmin,vmax[)

                (default: None).
Ultimanet's avatar
Ultimanet committed
499
500
501
502
503
            dev : float, *optional*
                Standard deviation (default: 1).
            var : float, *optional*
                Variance, overriding `dev` if both are specified
                (default: 1).
504
505
            spec : {scalar, list, numpy.ndarray, nifty.field, function},
                    *optional*
Ultimanet's avatar
Ultimanet committed
506
                Power spectrum (default: 1).
507
508
509
510
            pindex : numpy.ndarray, *optional*
                Indexing array giving the power spectrum index of each band
                (default: None).
            kindex : numpy.ndarray, *optional*
Ultimanet's avatar
Ultimanet committed
511
                Scale of each band (default: None).
512
            codomain : nifty.space, *optional*
Ultimanet's avatar
Ultimanet committed
513
                A compatible codomain with power indices (default: None).
514
            log : bool, *optional*
515
516
                Flag specifying if the spectral binning is performed on
                logarithmic
517
518
519
520
                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*
521
522
                Number of used spectral bins; if given `log` is set to
                ``False``;
523
524
525
526
527
                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
528
529
                (default: None).
            vmin : {scalar, list, ndarray, field}, *optional*
530
531
                Lower limit of the uniform distribution if ``random == "uni"``
                (default: 0).
Ultimanet's avatar
Ultimanet committed
532
533
534
535
            vmin : float, *optional*
                Lower limit for a uniform distribution (default: 0).
            vmax : float, *optional*
                Upper limit for a uniform distribution (default: 1).
Marco Selig's avatar
Marco Selig committed
536
        """
537
538
        raise NotImplementedError(about._errors.cstring(
            "ERROR: no generic instance method 'get_random_values'."))
Marco Selig's avatar
Marco Selig committed
539

540
    def calc_weight(self, x, power=1):
Marco Selig's avatar
Marco Selig committed
541
        """
542
543
            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
544
545
546

            Parameters
            ----------
547
548
549
550
            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
551
552
553

            Returns
            -------
554
555
            y : numpy.ndarray
                Weighted array.
Marco Selig's avatar
Marco Selig committed
556
        """
557
        raise NotImplementedError(about._errors.cstring(
558
            "ERROR: no generic instance method 'calc_weight'."))
Marco Selig's avatar
Marco Selig committed
559

560
561
562
    def get_weight(self, power=1):
        raise NotImplementedError(about._errors.cstring(
            "ERROR: no generic instance method 'get_weight'."))
Marco Selig's avatar
Marco Selig committed
563

564
    def calc_dot(self, x, y):
Marco Selig's avatar
Marco Selig committed
565
        """
566
567
            Computes the discrete inner product of two given arrays of field
            values.
Marco Selig's avatar
Marco Selig committed
568
569
570

            Parameters
            ----------
571
572
573
574
            x : numpy.ndarray
                First array
            y : numpy.ndarray
                Second array
Marco Selig's avatar
Marco Selig committed
575
576
577

            Returns
            -------
578
579
            dot : scalar
                Inner product of the two arrays.
Ultimanet's avatar
Ultimanet committed
580
        """
581
        raise NotImplementedError(about._errors.cstring(
582
            "ERROR: no generic instance method 'dot'."))
Marco Selig's avatar
Marco Selig committed
583

584
    def calc_transform(self, x, codomain=None, **kwargs):
Marco Selig's avatar
Marco Selig committed
585
        """
586
            Computes the transform of a given array of field values.
Marco Selig's avatar
Marco Selig committed
587

Ultimanet's avatar
Ultimanet committed
588
589
            Parameters
            ----------
590
591
592
593
594
            x : numpy.ndarray
                Array to be transformed.
            codomain : nifty.space, *optional*
                codomain space to which the transformation shall map
                (default: self).
Marco Selig's avatar
Marco Selig committed
595
596
597

            Returns
            -------
Ultimanet's avatar
Ultimanet committed
598
599
            Tx : numpy.ndarray
                Transformed array
600

Ultimanet's avatar
Ultimanet committed
601
602
603
604
            Other parameters
            ----------------
            iter : int, *optional*
                Number of iterations performed in specific transformations.
605
        """
606
607
        raise NotImplementedError(about._errors.cstring(
            "ERROR: no generic instance method 'calc_transform'."))
Marco Selig's avatar
Marco Selig committed
608

609
    def calc_smooth(self, x, sigma=0, **kwargs):
Marco Selig's avatar
Marco Selig committed
610
        """
Ultimanet's avatar
Ultimanet committed
611
612
            Smoothes an array of field values by convolution with a Gaussian
            kernel.
Marco Selig's avatar
Marco Selig committed
613
614
615

            Parameters
            ----------
Ultimanet's avatar
Ultimanet committed
616
617
618
619
620
            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).
Marco Selig's avatar
Marco Selig committed
621
622
623

            Returns
            -------
Ultimanet's avatar
Ultimanet committed
624
625
            Gx : numpy.ndarray
                Smoothed array.
Marco Selig's avatar
Marco Selig committed
626

Ultimanet's avatar
Ultimanet committed
627
628
629
630
            Other parameters
            ----------------
            iter : int, *optional*
                Number of iterations (default: 0).
Marco Selig's avatar
Marco Selig committed
631
        """
632
633
        raise NotImplementedError(about._errors.cstring(
            "ERROR: no generic instance method 'calc_smooth'."))
Marco Selig's avatar
Marco Selig committed
634

635
    def calc_power(self, x, **kwargs):
Marco Selig's avatar
Marco Selig committed
636
        """
Ultimanet's avatar
Ultimanet committed
637
            Computes the power of an array of field values.
Marco Selig's avatar
Marco Selig committed
638
639
640

            Parameters
            ----------
Ultimanet's avatar
Ultimanet committed
641
642
643
            x : numpy.ndarray
                Array containing the field values of which the power is to be
                calculated.
Marco Selig's avatar
Marco Selig committed
644
645
646
647

            Returns
            -------
            spec : numpy.ndarray
Ultimanet's avatar
Ultimanet committed
648
                Power contained in the input array.
Marco Selig's avatar
Marco Selig committed
649
650
651

            Other parameters
            ----------------
Ultimanet's avatar
Ultimanet committed
652
653
654
            pindex : numpy.ndarray, *optional*
                Indexing array assigning the input array components to
                components of the power spectrum (default: None).
655
            kindex : numpy.ndarray, *optional*
Ultimanet's avatar
Ultimanet committed
656
657
658
659
                Scale corresponding to each band in the power spectrum
                (default: None).
            rho : numpy.ndarray, *optional*
                Number of degrees of freedom per band (default: None).
660
661
662
            codomain : nifty.space, *optional*
                A compatible codomain for power indexing (default: None).
            log : bool, *optional*
663
664
                Flag specifying if the spectral binning is performed on
                logarithmic
665
666
667
668
                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*
669
670
                Number of used spectral bins; if given `log` is set to
                ``False``;
671
672
673
674
675
                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
676
677
                (default: None).
            vmin : {scalar, list, ndarray, field}, *optional*
678
679
                Lower limit of the uniform distribution if ``random == "uni"``
                (default: 0).
680

Marco Selig's avatar
Marco Selig committed
681
        """
682
683
        raise NotImplementedError(about._errors.cstring(
            "ERROR: no generic instance method 'calc_power'."))
Marco Selig's avatar
Marco Selig committed
684

685
686
687
688
689
690
691
    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'."))
Marco Selig's avatar
Marco Selig committed
692

693
    def get_plot(self, x, **kwargs):
Marco Selig's avatar
Marco Selig committed
694
        """
Ultimanet's avatar
Ultimanet committed
695
696
            Creates a plot of field values according to the specifications
            given by the parameters.
697
698
699

            Parameters
            ----------
Ultimanet's avatar
Ultimanet committed
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
736
737
738
739
740
741
742
743
744
            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*
745
746
                Flag specifying if the spectral binning is performed on
                logarithmic
747
748
749
                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).
Ultimanet's avatar
Ultimanet committed
750
            nbin : integer, *optional*
751
752
                Number of used spectral bins; if given `log` is set to
                ``False``;
753
                integers below the minimum of 3 induce an automatic setting;
754
                by default no binning is done (default: None).
Ultimanet's avatar
Ultimanet committed
755
            binbounds : {list, array}, *optional*
756
757
                User specific inner boundaries of the bins, which are preferred
                over the above parameters; by default no binning is done
758
759
                (default: None).
            vmin : {scalar, list, ndarray, field}, *optional*
Ultimanet's avatar
Ultimanet committed
760
761
762
763
                Lower limit of the uniform distribution if ``random == "uni"``
                (default: 0).
            iter : int, *optional*
                Number of iterations (default: 0).
Marco Selig's avatar
Marco Selig committed
764
765

        """
766
767
        raise NotImplementedError(about._errors.cstring(
            "ERROR: no generic instance method 'get_plot'."))
Marco Selig's avatar
Marco Selig committed
768

Ultimanet's avatar
Ultimanet committed
769
770
    def __repr__(self):
        return "<nifty_core.space>"
Marco Selig's avatar
Marco Selig committed
771

Ultimanet's avatar
Ultimanet committed
772
    def __str__(self):
773
774
        return "nifty_core.space instance\n- para     = " + str(self.para) + \
            "\n- dtype = " + str(self.dtype.type)
Marco Selig's avatar
Marco Selig committed
775
776


Ultimanet's avatar
Ultimanet committed
777
class point_space(space):
Marco Selig's avatar
Marco Selig committed
778
    """
Ultimanet's avatar
Ultimanet committed
779
780
781
782
783
784
785
        ..                            __             __
        ..                          /__/           /  /_
        ..      ______    ______    __   __ ___   /   _/
        ..    /   _   | /   _   | /  / /   _   | /  /
        ..   /  /_/  / /  /_/  / /  / /  / /  / /  /_
        ..  /   ____/  \______/ /__/ /__/ /__/  \___/  space class
        .. /__/
Marco Selig's avatar
Marco Selig committed
786

Ultimanet's avatar
Ultimanet committed
787
        NIFTY subclass for unstructured spaces.
Marco Selig's avatar
Marco Selig committed
788

Ultimanet's avatar
Ultimanet committed
789
790
        Unstructured spaces are lists of values without any geometrical
        information.
Marco Selig's avatar
Marco Selig committed
791
792
793

        Parameters
        ----------
Ultimanet's avatar
Ultimanet committed
794
795
        num : int
            Number of points.
796
        dtype : numpy.dtype, *optional*
Ultimanet's avatar
Ultimanet committed
797
            Data type of the field values (default: None).
Marco Selig's avatar
Marco Selig committed
798

Ultimanet's avatar
Ultimanet committed
799
        Attributes
Marco Selig's avatar
Marco Selig committed
800
        ----------
Ultimanet's avatar
Ultimanet committed
801
802
        para : numpy.ndarray
            Array containing the number of points.
803
        dtype : numpy.dtype
Ultimanet's avatar
Ultimanet committed
804
805
806
807
808
809
            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
810
    """
811

812
813
    def __init__(self, num, dtype=np.dtype('float'), datamodel='fftw',
                 comm=gc['default_comm']):
Ultimanet's avatar
Ultimanet committed
814
815
        """
            Sets the attributes for a point_space class instance.
Marco Selig's avatar
Marco Selig committed
816

Ultimanet's avatar
Ultimanet committed
817
818
819
820
            Parameters
            ----------
            num : int
                Number of points.
821
            dtype : numpy.dtype, *optional*
Ultimanet's avatar
Ultimanet committed
822
                Data type of the field values (default: numpy.float64).
Marco Selig's avatar
Marco Selig committed
823

Ultimanet's avatar
Ultimanet committed
824
825
826
827
            Returns
            -------
            None.
        """
828
829
        self.paradict = point_space_paradict(num=num)

830
831
        # parse dtype
        dtype = np.dtype(dtype)
Ultima's avatar
Ultima committed
832
833
834
835
836
837
838
839
840
841
842
        if dtype not in [np.dtype('bool'),
                         np.dtype('int8'),
                         np.dtype('int16'),
                         np.dtype('int32'),
                         np.dtype('int64'),
                         np.dtype('float16'),
                         np.dtype('float32'),
                         np.dtype('float64'),
                         np.dtype('complex64'),
                         np.dtype('complex128')]:
            raise ValueError(about._errors.cstring(
843
                             "WARNING: incompatible dtype: " + str(dtype)))
Ultima's avatar
Ultima committed
844
        self.dtype = dtype
845
846

        if datamodel not in ['np'] + POINT_DISTRIBUTION_STRATEGIES:
Ultima's avatar
Ultima committed
847
            about._errors.cstring("WARNING: datamodel set to default.")
848
            self.datamodel = \
849
                gc['default_distribution_strategy']
850
851
        else:
            self.datamodel = datamodel
852

853
        self.comm = self._parse_comm(comm)
Ultimanet's avatar
Ultimanet committed
854
        self.discrete = True
855
        self.harmonic = False
856
        self.distances = (np.float(1),)
Marco Selig's avatar
Marco Selig committed
857

Ultimanet's avatar
Ultimanet committed
858
859
860
861
    @property
    def para(self):
        temp = np.array([self.paradict['num']], dtype=int)
        return temp
862

Ultimanet's avatar
Ultimanet committed
863
864
    @para.setter
    def para(self, x):
Ultima's avatar
Ultima committed
865
        self.paradict['num'] = x[0]
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
    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()
                ]
        # Return the sorted identifiers as a tuple.
        return tuple(sorted(temp))

    def _parse_comm(self, comm):
        # check if comm is a string -> the name of comm is given
        # -> Extract it from the mpi_module
        if isinstance(comm, str):
            if gc.validQ('default_comm', comm):
                result_comm = getattr(gdi[gc['mpi_module']], comm)
            else:
                raise ValueError(about._errors.cstring(
                    "ERROR: The given communicator-name is not supported."))
        # check if the given comm object is an instance of default Intracomm
        else:
            if isinstance(comm, gdi[gc['mpi_module']].Intracomm):
                result_comm = comm
            else:
                raise ValueError(about._errors.cstring(
                    "ERROR: The given comm object is not an instance of the " +
                    "default-MPI-module's Intracomm Class."))
        return result_comm

895
    def copy(self):
896
        return point_space(num=self.paradict['num'],
897
                           dtype=self.dtype,
898
899
                           datamodel=self.datamodel)

Ultimanet's avatar
Ultimanet committed
900
901
    def getitem(self, data, key):
        return data[key]
Marco Selig's avatar
Marco Selig committed
902

Ultimanet's avatar
Ultimanet committed
903
    def setitem(self, data, update, key):
904
        data[key] = update
Marco Selig's avatar
Marco Selig committed
905

Ultimanet's avatar
Ultimanet committed
906
    def apply_scalar_function(self, x, function, inplace=False):
907
        if self.datamodel == 'np':
908
            if not inplace:
909
                try:
910
911
912
913
914
915
916
917
918
                    return function(x)
                except:
                    return np.vectorize(function)(x)
            else:
                try:
                    x[:] = function(x)
                except:
                    x[:] = np.vectorize(function)(x)
                return x
919
920

        elif self.datamodel in POINT_DISTRIBUTION_STRATEGIES:
921
            return x.apply_scalar_function(function, inplace=inplace)
Ultimanet's avatar
Ultimanet committed
922
        else:
923
924
925
            raise NotImplementedError(about._errors.cstring(
                "ERROR: function is not implemented for given datamodel."))

Ultimanet's avatar
Ultimanet committed
926
927
928
929
    def unary_operation(self, x, op='None', **kwargs):
        """
        x must be a numpy array which is compatible with the space!
        Valid operations are
930

Ultimanet's avatar
Ultimanet committed
931
        """
932
        if self.datamodel == 'np':
933
934
935
936
            def _argmin(z, **kwargs):
                ind = np.argmin(z, **kwargs)
                if np.isscalar(ind):
                    ind = np.unravel_index(ind, z.shape, order='C')
937
                    if(len(ind) == 1):
938
                        return ind[0]
939
940
                return ind

941
942
943
944
            def _argmax(z, **kwargs):
                ind = np.argmax(z, **kwargs)
                if np.isscalar(ind):
                    ind = np.unravel_index(ind, z.shape, order='C')
945
                    if(len(ind) == 1):
946
                        return ind[0]
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
                return ind

            translation = {"pos": lambda y: getattr(y, '__pos__')(),
                           "neg": lambda y: getattr(y, '__neg__')(),
                           "abs": lambda y: getattr(y, '__abs__')(),
                           "real": lambda y: getattr(y, 'real'),
                           "imag": lambda y: getattr(y, 'imag'),
                           "nanmin": np.nanmin,
                           "amin": np.amin,
                           "nanmax": np.nanmax,
                           "amax": 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,
                           "sum": np.sum,
                           "prod": np.prod,
                           "unique": np.unique,
                           "copy": np.copy,
                           "isnan": np.isnan,
                           "isinf": np.isinf,
                           "isfinite": np.isfinite,
                           "nan_to_num": np.nan_to_num,
                           "None": lambda y: y}

        elif self.datamodel in POINT_DISTRIBUTION_STRATEGIES:
            translation = {"pos": lambda y: getattr(y, '__pos__')(),
                           "neg": lambda y: getattr(y, '__neg__')(),
                           "abs": lambda y: getattr(y, '__abs__')(),
                           "real": lambda y: getattr(y, 'real'),
                           "imag": lambda y: getattr(y, 'imag'),
                           "nanmin": lambda y: getattr(y, 'nanmin')(),
                           "amin": lambda y: getattr(y, 'amin')(),
                           "nanmax": lambda y: getattr(y, 'nanmax')(),
                           "amax": lambda y: getattr(y, 'amax')(),
                           "median": lambda y: getattr(y, 'median')(),
                           "mean": lambda y: getattr(y, 'mean')(),
                           "std": lambda y: getattr(y, 'std')(),
                           "var": lambda y: getattr(y, 'var')(),
                           "argmin": lambda y: getattr(y, 'argmin_nonflat')(),
                           "argmin_flat": lambda y: getattr(y, 'argmin')(),
                           "argmax": lambda y: getattr(y, 'argmax_nonflat')(),
                           "argmax_flat": lambda y: getattr(y, 'argmax')(),
                           "conjugate": lambda y: getattr(y, 'conjugate')(),
                           "sum": lambda y: getattr(y, 'sum')(),
                           "prod": lambda y: getattr(y, 'prod')(),
                           "unique": lambda y: getattr(y, 'unique')(),
                           "copy": lambda y: getattr(y, 'copy')(),
                           "isnan": lambda y: getattr(y, 'isnan')(),
                           "isinf": lambda y: getattr(y, 'isinf')(),
                           "isfinite": lambda y: getattr(y, 'isfinite')(),
                           "nan_to_num": lambda y: getattr(y, 'nan_to_num')(),
                           "None": lambda y: y}
1005
1006
1007
        else:
            raise NotImplementedError(about._errors.cstring(
                "ERROR: function is not implemented for given datamodel."))
Marco Selig's avatar
Marco Selig committed
1008

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

Ultimanet's avatar
Ultimanet committed
1011
    def binary_operation(self, x, y, op='None', cast=0):
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035

        translation = {"add": lambda z: getattr(z, '__add__'),
                       "radd": lambda z: getattr(z, '__radd__'),
                       "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__'),
                       "rmul": lambda z: getattr(z, '__rmul__'),
                       "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__'),
                       "ne": lambda z: getattr(z, '__ne__'),
                       "lt": lambda z: getattr(z, '__lt__'),
                       "le": lambda z: getattr(z, '__le__'),
                       "eq": lambda z: getattr(z, '__eq__'),
                       "ge": lambda z: getattr(z, '__ge__'),
                       "gt": lambda z: getattr(z, '__gt__'),
                       "None": lambda z: lambda u: u}

Ultimanet's avatar
Ultimanet committed
1036
1037
1038
        if (cast & 1) != 0:
            x = self.cast(x)
        if (cast & 2) != 0:
1039
1040
            y = self.cast(y)

Ultimanet's avatar
Ultimanet committed
1041
        return translation[op](x)(y)
Marco Selig's avatar
Marco Selig committed
1042

1043
    def get_norm(self, x, q=2):
Ultimanet's avatar
Ultimanet committed
1044
1045
        """
            Computes the Lq-norm of field values.
Marco Selig's avatar
Marco Selig committed
1046

Ultimanet's avatar
Ultimanet committed
1047
1048
            Parameters
            ----------
1049
1050
            x : np.ndarray
                The data array
Ultimanet's avatar
Ultimanet committed
1051
1052
            q : scalar
                Parameter q of the Lq-norm (default: 2).
Marco Selig's avatar
Marco Selig committed
1053

Ultimanet's avatar
Ultimanet committed
1054
1055
1056
1057
            Returns
            -------
            norm : scalar
                The Lq-norm of the field values.
Marco Selig's avatar
Marco Selig committed
1058

Ultimanet's avatar
Ultimanet committed
1059
        """
1060
        if q == 2:
1061
            result = self.calc_dot(x, x)
Ultimanet's avatar
Ultimanet committed
1062
        else:
1063
1064
            y = x**(q - 1)
            result = self.calc_dot(x, y)
Marco Selig's avatar
Marco Selig committed
1065

1066
1067
        result = result**(1. / q)
        return result
Marco Selig's avatar
Marco Selig committed
1068

1069
    def get_shape(self):
1070
        return (self.paradict['num'],)
Marco Selig's avatar
Marco Selig committed
1071

1072
    def get_dim(self, split=False):
Ultimanet's avatar
Ultimanet committed
1073
1074
        """
            Computes the dimension of the space, i.e.\  the number of points.
Marco Selig's avatar
Marco Selig committed
1075

Ultimanet's avatar
Ultimanet committed
1076
1077
1078
1079
1080
            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
1081

Ultimanet's avatar
Ultimanet committed
1082
1083
1084
1085
1086
            Returns
            -------
            dim : {int, numpy.ndarray}
                Dimension(s) of the space.
        """
1087
        if split:
1088
            return self.get_shape()
Ultimanet's avatar
Ultimanet committed
1089
        else:
1090
            return np.prod(self.get_shape())
Marco Selig's avatar
Marco Selig committed
1091

1092
    def get_dof(self, split=False):
Ultimanet's avatar
Ultimanet committed
1093
1094
1095
1096
        """
            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
1097

Ultimanet's avatar
Ultimanet committed
1098
1099
1100
1101
1102
            Returns
            -------
            dof : int
                Number of degrees of freedom of the space.
        """
1103
1104
1105
1106
1107
1108
1109
1110
1111
        pre_dof = self.get_dim(split=split)
        if issubclass(self.dtype.type, np.complexfloating):
            return pre_dof * 2
        else:
            return pre_dof

    def get_vol(self, split=False):
        if split:
            return self.distances
Ultimanet's avatar
Ultimanet committed
1112
        else:
1113
            return np.prod(self.distances)
Marco Selig's avatar
Marco Selig committed
1114

1115
    def get_meta_volume(self, split=False):
Marco Selig's avatar
Marco Selig committed
1116
        """
1117
            Calculates the meta volumes.
Ultimanet's avatar
Ultimanet committed
1118

1119
1120
1121
1122
1123
            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
1124
1125
1126

            Parameters
            ----------
1127
1128
1129
            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
1130
1131
1132

            Returns
            -------
1133
1134
            mol : {numpy.ndarray, float}
                Meta volume of the pixels or the complete space.
Ultimanet's avatar
Ultimanet committed
1135
        """
1136
1137
1138
1139
1140
        if not split:
            return self.get_dim() * self.get_vol()
        else:
            mol = self.cast(1, dtype=np.dtype('float'))
            return self.calc_weight(mol, power=1)
1141

Ultima's avatar