nifty_rg.py 99.6 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) 2015 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

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

Marco Selig's avatar
Marco Selig committed
31
    NIFTY submodule for regular Cartesian grids.
Marco Selig's avatar
Marco Selig committed
32
33
34

"""
from __future__ import division
Ultimanet's avatar
Ultimanet committed
35

Marco Selig's avatar
Marco Selig committed
36
37
import os
import numpy as np
38
from scipy.special import erf
Marco Selig's avatar
Marco Selig committed
39
40
41
import pylab as pl
from matplotlib.colors import LogNorm as ln
from matplotlib.ticker import LogFormatter as lf
Ultimanet's avatar
Ultimanet committed
42

43
44
45
from nifty.nifty_core import point_space,\
                             field
import nifty_fft
46
from nifty.keepers import about,\
Ultima's avatar
Ultima committed
47
48
                          global_dependency_injector as gdi,\
                          global_configuration as gc
49
from nifty.nifty_mpi_data import distributed_data_object
50
from nifty.nifty_mpi_data import STRATEGIES as DISTRIBUTION_STRATEGIES
Ultimanet's avatar
Ultimanet committed
51
from nifty.nifty_paradict import rg_space_paradict
52
53
from nifty.nifty_power_indices import rg_power_indices
from nifty.nifty_random import random
Ultima's avatar
Ultima committed
54
import nifty.nifty_utilities as utilities
55

Ultima's avatar
Ultima committed
56
MPI = gdi[gc['mpi_module']]
57
RG_DISTRIBUTION_STRATEGIES = DISTRIBUTION_STRATEGIES['global']
Ultimanet's avatar
Ultimanet committed
58

Marco Selig's avatar
Marco Selig committed
59

60
class rg_space(point_space):
Marco Selig's avatar
Marco Selig committed
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
    """
        ..      _____   _______
        ..    /   __/ /   _   /
        ..   /  /    /  /_/  /
        ..  /__/     \____  /  space class
        ..          /______/

        NIFTY subclass for spaces of regular Cartesian grids.

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

        Notes
        -----
        Only even numbers of grid points per axis are supported.
        The basis transformations between position `x` and Fourier mode `k`
        rely on (inverse) fast Fourier transformations using the
        :math:`exp(2 \pi i k^\dagger x)`-formulation.

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

123
124
125
    def __init__(self, num, zerocenter=False, complexity=0, dist=None,
                 harmonic=False, datamodel='fftw', fft_module='pyfftw',
                 comm=gc['default_comm']):
Marco Selig's avatar
Marco Selig committed
126
127
128
129
130
131
132
133
134
135
136
137
        """
            Sets the attributes for an rg_space class instance.

            Parameters
            ----------
            num : {int, numpy.ndarray}
                Number of gridpoints or numbers of gridpoints along each axis.
            naxes : int, *optional*
                Number of axes (default: None).
            zerocenter : {bool, numpy.ndarray}, *optional*
                Whether the Fourier zero-mode is located in the center of the
                grid (or the center of each axis speparately) or not
Ultimanet's avatar
Ultimanet committed
138
                (default: False).
Marco Selig's avatar
Marco Selig committed
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
            hermitian : bool, *optional*
                Whether the fields living in the space follow hermitian
                symmetry or not (default: True).
            purelyreal : bool, *optional*
                Whether the field values are purely real (default: True).
            dist : {float, numpy.ndarray}, *optional*
                Distance between two grid points along each axis
                (default: None).
            fourier : bool, *optional*
                Whether the space represents a Fourier or a position grid
                (default: False).

            Returns
            -------
            None
        """
155
156
157
158

        self.paradict = rg_space_paradict(num=num,
                                          complexity=complexity,
                                          zerocenter=zerocenter)
159
        # set dtype
160
        if self.paradict['complexity'] == 0:
161
            self.dtype = np.dtype('float64')
Marco Selig's avatar
Marco Selig committed
162
        else:
163
            self.dtype = np.dtype('complex128')
164
165
166

        # set datamodel
        if datamodel not in ['np'] + RG_DISTRIBUTION_STRATEGIES:
167
            about.warnings.cprint("WARNING: datamodel set to default.")
168
            self.datamodel = \
Ultima's avatar
Ultima committed
169
                gc['default_distribution_strategy']
170
171
172
        else:
            self.datamodel = datamodel

173
174
175
176
177
178
        # set volume/distances
        naxes = len(self.paradict['num'])
        if dist is None:
            dist = 1 / np.array(self.paradict['num'], dtype=np.float)
        elif np.isscalar(dist):
            dist = np.ones(naxes, dtype=np.float) * dist
Marco Selig's avatar
Marco Selig committed
179
        else:
180
181
182
183
            dist = np.array(dist, dtype=np.float)
            if np.size(dist) == 1:
                dist = dist * np.ones(naxes, dtype=np.float)
            if np.size(dist) != naxes:
184
185
186
                raise ValueError(about._errors.cstring(
                    "ERROR: size mismatch ( " + str(np.size(dist)) + " <> " +
                    str(naxes) + " )."))
187
        if np.any(dist <= 0):
188
            raise ValueError(about._errors.cstring(
189
                "ERROR: nonpositive distance(s)."))
Marco Selig's avatar
Marco Selig committed
190

191
192
193
194
195
        self.distances = tuple(dist)
        self.harmonic = bool(harmonic)
        self.discrete = False

        self.comm = self._parse_comm(comm)
Ultima's avatar
Ultima committed
196

197
198
        # Initializes the fast-fourier-transform machine, which will be used
        # to transform the space
Ultima's avatar
Ultima committed
199
200
201
        if not gc.validQ('fft_module', fft_module):
            fft_module = gc['fft_module']
        self.fft_machine = nifty_fft.fft_factory(fft_module)
202
203
204
205

        # Initialize the power_indices object which takes care of kindex,
        # pindex, rho and the pundex for a given set of parameters
        if self.harmonic:
206
207
208
209
210
211
212
            self.power_indices = rg_power_indices(
                    shape=self.get_shape(),
                    dgrid=dist,
                    zerocentered=self.paradict['zerocenter'],
                    comm=self.comm,
                    datamodel=self.datamodel,
                    allowed_distribution_strategies=RG_DISTRIBUTION_STRATEGIES)
213

214
215
    @property
    def para(self):
216
217
218
        temp = np.array(self.paradict['num'] +
                        [self.paradict['complexity']] +
                        self.paradict['zerocenter'], dtype=int)
219
        return temp
220

221
222
    @para.setter
    def para(self, x):
223
224
225
        self.paradict['num'] = x[:(np.size(x) - 1) // 2]
        self.paradict['zerocenter'] = x[(np.size(x) + 1) // 2:]
        self.paradict['complexity'] = x[(np.size(x) - 1) // 2]
Ultimanet's avatar
Ultimanet committed
226

227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
    # __identiftier__ returns an object which contains all information needed
    # to uniquely identify a space. It returns a (immutable) tuple which
    # therefore can be compared.
    # The rg_space version of __identifier__ filters out the vars-information
    # which is describing the rg_space's structure
    def _identifier(self):
        # Extract the identifying parts from the vars(self) dict.
        temp = [(ii[0],
                 ((lambda x: tuple(x) if
                  isinstance(x, np.ndarray) else x)(ii[1])))
                for ii in vars(self).iteritems()
                if ii[0] not in ['fft_machine', 'power_indices', 'comm']]
        temp.append(('comm', self.comm.__hash__()))
        # Return the sorted identifiers as a tuple.
        return tuple(sorted(temp))
Ultimanet's avatar
Ultimanet committed
242

243
    def copy(self):
244
245
246
        return rg_space(num=self.paradict['num'],
                        complexity=self.paradict['complexity'],
                        zerocenter=self.paradict['zerocenter'],
247
248
                        dist=self.distances,
                        harmonic=self.harmonic,
249
                        datamodel=self.datamodel)
250
251

    def get_shape(self):
252
        return tuple(self.paradict['num'])
Marco Selig's avatar
Marco Selig committed
253

254
255
256
257
258
259
260
261
262
263
    def _cast_to_d2o(self, x, dtype=None, hermitianize=True, **kwargs):
        casted_x = super(rg_space, self)._cast_to_d2o(x=x,
                                                      dtype=dtype,
                                                      **kwargs)
        if hermitianize and self.paradict['complexity'] == 1 and \
           not casted_x.hermitian:
            about.warnings.cflush(
                 "WARNING: Data gets hermitianized. This operation is " +
                 "extremely expensive\n")
            casted_x = utilities.hermitianize(casted_x)
Marco Selig's avatar
Marco Selig committed
264

265
        return casted_x
266

267
268
269
270
271
272
273
274
275
    def _cast_to_np(self, x, dtype=None, hermitianize=True, **kwargs):
        casted_x = super(rg_space, self)._cast_to_np(x=x,
                                                     dtype=dtype,
                                                     **kwargs)
        if hermitianize and self.paradict['complexity'] == 1:
            about.warnings.cflush(
                 "WARNING: Data gets hermitianized. This operation is " +
                 "extremely expensive\n")
            casted_x = utilities.hermitianize(casted_x)
Marco Selig's avatar
Marco Selig committed
276

277
        return casted_x
ultimanet's avatar
ultimanet committed
278

279
280
    def enforce_power(self, spec, size=None, kindex=None, codomain=None,
                      log=False, nbin=None, binbounds=None):
Marco Selig's avatar
Marco Selig committed
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
        """
            Provides a valid power spectrum array from a given object.

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

            Returns
            -------
            spec : numpy.ndarray
                Valid power spectrum.

            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*
305
306
307
                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
308
                binning is done (default: None).
Marco Selig's avatar
Marco Selig committed
309
            nbin : integer, *optional*
310
                Number of used spectral bins; if given `log` is set to
311
312
                ``False``; iintegers below the minimum of 3 induce an automatic
                setting; by default no binning is done (default: None).
Marco Selig's avatar
Marco Selig committed
313
314
315
            binbounds : {list, array}, *optional*
                User specific inner boundaries of the bins, which are preferred
                over the above parameters; by default no binning is done
316
                (default: None).
Marco Selig's avatar
Marco Selig committed
317
        """
318
319
320
321
322
323
324

        # Setting up the local variables: kindex
        # The kindex is only necessary if spec is a function or if
        # the size is not set explicitly
        if kindex is None and (size is None or callable(spec)):
            # Determine which space should be used to get the kindex
            if self.harmonic:
325
326
                kindex_supply_space = self
            else:
327
328
                # Check if the given codomain is compatible with the space
                try:
329
330
331
                    assert(self.check_codomain(codomain))
                    kindex_supply_space = codomain
                except(AssertionError):
332
333
334
335
                    about.warnings.cprint("WARNING: Supplied codomain is " +
                                          "incompatible. Generating a " +
                                          "generic codomain. This can " +
                                          "be expensive!")
336
337
                    kindex_supply_space = self.get_codomain()
            kindex = kindex_supply_space.\
338
339
340
                power_indices.get_index_dict(log=log, nbin=nbin,
                                             binbounds=binbounds)['kindex']

341
342
343
        return self._enforce_power_helper(spec=spec,
                                          size=size,
                                          kindex=kindex)
344

345
    def check_codomain(self, codomain):
Marco Selig's avatar
Marco Selig committed
346
        """
347
            Checks whether a given codomain is compatible to the space or not.
Marco Selig's avatar
Marco Selig committed
348
349
350

            Parameters
            ----------
351
352
            codomain : nifty.space
                Space to be checked for compatibility.
Marco Selig's avatar
Marco Selig committed
353
354
355

            Returns
            -------
356
357
            check : bool
                Whether or not the given codomain is compatible to the space.
Marco Selig's avatar
Marco Selig committed
358
        """
359
360
        if codomain is None:
            return False
361

362
363
        if not isinstance(codomain, rg_space):
            raise TypeError(about._errors.cstring("ERROR: invalid input."))
364

365
366
367
368
369
370
        if self.datamodel is not codomain.datamodel:
            return False
        # check number of number and size of axes
        if not np.all(np.array(self.paradict['num']) ==
                      np.array(codomain.paradict['num'])):
            return False
Ultima's avatar
Ultima committed
371

372
373
374
        # check harmonic flag
        if self.harmonic == codomain.harmonic:
            return False
Ultima's avatar
Ultima committed
375

376
377
378
379
        # check complexity-type
        # prepare the shorthands
        dcomp = self.paradict['complexity']
        cocomp = codomain.paradict['complexity']
Ultima's avatar
Ultima committed
380

381
382
383
384
385
386
387
388
389
390
391
392
393
394
        # Case 1: if the domain is copmleteley complex
        # -> the codomain must be complex, too
        if dcomp == 2:
            if cocomp != 2:
                return False
        # Case 2: domain is hermitian
        # -> codmomain can be real. If it is marked as hermitian or even
        # fully complex, a warning is raised
        elif dcomp == 1:
            if cocomp > 0:
                about.warnings.cprint("WARNING: Unrecommended codomain! " +
                                      "The domain is hermitian, hence the " +
                                      "codomain should be restricted to " +
                                      "real values!")
Ultima's avatar
Ultima committed
395

396
397
398
399
400
401
402
403
404
405
        # Case 3: domain is real
        # -> codmain should be hermitian
        elif dcomp == 0:
            if cocomp == 2:
                about.warnings.cprint("WARNING: Unrecommended codomain! " +
                                      "The domain is real, hence the " +
                                      "codomain should be restricted to " +
                                      "hermitian configurations!")
            elif cocomp == 0:
                return False
Ultima's avatar
Ultima committed
406

407
408
409
410
411
412
        # Check if the distances match, i.e. dist'=1/(num*dist)
        if not np.all(
                np.absolute(np.array(self.paradict['num']) *
                            np.array(self.distances) *
                            np.array(codomain.distances) - 1) < self.epsilon):
            return False
Ultima's avatar
Ultima committed
413

414
        return True
415

416
    def get_codomain(self, coname=None, cozerocenter=None, **kwargs):
Marco Selig's avatar
Marco Selig committed
417
        """
418
419
420
            Generates a compatible codomain to which transformations are
            reasonable, i.e.\  either a shifted grid or a Fourier conjugate
            grid.
Marco Selig's avatar
Marco Selig committed
421
422
423

            Parameters
            ----------
424
425
426
427
428
            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).
Marco Selig's avatar
Marco Selig committed
429
430
431

            Returns
            -------
432
433
            codomain : nifty.rg_space
                A compatible codomain.
Marco Selig's avatar
Marco Selig committed
434

435
436
437
438
439
440
            Notes
            -----
            Possible arguments for `coname` are ``'f'`` in which case the
            codomain arises from a Fourier transformation, ``'i'`` in which
            case it arises from an inverse Fourier transformation.If no
            `coname` is given, the Fourier conjugate grid is produced.
Marco Selig's avatar
Marco Selig committed
441
        """
442
443
444
445
446
447
448
449
        naxes = len(self.get_shape())
        # Parse the cozerocenter input
        if(cozerocenter is None):
            cozerocenter = self.paradict['zerocenter']
        # if the input is something scalar, cast it to a boolean
        elif(np.isscalar(cozerocenter)):
            cozerocenter = bool(cozerocenter)
        # if it is not a scalar...
Marco Selig's avatar
Marco Selig committed
450
        else:
451
452
453
454
455
456
457
458
459
460
461
            # ...cast it to a numpy array of booleans
            cozerocenter = np.array(cozerocenter, dtype=np.bool)
            # if it was a list of length 1, extract the boolean
            if(np.size(cozerocenter) == 1):
                cozerocenter = np.asscalar(cozerocenter)
            # if the length of the input does not match the number of
            # dimensions, raise an exception
            elif(np.size(cozerocenter) != naxes):
                raise ValueError(about._errors.cstring(
                    "ERROR: size mismatch ( " +
                    str(np.size(cozerocenter)) + " <> " + str(naxes) + " )."))
Marco Selig's avatar
Marco Selig committed
462

463
464
465
466
        # Set up the initialization variables
        num = self.paradict['num']
        dist = 1 / (np.array(self.paradict['num']) * np.array(self.distances))
        datamodel = self.datamodel
Marco Selig's avatar
Marco Selig committed
467

468
469
470
471
472
473
474
475
476
477
478
        complexity = {0: 1, 1: 0, 2: 2}[self.paradict['complexity']]

        if coname is None:
            harmonic = bool(not self.harmonic)
        elif coname[0] == 'f':
            harmonic = True
        elif coname[0] == 'i':
            harmonic = False
        else:
            raise ValueError(about._errors.cstring(
                "ERROR: Unknown coname keyword"))
Marco Selig's avatar
Marco Selig committed
479

480
481
482
483
484
485
486
        new_space = rg_space(num,
                             zerocenter=cozerocenter,
                             complexity=complexity,
                             dist=dist,
                             harmonic=harmonic,
                             datamodel=datamodel)
        return new_space
Marco Selig's avatar
Marco Selig committed
487

488
    def get_random_values(self, **kwargs):
Marco Selig's avatar
Marco Selig committed
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
        """
            Generates random field values according to the specifications given
            by the parameters, taking into account possible complex-valuedness
            and hermitian symmetry.

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

            Other parameters
            ----------------
            random : string, *optional*
                Specifies the probability distribution from which the random
                numbers are to be drawn.
                Supported distributions are:

                - "pm1" (uniform distribution over {+1,-1} or {+1,+i,-1,-i}
507
508
                - "gau" (normal distribution with zero-mean and a given
                    standard
Marco Selig's avatar
Marco Selig committed
509
510
511
512
513
514
515
516
517
518
                    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).
519
520
            spec : {scalar, list, numpy.ndarray, nifty.field, function},
                *optional*
Marco Selig's avatar
Marco Selig committed
521
522
523
524
525
526
527
                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.rg_space, *optional*
Ultimanet's avatar
Ultimanet committed
528
                A compatible codomain (default: None).
Marco Selig's avatar
Marco Selig committed
529
            log : bool, *optional*
530
531
                Flag specifying if the spectral binning is performed on
                    logarithmic
Marco Selig's avatar
Marco Selig committed
532
533
534
535
                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*
536
537
                Number of used spectral bins; if given `log` is set to
                    ``False``;
Marco Selig's avatar
Marco Selig committed
538
539
540
541
542
                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
543
                (default: None).
Ultimanet's avatar
Ultimanet committed
544
            vmin : float, *optional*
Marco Selig's avatar
Marco Selig committed
545
546
547
548
                Lower limit for a uniform distribution (default: 0).
            vmax : float, *optional*
                Upper limit for a uniform distribution (default: 1).
        """
549
550
551
552
        # TODO: Without hermitianization the random-methods from pointspace
        # could be used.

        # Parse the keyword arguments
553
        arg = random.parse_arguments(self, **kwargs)
554
555
556

        # Prepare the empty distributed_data_object
        sample = distributed_data_object(global_shape=self.get_shape(),
557
                                         dtype=self.dtype)
Ultimanet's avatar
Ultimanet committed
558

559
560
561
        # Should the output be hermitianized? This does not depend on the
        # hermitianize boolean in about, as it would yield in wrong,
        # not recoverable results
562

563
        hermitianizeQ = self.paradict['complexity']
Ultimanet's avatar
Ultimanet committed
564

565
        # Case 1: uniform distribution over {-1,+1}/{1,i,-1,-i}
566
567
568
        if arg[0] == 'pm1' and not hermitianizeQ:
            sample.apply_generator(lambda s: random.pm1(dtype=self.dtype,
                                                        shape=s))
569

570
        elif arg[0] == 'pm1' and hermitianizeQ:
571
            sample = self.get_random_values(random='uni', vmin=-1, vmax=1)
Ultimanet's avatar
Ultimanet committed
572
            local_data = sample.get_local_data()
573
            if issubclass(sample.dtype.type, np.complexfloating):
Ultimanet's avatar
Ultimanet committed
574
575
                temp_data = local_data.copy()
                local_data[temp_data.real >= 0.5] = 1
576
577
578
                local_data[(temp_data.real >= 0) * (temp_data.real < 0.5)] = -1
                local_data[(temp_data.real < 0) * (temp_data.imag >= 0)] = 1j
                local_data[(temp_data.real < 0) * (temp_data.imag < 0)] = -1j
Ultimanet's avatar
Ultimanet committed
579
580
581
582
            else:
                local_data[local_data >= 0] = 1
                local_data[local_data < 0] = -1
            sample.set_local_data(local_data)
583
584

        # Case 2: normal distribution with zero-mean and a given standard
585
        #         deviation or variance
Ultimanet's avatar
Ultimanet committed
586
        elif arg[0] == 'gau':
587
            var = arg[3]
588
589
590
591
592
593
594
            if np.isscalar(var) == True or var is None:
                processed_var = var
            else:
                try:
                    processed_var = sample.distributor.extract_local_data(var)
                except(AttributeError):
                    processed_var = var
595

596
597
598
599
600
            sample.apply_generator(lambda s: random.gau(dtype=self.dtype,
                                                        shape=s,
                                                        mean=arg[1],
                                                        dev=arg[2],
                                                        var=processed_var))
601

602
            if hermitianizeQ:
Ultimanet's avatar
Ultimanet committed
603
                sample = utilities.hermitianize(sample)
Ultimanet's avatar
Ultimanet committed
604

605
        # Case 3: uniform distribution
606
607
608
609
610
611
612
        elif arg[0] == "uni" and not hermitianizeQ:
            sample.apply_generator(lambda s: random.uni(dtype=self.dtype,
                                                        shape=s,
                                                        vmin=arg[1],
                                                        vmax=arg[2]))

        elif arg[0] == "uni" and hermitianizeQ:
613
614
615
616
617
            # For a hermitian uniform sample, generate a gaussian one
            # and then convert it to a uniform one
            sample = self.get_random_values(random='gau')
            # Use the cummulative of the gaussian, the error function in order
            # to transform it to a uniform distribution.
618
619
620
            if issubclass(sample.dtype.type, np.complexfloating):
                def temp_func(x):
                    return erf(x.real) + 1j * erf(x.imag)
Ultimanet's avatar
Ultimanet committed
621
            else:
622
623
                def temp_func(x):
                    return erf(x / np.sqrt(2))
624
625
626
627
            sample.apply_scalar_function(function=temp_func,
                                         inplace=True)

            # Shift and stretch the uniform distribution into the given limits
628
            # sample = (sample + 1)/2 * (vmax-vmin) + vmin
Ultimanet's avatar
Ultimanet committed
629
            vmin = arg[1]
630
631
632
            vmax = arg[2]
            sample *= (vmax - vmin) / 2.
            sample += 1 / 2. * (vmax + vmin)
Marco Selig's avatar
Marco Selig committed
633

634
        elif(arg[0] == "syn"):
Ultimanet's avatar
Ultimanet committed
635
636
637
638
639
640
            spec = arg[1]
            kpack = arg[2]
            harmonic_domain = arg[3]
            log = arg[4]
            nbin = arg[5]
            binbounds = arg[6]
641
642
643
            # Check whether there is a kpack available or not.
            # kpack is only used for computing kdict and extracting kindex
            # If not, take kdict and kindex from the fourier_domain
644
            if kpack is None:
Ultimanet's avatar
Ultimanet committed
645
                power_indices =\
646
647
648
649
                    harmonic_domain.power_indices.get_index_dict(
                                                        log=log,
                                                        nbin=nbin,
                                                        binbounds=binbounds)
650

Ultimanet's avatar
Ultimanet committed
651
652
653
654
655
656
                kindex = power_indices['kindex']
                kdict = power_indices['kdict']
                kpack = [power_indices['pindex'], power_indices['kindex']]
            else:
                kindex = kpack[1]
                kdict = harmonic_domain.power_indices.\
657
658
659
660
661
662
663
664
                    _compute_kdict_from_pindex_kindex(kpack[0], kpack[1])

            # draw the random samples
            # Case 1: self is a harmonic space
            if self.harmonic:
                # subcase 1: self is real
                # -> simply generate a random field in fourier space and
                # weight the entries accordingly to the powerspectrum
Ultimanet's avatar
Ultimanet committed
665
                if self.paradict['complexity'] == 0:
666
667
668
                    # set up the sample object. Overwrite the default from
                    # above to be sure, that the distribution strategy matches
                    # with the one from kdict
669
670
671
672
                    sample = kdict.copy_empty(dtype=self.dtype)
                    # set up and apply the random number generator
                    sample.apply_generator(lambda s: np.random.normal(
                                                       loc=0, scale=1, size=s))
Marco Selig's avatar
Marco Selig committed
673

674
675
676
677
678
                # subcase 2: self is hermitian but probably complex
                # -> generate a real field (in position space) and transform
                # it to harmonic space -> field in harmonic space is
                # hermitian. Now weight the modes accordingly to the
                # powerspectrum.
Ultimanet's avatar
Ultimanet committed
679
680
                elif self.paradict['complexity'] == 1:
                    temp_codomain = self.get_codomain()
681
682
683
                    # set up the sample object. Overwrite the default from
                    # above to be sure, that the distribution strategy matches
                    # with the one from kdict
Ultimanet's avatar
Ultimanet committed
684
                    sample = kdict.copy_empty(
685
686
687
688
                        dtype=temp_codomain.dtype)
                    # set up and apply the random number generator
                    sample.apply_generator(lambda s: np.random.normal(
                                                       loc=0, scale=1, size=s))
689
690
691
692
693
694

                    # In order to get the normalisation right, the sqrt
                    # of self.dim must be divided out.
                    # Furthermore, the normalisation in the fft routine
                    # must be undone
                    # TODO: Insert explanation
695
                    sqrt_of_dim = np.sqrt(self.get_dim())
Ultimanet's avatar
Ultimanet committed
696
697
698
                    sample /= sqrt_of_dim
                    sample = temp_codomain.calc_weight(sample, power=-1)

699
                    # tronsform the random field to harmonic space
Ultimanet's avatar
Ultimanet committed
700
                    sample = temp_codomain.\
701
702
703
704
705
706
707
708
709
710
                        calc_transform(sample, codomain=self)

                    # ensure that the kdict and the harmonic_sample have the
                    # same distribution strategy
                    assert(kdict.distribution_strategy ==
                           sample.distribution_strategy)

                # subcase 3: self is fully complex
                # -> generate a complex random field in harmonic space and
                # weight the modes accordingly to the powerspectrum
Ultimanet's avatar
Ultimanet committed
711
                elif self.paradict['complexity'] == 2:
712
713
714
                    # set up the sample object. Overwrite the default from
                    # above to be sure, that the distribution strategy matches
                    # with the one from kdict
715
716
                    sample = kdict.copy_empty(dtype=self.dtype)

717
                    # set up the random number generator
718
719
720
721
722
723
724
725
                    def temp_gen(s):
                        result = (np.random.normal(loc=0,
                                                   scale=1 / np.sqrt(2),
                                                   size=s) +
                                  np.random.normal(loc=0,
                                                   scale=1 / np.sqrt(2),
                                                   size=s) * 1.j)
                        return result
726
                    # apply the random number generator
727
                    sample.apply_generator(temp_gen)
728
729
730

                # apply the powerspectrum renormalization
                # therefore extract the local data from kdict
Ultimanet's avatar
Ultimanet committed
731
732
                local_kdict = kdict.get_local_data()
                rescaler = np.sqrt(
733
734
                    spec[np.searchsorted(kindex, local_kdict)])
                sample.apply_scalar_function(lambda x: x * rescaler,
Ultimanet's avatar
Ultimanet committed
735
                                             inplace=True)
736
            # Case 2: self is a position space
Ultimanet's avatar
Ultimanet committed
737
            else:
738
739
                # get a suitable codomain
                temp_codomain = self.get_codomain()
Ultimanet's avatar
Ultimanet committed
740

741
742
743
                # subcase 1: self is a real space.
                # -> generate a hermitian sample with the codomain in harmonic
                # space and make a fourier transformation.
Ultimanet's avatar
Ultimanet committed
744
                if self.paradict['complexity'] == 0:
745
                    # check that the codomain is hermitian
Ultimanet's avatar
Ultimanet committed
746
                    assert(temp_codomain.paradict['complexity'] == 1)
747
748
749
750

                # subcase 2: self is hermitian but probably complex
                # -> generate a real-valued random sample in fourier space
                # and transform it to real space
Ultimanet's avatar
Ultimanet committed
751
                elif self.paradict['complexity'] == 1:
752
753
                    # check that the codomain is real
                    assert(temp_codomain.paradict['complexity'] == 0)
Ultimanet's avatar
Ultimanet committed
754

755
756
757
758
759
760
                # subcase 3: self is fully complex
                # -> generate a complex-valued random sample in fourier space
                # and transform it to real space
                elif self.paradict['complexity'] == 2:
                    # check that the codomain is real
                    assert(temp_codomain.paradict['complexity'] == 2)
Ultimanet's avatar
Ultimanet committed
761

762
763
                # Get a hermitian/real/complex sample in harmonic space from
                # the codomain
Ultimanet's avatar
Ultimanet committed
764
                sample = temp_codomain.get_random_values(
765
766
767
768
769
770
771
772
773
774
                    random='syn',
                    pindex=kpack[0],
                    kindex=kpack[1],
                    spec=spec,
                    codomain=self,
                    log=log,
                    nbin=nbin,
                    binbounds=binbounds
                )

775
                # Perform a fourier transform
776
777
                sample = temp_codomain.calc_transform(sample,
                                                      codomain=self)
Ultimanet's avatar
Ultimanet committed
778
779

            if self.paradict['complexity'] == 1:
780
781
                sample.hermitian = True

Ultimanet's avatar
Ultimanet committed
782
783
        else:
            raise KeyError(about._errors.cstring(
784
                "ERROR: unsupported random key '" + str(arg[0]) + "'."))
Marco Selig's avatar
Marco Selig committed
785

786
        return sample
Marco Selig's avatar
Marco Selig committed
787

Ultimanet's avatar
Ultimanet committed
788
    def calc_weight(self, x, power=1):
Marco Selig's avatar
Marco Selig committed
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
        """
            Weights a given array with the pixel volumes to a given power.

            Parameters
            ----------
            x : numpy.ndarray
                Array to be weighted.
            power : float, *optional*
                Power of the pixel volumes to be used (default: 1).

            Returns
            -------
            y : numpy.ndarray
                Weighted array.
        """
804
805
        # weight
        x = x * self.get_weight(power=power)
Ultimanet's avatar
Ultimanet committed
806
        return x
Marco Selig's avatar
Marco Selig committed
807

808
    def get_weight(self, power=1):
809
        return np.prod(self.distances)**power
810

811
    def calc_dot(self, x, y):
Marco Selig's avatar
Marco Selig committed
812
        """
813
814
            Computes the discrete inner product of two given arrays of field
            values.
Marco Selig's avatar
Marco Selig committed
815
816
817
818
819
820
821
822
823
824
825
826
827

            Parameters
            ----------
            x : numpy.ndarray
                First array
            y : numpy.ndarray
                Second array

            Returns
            -------
            dot : scalar
                Inner product of the two arrays.
        """
828
829
        x = self.cast(x)
        y = self.cast(y)
830

831
832
        if self.datamodel == 'np':
            result = np.vdot(x, y)
833
        elif self.datamodel in RG_DISTRIBUTION_STRATEGIES:
834
835
836
837
838
            result = x.vdot(y)
        else:
            raise NotImplementedError(about._errors.cstring(
                "ERROR: function is not implemented for given datamodel."))

839
        if np.isreal(result):
840
            result = np.asscalar(np.real(result))
Ultimanet's avatar
Ultimanet committed
841
        if self.paradict['complexity'] != 2:
842
843
            if (np.absolute(result.imag) >
                    self.epsilon**2 * np.absolute(result.real)):
Ultimanet's avatar
Ultimanet committed
844
845
                about.warnings.cprint(
                    "WARNING: Discarding considerable imaginary part.")
846
            result = np.asscalar(np.real(result))
847
        return result
Marco Selig's avatar
Marco Selig committed
848

849
    def calc_transform(self, x, codomain=None, **kwargs):
Marco Selig's avatar
Marco Selig committed
850
851
852
853
854
855
856
857
        """
            Computes the transform of a given array of field values.

            Parameters
            ----------
            x : numpy.ndarray
                Array to be transformed.
            codomain : nifty.rg_space, *optional*
858
                codomain space to which the transformation shall map
Marco Selig's avatar
Marco Selig committed
859
860
861
862
863
864
865
                (default: None).

            Returns
            -------
            Tx : numpy.ndarray
                Transformed array
        """
866
        x = self.cast(x)
867

868
        if codomain is None:
Ultimanet's avatar
Ultimanet committed
869
            codomain = self.get_codomain()
870
871

        # Check if the given codomain is suitable for the transformation
872
873
874
        if (not isinstance(codomain, rg_space)) or \
                (not self.check_codomain(codomain)):
            raise ValueError(about._errors.cstring(
875
                "ERROR: unsupported codomain."))
876
        if codomain.harmonic:
877
            # correct for forward fft
878
            x = self.calc_weight(x, power=1)
879

Ultimanet's avatar
Ultimanet committed
880
881
#            ## correct for inverse fft
#            x = self.calc_weight(x, power=1)
882
#            x *= self.get_dim(split=False)
883
884
885

        # Perform the transformation
        Tx = self.fft_machine.transform(val=x, domain=self, codomain=codomain,
886
887
                                        **kwargs)

888
        if not codomain.harmonic:
889
            # correct for inverse fft
Ultimanet's avatar
Ultimanet committed
890
891
            Tx = codomain.calc_weight(Tx, power=-1)

892
893
894
        # when the codomain space is purely real, the result of the
        # transformation must be corrected accordingly. Using the casting
        # method of codomain is sufficient
895
        # TODO: Let .transform  yield the correct dtype
896
        Tx = codomain.cast(Tx)
897

898
899
        return Tx

Ultimanet's avatar
Ultimanet committed
900
    def calc_smooth(self, x, sigma=0, codomain=None):
Marco Selig's avatar
Marco Selig committed
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
        """
            Smoothes an array of field values by convolution with a Gaussian
            kernel.

            Parameters
            ----------
            x : numpy.ndarray
                Array of field values to be smoothed.
            sigma : float, *optional*
                Standard deviation of the Gaussian kernel, specified in units
                of length in position space; for testing: a sigma of -1 will be
                reset to a reasonable value (default: 0).

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

920
        # Check sigma
Ultimanet's avatar
Ultimanet committed
921
        if sigma == 0:
Marco Selig's avatar
Marco Selig committed
922
            return x
Ultimanet's avatar
Ultimanet committed
923
924
925
        elif sigma == -1:
            about.infos.cprint(
                "INFO: Resetting sigma to sqrt(2)*max(dist).")
926
            sigma = np.sqrt(2) * np.max(self.distances)
927
        elif(sigma < 0):
Marco Selig's avatar
Marco Selig committed
928
            raise ValueError(about._errors.cstring("ERROR: invalid sigma."))
Ultimanet's avatar
Ultimanet committed
929

930
        # if a codomain was given...
931
        if codomain is not None:
932
            # ...check if it was suitable
Ultimanet's avatar
Ultimanet committed
933
934
935
            if not isinstance(codomain, rg_space):
                raise ValueError(about._errors.cstring(
                    "ERROR: codomain is not a rg_space instance!"))
936
            if not self.harmonic and not codomain.harmonic:
Ultimanet's avatar
Ultimanet committed
937
938
939
940
941
                raise ValueError(about._errors.cstring(
                    "ERROR: fourier_domain is not a fourier space!"))
            if not self.check_codomain(codomain):
                raise ValueError(about._errors.cstring(
                    "ERROR: fourier_codomain is not a valid codomain!"))
942
        elif not self.harmonic:
Ultimanet's avatar
Ultimanet committed
943
944
            codomain = self.get_codomain()

945
946
947
        # Case1:
        # If self is a position-space, fourier transform the input and
        # call calc_smooth of the fourier codomain
948
        if not self.harmonic:
949
            x = self.calc_transform(x, codomain=codomain)
Ultimanet's avatar
Ultimanet committed
950
            x = codomain.calc_smooth(x, sigma)
951
            x = codomain.calc_transform(x, codomain=self)
Ultimanet's avatar
Ultimanet committed
952
            return x
953
954
955
956
957
958
959
960
961

        # Case 2:
        # if self is fourier multiply the gaussian kernel, etc...

        # Cast the input
        x = self.cast(x)

        # if x is hermitian it remains hermitian during smoothing
        if self.datamodel in RG_DISTRIBUTION_STRATEGIES:
962
            remeber_hermitianQ = x.hermitian
Ultimanet's avatar
Ultimanet committed
963

964
965
966
967
        # Define the Gaussian kernel function
        gaussian = lambda x: np.exp(-2. * np.pi**2 * x**2 * sigma**2)

        # Define the variables in the dialect of the legacy smoothing.py
968
969
        nx = np.array(self.get_shape())
        dx = 1 / nx / self.distances
970
        # Multiply the data along each axis with suitable the gaussian kernel
Ultimanet's avatar
Ultimanet committed
971
        for i in range(len(nx)):
972
973
            # Prepare the exponent
            dk = 1. / nx[i] / dx[i]
Ultimanet's avatar
Ultimanet committed
974
            nk = nx[i]
975
            k = -0.5 * nk * dk + np.arange(nk) * dk
Ultimanet's avatar
Ultimanet committed
976
977
            if self.paradict['zerocenter'][i] == False:
                k = np.fft.fftshift(k)
978
            # compute the actual kernel vector
Ultimanet's avatar
Ultimanet committed
979
            gaussian_kernel_vector = gaussian(k)
980
981
            # blow up the vector to an array of shape (1,.,1,len(nk),1,.,1)
            blown_up_shape = [1, ] * len(nx)
Ultimanet's avatar
Ultimanet committed
982
983
984
            blown_up_shape[i] = len(gaussian_kernel_vector)
            gaussian_kernel_vector =\
                gaussian_kernel_vector.reshape(blown_up_shape)
985
986
            # apply the blown-up gaussian_kernel_vector
            x = x*gaussian_kernel_vector
987

988
        if self.datamodel in RG_DISTRIBUTION_STRATEGIES:
989
            x.hermitian = remeber_hermitianQ
990

Ultimanet's avatar
Ultimanet committed
991
        return x
Marco Selig's avatar
Marco Selig committed
992

993
    def calc_power(self, x, **kwargs):
Marco Selig's avatar
Marco Selig committed
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
        """
            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).
            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*
1018
1019
                Flag specifying if the spectral binning is performed on
                logarithmic
Marco Selig's avatar
Marco Selig committed
1020
1021
1022
1023
                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*
1024
1025
                Number of used spectral bins; if given `log` is set to
                ``False``;
Marco Selig's avatar
Marco Selig committed
1026
1027
1028
1029
1030
                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
1031
                (default: None).
Marco Selig's avatar
Marco Selig committed
1032
1033

        """
Ultimanet's avatar
Ultimanet committed
1034
1035
        x = self.cast(x)

1036
        # If self is a position space, delegate calc_power to its codomain.
1037
        if not self.harmonic:
Marco Selig's avatar
Marco Selig committed
1038
            try:
1039
                codomain = kwargs['codomain']
Ultimanet's avatar
Ultimanet committed
1040
1041
            except(KeyError):
                codomain = self.get_codomain()
1042

Ultimanet's avatar
Ultimanet committed
1043
1044
1045
            y = self.calc_transform(x, codomain)
            kwargs.update({'codomain': self})
            return codomain.calc_power(y, **kwargs)
1046
1047
1048
1049
1050
1051

        # If some of the pindex, kindex or rho arrays are given explicitly,
        # favor them over those from the self.power_indices dictionary.
        # As the default value in kwargs.get(key, default) does NOT evaluate
        # lazy, a distinction of cases is necessary. Otherwise the
        # powerindices might be computed, although not necessary
1052
        if 'pindex' in kwargs and 'kindex' in kwargs and 'rho' in kwargs:
Ultimanet's avatar
Ultimanet committed
1053
1054
1055
1056
1057
            pindex = kwargs.get('pindex')
            rho = kwargs.get('rho')
        else:
            log = kwargs.get('log', None)
            nbin = kwargs.get('nbin', None)
1058
            binbounds = kwargs.get('binbounds', None)
1059
1060
1061
1062
            power_indices = self.power_indices.get_index_dict(
                                                        log=log,
                                                        nbin=nbin,
                                                        binbounds=binbounds)
Ultimanet's avatar
Ultimanet committed
1063
1064
            pindex = kwargs.get('pindex', power_indices['pindex'])
            rho = kwargs.get('rho', power_indices['rho'])
1065

Ultimanet's avatar
Ultimanet committed
1066
        fieldabs = abs(x)**2
1067
        power_spectrum = np.zeros(rho.shape)
1068

1069
        if self.datamodel == 'np':
1070
1071
            power_spectrum = np.bincount(pindex.flatten(),
                                         weights=fieldabs.flatten())
1072
        elif self.datamodel in RG_DISTRIBUTION_STRATEGIES:
1073
            power_spectrum = pindex.bincount(weights=fieldabs)
1074
1075
1076
        else:
            raise NotImplementedError(about._errors.cstring(
                "ERROR: function is not implemented for given datamodel."))
1077
1078

        # Divide out the degeneracy factor
Ultimanet's avatar
Ultimanet committed
1079
1080
        power_spectrum /= rho
        return power_spectrum
Marco Selig's avatar
Marco Selig committed
1081

1082

Marco Selig's avatar
Marco Selig committed
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
    def get_plot(self,x,title="",vmin=None,vmax=None,power=None,unit="",norm=None,cmap=None,cbar=True,other=None,legend=False,mono=True,**kwargs):
        """
            Creates a plot of field values according to the specifications
            given by the parameters.

            Parameters
            ----------
            x : numpy.ndarray
                Array containing the field values.

            Returns
            -------
            None

            Other parameters
            ----------------
            title : string, *optional*
                Title of the plot (default: "").
            vmin : float, *optional*
                Minimum value to be displayed (default: ``min(x)``).
            vmax : float, *optional*
                Maximum value to be displayed (default: ``max(x)``).
            power : bool, *optional*
                Whether to plot the power contained in the field or the field
                values themselves (default: False).
            unit : string, *optional*
                Unit of the field values (default: "").
            norm : string, *optional*
                Scaling of the field values before plotting (default: None).
            cmap : matplotlib.colors.LinearSegmentedColormap, *optional*
                Color map to be used for two-dimensional plots (default: None).
            cbar : bool, *optional*
                Whether to show the color bar or not (default: True).
            other : {single object, tuple of objects}, *optional*
                Object or tuple of objects to be added, where objects can be
                scalars, arrays, or fields (default: None).
            legend : bool, *optional*
                Whether to show the legend or not (default: False).
            mono : bool, *optional*
                Whether to plot the monopole or not (default: True).
            save : string, *optional*
                Valid file name where the figure is to be stored, by default
                the figure is not saved (default: False).
            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).

        """
1151
1152
1153
1154
        try:
            x = x.get_full_data()
        except AttributeError:
            pass
Marco Selig's avatar
Marco Selig committed
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213