nifty_rg.py 115 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
46
from nifty.keepers import about,\
                          global_dependency_injector,\
                          global_configuration
from nifty.nifty_core import point_space,\
Marco Selig's avatar
Marco Selig committed
47
                             field
Ultimanet's avatar
Ultimanet committed
48
from nifty.nifty_random import random
49
from nifty.nifty_mpi_data import distributed_data_object
50
51
from nifty.nifty_mpi_data import STRATEGIES as DISTRIBUTION_STRATEGIES

Ultimanet's avatar
Ultimanet committed
52
from nifty.nifty_paradict import rg_space_paradict
Ultima's avatar
Ultima committed
53
import nifty.nifty_utilities as utilities
54
55
56
57
58
59

import nifty_fft

MPI = global_dependency_injector[global_configuration['mpi_module']]

RG_DISTRIBUTION_STRATEGIES = DISTRIBUTION_STRATEGIES['global']
Ultimanet's avatar
Ultimanet committed
60

ultimanet's avatar
ultimanet committed
61
'''
Marco Selig's avatar
Marco Selig committed
62
63
64
65
66
try:
    import gfft as gf
except(ImportError):
    about.infos.cprint('INFO: "plain" gfft version 0.1.0')
    import gfft_rg as gf
ultimanet's avatar
ultimanet committed
67
'''
Ultimanet's avatar
Ultimanet committed
68
69


70
# -----------------------------------------------------------------------------
Marco Selig's avatar
Marco Selig committed
71

72
class rg_space(point_space):
Marco Selig's avatar
Marco Selig committed
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
    """
        ..      _____   _______
        ..    /   __/ /   _   /
        ..   /  /    /  /_/  /
        ..  /__/     \____  /  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.
        datatype : numpy.dtype
            Data type of the field values for a field defined on this space,
            either ``numpy.float64`` or ``numpy.complex128``.
        discrete : bool
            Whether or not the underlying space is discrete, always ``False``
            for regular grids.
        vol : numpy.ndarray
            One-dimensional array containing the distances between two grid
            points along each axis, in reverse order. By default, the total
            length of each axis is assumed to be one.
        fourier : bool
            Whether or not the grid represents a Fourier basis.
    """
133
    epsilon = 0.0001  # relative precision for comparisons
Marco Selig's avatar
Marco Selig committed
134

135
136
137
    def __init__(self, num, naxes=None, zerocenter=False,
                 complexity=None, hermitian=True, purelyreal=True,
                 dist=None, fourier=False, datamodel='fftw'):
Marco Selig's avatar
Marco Selig committed
138
139
140
141
142
143
144
145
146
147
148
149
        """
            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
150
                (default: False).
Marco Selig's avatar
Marco Selig committed
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
            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
        """
167
        if complexity is None:
168
169
            complexity = 2 - \
                (bool(hermitian) or bool(purelyreal)) - bool(purelyreal)
170

Ultimanet's avatar
Ultimanet committed
171
        if np.isscalar(num):
172
173
174
175
176
177
            num = (num,) * np.asscalar(np.array(naxes))

        self.paradict = rg_space_paradict(num=num,
                                          complexity=complexity,
                                          zerocenter=zerocenter)

178
        naxes = len(self.paradict['num'])
Marco Selig's avatar
Marco Selig committed
179

180
181
        # set datatype
        if self.paradict['complexity'] == 0:
Marco Selig's avatar
Marco Selig committed
182
183
184
            self.datatype = np.float64
        else:
            self.datatype = np.complex128
185
186
187

        # set datamodel
        if datamodel not in ['np'] + RG_DISTRIBUTION_STRATEGIES:
188
            about.warnings.cprint("WARNING: datamodel set to default.")
189
190
            self.datamodel = \
                global_configuration['default_distribution_strategy']
191
192
193
        else:
            self.datamodel = datamodel

Marco Selig's avatar
Marco Selig committed
194
195
        self.discrete = False

196
        # set volume
Marco Selig's avatar
Marco Selig committed
197
        if(dist is None):
198
            dist = 1 / np.array(self.paradict['num'], dtype=self.datatype)
Marco Selig's avatar
Marco Selig committed
199
        elif(np.isscalar(dist)):
200
201
            dist = self.datatype(dist) * np.ones(naxes, dtype=self.datatype,
                                                 order='C')
Marco Selig's avatar
Marco Selig committed
202
        else:
203
            dist = np.array(dist, dtype=self.datatype)
204
            if(np.size(dist) == 1):
205
206
207
208
209
210
211
                dist = dist * np.ones(naxes, dtype=self.datatype, order='C')
            if(np.size(dist) != naxes):
                raise ValueError(about._errors.cstring(
                    "ERROR: size mismatch ( " + str(np.size(dist)) + " <> " +
                    str(naxes) + " )."))
        if(np.any(dist <= 0)):
            raise ValueError(about._errors.cstring(
212
213
                "ERROR: nonpositive distance(s)."))
        self.vol = np.real(dist)
Marco Selig's avatar
Marco Selig committed
214

215
        # TODO: Deprecate self.fourier
Marco Selig's avatar
Marco Selig committed
216
        self.fourier = bool(fourier)
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
        self.harmonic = self.fourier
        # Initializes the fast-fourier-transform machine, which will be used
        # to transform the space
        self.fft_machine = nifty_fft.fft_factory()

        # Initialize the power_indices object which takes care of kindex,
        # pindex, rho and the pundex for a given set of parameters
        if self.harmonic:
            self.power_indices = power_indices(
                                    shape=self.get_shape(),
                                    dgrid=dist,
                                    zerocentered=self.paradict['zerocenter'],
                                    comm=MPI.COMM_WORLD, # TODO: insert output from about.configuration
                                    datamodel=self.datamodel)

Marco Selig's avatar
Marco Selig committed
232

233
234
    @property
    def para(self):
235
236
237
        temp = np.array(self.paradict['num'] +
                        [self.paradict['complexity']] +
                        self.paradict['zerocenter'], dtype=int)
238
        return temp
239

240
241
    @para.setter
    def para(self, x):
242
243
244
        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
245
246


247
    # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
248
    def copy(self):
249
250
251
252
253
254
        return rg_space(num=self.paradict['num'],
                        complexity=self.paradict['complexity'],
                        zerocenter=self.paradict['zerocenter'],
                        dist=self.vol,
                        fourier=self.harmonic,
                        datamodel=self.datamodel)
255
256
257

    def num(self):
        np.prod(self.get_shape())
258

259
    def get_naxes(self):
Marco Selig's avatar
Marco Selig committed
260
261
262
263
264
265
266
267
        """
            Returns the number of axes of the grid.

            Returns
            -------
            naxes : int
                Number of axes of the regular grid.
        """
268
#        return (np.size(self.para)-1)//2
269
        return len(self.get_shape())
Marco Selig's avatar
Marco Selig committed
270
271
272
273
274
275
276
277
278
279

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

            Returns
            -------
            zerocenter : numpy.ndarray
                Whether the grid is centered on zero for each axis or not.
        """
280
        # return self.para[-(np.size(self.para)-1)//2:][::-1].astype(np.bool)
281
        return self.paradict['zerocenter']
Marco Selig's avatar
Marco Selig committed
282
283
284
285
286
287
288
289
290
291

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

            Returns
            -------
            dist : np.ndarray
                Distances between two grid points on each axis.
        """
292
        return self.vol
293

294
    def get_shape(self):
295
        return np.array(self.paradict['num'])
Marco Selig's avatar
Marco Selig committed
296

297
    def get_dim(self, split=False):
Marco Selig's avatar
Marco Selig committed
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
        """
            Computes the dimension of the space, i.e.\  the number of pixels.

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

            Returns
            -------
            dim : {int, numpy.ndarray}
                Dimension(s) of the space. If ``split==True``, a
                one-dimensional array with an entry for each axis is returned.
        """
        ## dim = product(n)
314
        if split == True:
315
            return self.get_shape()
Marco Selig's avatar
Marco Selig committed
316
        else:
317
            return np.prod(self.get_shape())
Marco Selig's avatar
Marco Selig committed
318

319
    # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Marco Selig's avatar
Marco Selig committed
320

321
    def get_dof(self):
Marco Selig's avatar
Marco Selig committed
322
323
324
325
326
327
328
329
330
331
        """
            Computes the number of degrees of freedom of the space, i.e.\  the
            number of grid points multiplied with one or two, depending on
            complex-valuedness and hermitian symmetry of the fields.

            Returns
            -------
            dof : int
                Number of degrees of freedom of the space.
        """
332
        # dof ~ dim
333
334
        if self.paradict['complexity'] < 2:
            return np.prod(self.paradict['num'])
Marco Selig's avatar
Marco Selig committed
335
        else:
336
            return 2 * np.prod(self.paradict['num'])
337
338
339
340

#        if(self.para[(np.size(self.para)-1)//2]<2):
#            return np.prod(self.para[:(np.size(self.para)-1)//2],axis=0,dtype=None,out=None)
#        else:
341
342
# return
# 2*np.prod(self.para[:(np.size(self.para)-1)//2],axis=0,dtype=None,out=None)
Marco Selig's avatar
Marco Selig committed
343

344
    # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
ultimanet's avatar
ultimanet committed
345

346
347
    def enforce_power(self, spec, size=None, kindex=None, codomain=None,
                      log=False, nbin=None, binbounds=None):
Marco Selig's avatar
Marco Selig committed
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
        """
            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*
372
373
374
                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
375
                binning is done (default: None).
Marco Selig's avatar
Marco Selig committed
376
            nbin : integer, *optional*
377
                Number of used spectral bins; if given `log` is set to
378
379
                ``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
380
381
382
            binbounds : {list, array}, *optional*
                User specific inner boundaries of the bins, which are preferred
                over the above parameters; by default no binning is done
383
                (default: None).
Marco Selig's avatar
Marco Selig committed
384
        """
385
386
387
388
389
390
391

        # 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:
392
393
                kindex_supply_space = self
            else:
394
395
                # Check if the given codomain is compatible with the space
                try:
396
397
398
                    assert(self.check_codomain(codomain))
                    kindex_supply_space = codomain
                except(AssertionError):
399
400
401
402
                    about.warnings.cprint("WARNING: Supplied codomain is " +
                                          "incompatible. Generating a " +
                                          "generic codomain. This can " +
                                          "be expensive!")
403
404
                    kindex_supply_space = self.get_codomain()
            kindex = kindex_supply_space.\
405
406
407
408
409
410
411
412
                power_indices.get_index_dict(log=log, nbin=nbin,
                                             binbounds=binbounds)['kindex']

        # Now it's about to extract a powerspectrum from spec
        # First of all just extract a numpy array. The shape is cared about
        # later.

        # Case 1: spec is a function
413
        if callable(spec) == True:
414
            # Try to plug in the kindex array in the function directly
Marco Selig's avatar
Marco Selig committed
415
            try:
416
                spec = np.array(spec(kindex), dtype=self.datatype)
Marco Selig's avatar
Marco Selig committed
417
            except:
418
419
                # Second try: Use a vectorized version of the function.
                # This is slower, but better than nothing
420
421
422
423
                try:
                    spec = np.vectorize(spec)(kindex)
                except:
                    raise TypeError(about._errors.cstring(
424
425
426
                        "ERROR: invalid power spectra function."))

        # Case 2: spec is a field:
427
428
        elif isinstance(spec, field):
            spec = spec[:]
429
430
431
            spec = np.array(spec, dtype=self.datatype).flatten()

        # Case 3: spec is a scalar or something else:
Marco Selig's avatar
Marco Selig committed
432
        else:
433
434
435
436
            spec = np.array(spec, dtype=self.datatype).flatten()

        # Make some sanity checks
        # Drop imaginary part
437
438
439
440
441
442
        temp_spec = np.real(spec)
        try:
            np.testing.assert_allclose(spec, temp_spec)
        except(AssertionError):
            about.warnings.cprint("WARNING: Dropping imaginary part.")
        spec = temp_spec
443
444

        # check finiteness
445
        if not np.all(np.isfinite(spec)):
Marco Selig's avatar
Marco Selig committed
446
            about.warnings.cprint("WARNING: infinite value(s).")
447
448
449

        # check positivity (excluding null)
        if np.any(spec < 0):
450
            raise ValueError(about._errors.cstring(
451
452
453
454
455
                "ERROR: nonpositive value(s)."))
        if np.any(spec == 0):
            about.warnings.cprint("WARNING: nonpositive value(s).")

        # Set the size parameter
Ultimanet's avatar
Ultimanet committed
456
457
        if size == None:
            size = len(kindex)
458
459
460

        # Fix the size of the spectrum
        # If spec is singlevalued, expand it
461
        if np.size(spec) == 1:
462
463
            spec = spec * np.ones(size, dtype=spec.dtype, order='C')
        # If the size does not fit at all, throw an exception
464
        elif np.size(spec) < size:
465
466
            raise ValueError(about._errors.cstring("ERROR: size mismatch ( " +
                                                   str(np.size(spec)) + " < " + str(size) + " )."))
467
        elif np.size(spec) > size:
468
469
            about.warnings.cprint("WARNING: power spectrum cut to size ( == " +
                                  str(size) + " ).")
Marco Selig's avatar
Marco Selig committed
470
471
            spec = spec[:size]

472
        return spec
473

474
    # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Marco Selig's avatar
Marco Selig committed
475

Ultimanet's avatar
Ultimanet committed
476
    def set_power_indices(self, log=False, nbin=None, binbounds=None, **kwargs):
Marco Selig's avatar
Marco Selig committed
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
        """
            Sets the (un)indexing objects for spectral indexing internally.

            Parameters
            ----------
            log : bool
                Flag specifying if the 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
                Number of used 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}
                User specific inner boundaries of the bins, which are preferred
                over the above parameters; by default no binning is done
                (default: None).

            Returns
            -------
            None

            See Also
            --------
            get_power_indices

            Raises
            ------
            AttributeError
507
                If ``self.harmonic == False``.
Marco Selig's avatar
Marco Selig committed
508
509
510
511
            ValueError
                If the binning leaves one or more bins empty.

        """
512

513
514
515
        about.warnings.cflush("WARNING: set_power_indices is a deprecated" +
                              "function. Please use the interface of" +
                              "self.power_indices in future!")
516
        self.power_indices.set_default(log=log, nbin=nbin, binbounds=binbounds)
Marco Selig's avatar
Marco Selig committed
517
518
        return None

519
520
    # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    def _cast_to_d2o(self, x, dtype=None, ignore_complexity=False,
521
                     verbose=False, **kwargs):
522
523
        """
            Computes valid field values from a given object, trying
524
525
            to translate the given data into a valid form. Thereby it is as
            benevolent as possible.
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540

            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*
541
                Whether the method should raise a warning if information is
542
543
                lost during casting (default: False).
        """
544
545
        if dtype is None:
            dtype = self.datatype
546
        # Case 1: x is a field
547
548
        if isinstance(x, field):
            if verbose:
549
                # Check if the domain matches
550
                if(self != x.domain):
551
552
553
                    about.warnings.cflush(
                        "WARNING: Getting data from foreign domain!")
            # Extract the data, whatever it is, and cast it again
554
            return self.cast(x.val, dtype=dtype)
555
556

        # Case 2: x is a distributed_data_object
557
        if isinstance(x, distributed_data_object):
558
559
560
            # Check the shape
            if np.any(x.shape != self.get_shape()):
                # Check if at least the number of degrees of freedom is equal
561
                if x.get_dim() == self.get_dim():
562
563
564
565
                    # If the number of dof is equal or 1, use np.reshape...
                    about.warnings.cflush(
                        "WARNING: Trying to reshape the data. This operation is " +
                        "expensive as it consolidates the full data!\n")
566
                    temp = x.get_full_data()
567
568
                    temp = np.reshape(temp, self.get_shape())
                    # ... and cast again
569
                    return self.cast(temp, dtype=dtype)
570

571
                else:
572
573
574
575
                    raise ValueError(about._errors.cstring(
                        "ERROR: Data has incompatible shape!"))

            # Check the datatype
576
577
            if np.dtype(x.dtype) != np.dtype(dtype):
                if np.dtype(x.dtype) > np.dtype(dtype):
578
579
580
581
                    about.warnings.cflush(
                        "WARNING: Datatypes are uneqal/of conflicting precision (own: "
                        + str(dtype) + " <> foreign: " + str(x.dtype)
                        + ") and will be casted! "
582
583
                        + "Potential loss of precision!\n")
                temp = x.copy_empty(dtype=dtype)
584
585
586
                temp.set_local_data(x.get_local_data())
                temp.hermitian = x.hermitian
                x = temp
587

588
            if ignore_complexity == False:
589
                # Check hermitianity/reality
590
591
                if self.paradict['complexity'] == 0:
                    if x.iscomplex().any() == True:
592
593
594
595
                        about.warnings.cflush(
                            "WARNING: Data is not completely real. Imaginary part " +
                            "will be discarded!\n")
                        temp = x.copy_empty()
596
597
                        temp.set_local_data(np.real(x.get_local_data()))
                        x = temp
598

599
600
                elif self.paradict['complexity'] == 1:
                    if x.hermitian == False and about.hermitianize.status == True:
601
602
603
604
605
                        about.warnings.cflush(
                            "WARNING: Data gets hermitianized. This operation is " +
                            "extremely expensive\n")
                        #temp = x.copy_empty()
                        # temp.set_full_data(gp.nhermitianize_fast(x.get_full_data(),
606
607
                        #    (False, )*len(x.shape)))
                        x = utilities.hermitianize(x)
608

609
            return x
610
611
612
613
614
615

        # Case 3: x is something else
        # Use general d2o casting
        x = distributed_data_object(x, global_shape=self.get_shape(),
                                    dtype=dtype)
        # Cast the d2o
616
        return self.cast(x, dtype=dtype)
Ultimanet's avatar
Ultimanet committed
617

618
619
    def _cast_to_np(self, x, dtype=None, ignore_complexity=False,
                    verbose=False, **kwargs):
620
621
        """
            Computes valid field values from a given object, trying
622
623
            to translate the given data into a valid form. Thereby it is as
            benevolent as possible.
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638

            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*
639
                Whether the method should raise a warning if information is
640
641
                lost during casting (default: False).
        """
642
643
        if dtype is None:
            dtype = self.datatype
644
        # Case 1: x is a field
645
646
        if isinstance(x, field):
            if verbose:
647
                # Check if the domain matches
648
                if(self != x.domain):
649
650
651
                    about.warnings.cflush(
                        "WARNING: Getting data from foreign domain!")
            # Extract the data, whatever it is, and cast it again
652
            return self.cast(x.val, dtype=dtype)
653
654

        # Case 2: x is a distributed_data_object
655
        if isinstance(x, distributed_data_object):
656
            # Extract the data
657
            temp = x.get_full_data()
658
            # Cast the resulting numpy array again
659
            return self.cast(temp, dtype=dtype)
660

661
        elif isinstance(x, np.ndarray):
662
663
664
            # Check the shape
            if np.any(x.shape != self.get_shape()):
                # Check if at least the number of degrees of freedom is equal
665
                if x.size == self.get_dim():
666
667
668
                    # If the number of dof is equal or 1, use np.reshape...
                    temp = x.reshape(self.get_shape())
                    # ... and cast again
669
                    return self.cast(temp, dtype=dtype)
670
                elif x.size == 1:
671
672
                    temp = np.empty(shape=self.get_shape(),
                                    dtype=dtype)
673
                    temp[:] = x
674
                    return self.cast(temp, dtype=dtype)
675
                else:
676
677
678
679
                    raise ValueError(about._errors.cstring(
                        "ERROR: Data has incompatible shape!"))

            # Check the datatype
680
            if x.dtype != dtype:
681
682
683
684
685
686
                about.warnings.cflush(
                    "WARNING: Datatypes are uneqal/of conflicting precision (own: "
                    + str(dtype) + " <> foreign: " + str(x.dtype)
                    + ") and will be casted! "
                    + "Potential loss of precision!\n")
                # Fix the datatype...
687
                temp = x.astype(dtype)
688
                # ... and cast again
689
                return self.cast(temp, dtype=dtype)
690

691
            if ignore_complexity == False:
692
                # Check hermitianity/reality
693
694
                if self.paradict['complexity'] == 0:
                    if not np.all(np.isreal(x)) == True:
695
696
697
                        about.warnings.cflush(
                            "WARNING: Data is not completely real. Imaginary part " +
                            "will be discarded!\n")
698
                        x = np.real(x)
699

700
701
                elif self.paradict['complexity'] == 1:
                    if about.hermitianize.status == True:
702
703
704
705
706
                        about.warnings.cflush(
                            "WARNING: Data gets hermitianized. This operation is " +
                            "rather expensive.\n")
                        #temp = x.copy_empty()
                        # temp.set_full_data(gp.nhermitianize_fast(x.get_full_data(),
707
708
                        #    (False, )*len(x.shape)))
                        x = utilities.hermitianize(x)
709

710
            return x
711
712
713

        # Case 3: x is something else
        # Use general numpy casting
714
        else:
715
            temp = np.empty(self.get_shape(), dtype=dtype)
716
717
            temp[:] = x
            return temp
718
719

    def enforce_values(self, x, extend=True):
Marco Selig's avatar
Marco Selig committed
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
        """
            Computes valid field values from a given object, taking care of
            data types, shape, and symmetry.

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

            Returns
            -------
            x : numpy.ndarray
                Array containing the valid field values.

            Other parameters
            ----------------
            extend : bool, *optional*
                Whether a scalar is extented to a constant array or not
                (default: True).
        """
740
        about.warnings.cflush(
741
            "WARNING: enforce_values is deprecated function. Please use self.cast")
742
743
        if(isinstance(x, field)):
            if(self == x.domain):
Marco Selig's avatar
Marco Selig committed
744
                if(self.datatype is not x.domain.datatype):
745
746
                    raise TypeError(about._errors.cstring("ERROR: inequal data types ( '" + str(
                        np.result_type(self.datatype)) + "' <> '" + str(np.result_type(x.domain.datatype)) + "' )."))
Marco Selig's avatar
Marco Selig committed
747
748
749
                else:
                    x = np.copy(x.val)
            else:
750
751
                raise ValueError(about._errors.cstring(
                    "ERROR: inequal domains."))
Marco Selig's avatar
Marco Selig committed
752
        else:
753
            if(np.size(x) == 1):
Marco Selig's avatar
Marco Selig committed
754
                if(extend):
755
756
                    x = self.datatype(
                        x) * np.ones(self.get_dim(split=True), dtype=self.datatype, order='C')
Marco Selig's avatar
Marco Selig committed
757
758
                else:
                    if(np.isscalar(x)):
759
                        x = np.array([x], dtype=self.datatype)
Marco Selig's avatar
Marco Selig committed
760
                    else:
761
                        x = np.array(x, dtype=self.datatype)
Marco Selig's avatar
Marco Selig committed
762
            else:
763
                x = self.enforce_shape(np.array(x, dtype=self.datatype))
Marco Selig's avatar
Marco Selig committed
764

765
766
        # hermitianize if ...
        if(about.hermitianize.status)and(np.size(x) != 1)and(self.para[(np.size(self.para) - 1) // 2] == 1):
Ultimanet's avatar
Ultimanet committed
767
768
            #x = gp.nhermitianize_fast(x,self.para[-((np.size(self.para)-1)//2):].astype(np.bool),special=False)
            x = utilities.hermitianize(x)
769
        # check finiteness
Marco Selig's avatar
Marco Selig committed
770
771
772
773
774
        if(not np.all(np.isfinite(x))):
            about.warnings.cprint("WARNING: infinite value(s).")

        return x

775
    # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Marco Selig's avatar
Marco Selig committed
776

777
    def get_random_values(self, **kwargs):
Marco Selig's avatar
Marco Selig committed
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
        """
            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}
                - "gau" (normal distribution with zero-mean and a given standard
                    deviation or variance)
                - "syn" (synthesizes from a given power spectrum)
                - "uni" (uniform distribution over [vmin,vmax[)

                (default: None).
            dev : float, *optional*
                Standard deviation (default: 1).
            var : float, *optional*
                Variance, overriding `dev` if both are specified
                (default: 1).
            spec : {scalar, list, numpy.ndarray, nifty.field, function}, *optional*
                Power spectrum (default: 1).
            pindex : numpy.ndarray, *optional*
                Indexing array giving the power spectrum index of each band
                (default: None).
            kindex : numpy.ndarray, *optional*
                Scale of each band (default: None).
            codomain : nifty.rg_space, *optional*
Ultimanet's avatar
Ultimanet committed
815
                A compatible codomain (default: None).
Marco Selig's avatar
Marco Selig committed
816
817
818
819
820
821
822
823
824
825
826
827
828
829
            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"``
830
                (default: 0).
Ultimanet's avatar
Ultimanet committed
831
            vmin : float, *optional*
Marco Selig's avatar
Marco Selig committed
832
833
834
835
                Lower limit for a uniform distribution (default: 0).
            vmax : float, *optional*
                Upper limit for a uniform distribution (default: 1).
        """
836
837
838
839
        # TODO: Without hermitianization the random-methods from pointspace
        # could be used.

        # Parse the keyword arguments
840
        arg = random.parse_arguments(self, **kwargs)
841
842
843

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

846
847
848
        # Should the output be hermitianized? This does not depend on the
        # hermitianize boolean in about, as it would yield in wrong,
        # not recoverable results
849

850
851
        #hermitianizeQ = about.hermitianize.status and self.paradict['complexity']
        hermitianizeQ = self.paradict['complexity']
Ultimanet's avatar
Ultimanet committed
852

853
        # Case 1: uniform distribution over {-1,+1}/{1,i,-1,-i}
Ultimanet's avatar
Ultimanet committed
854
        if arg[0] == 'pm1' and hermitianizeQ == False:
Ultimanet's avatar
Ultimanet committed
855
            gen = lambda s: random.pm1(datatype=self.datatype,
856
                                       shape=s)
Ultimanet's avatar
Ultimanet committed
857
            sample.apply_generator(gen)
858

Ultimanet's avatar
Ultimanet committed
859
        elif arg[0] == 'pm1' and hermitianizeQ == True:
860
            sample = self.get_random_values(random='uni', vmin=-1, vmax=1)
Ultimanet's avatar
Ultimanet committed
861
862
863
864
            local_data = sample.get_local_data()
            if issubclass(sample.dtype, np.complexfloating):
                temp_data = local_data.copy()
                local_data[temp_data.real >= 0.5] = 1
865
866
867
                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
868
869
870
871
            else:
                local_data[local_data >= 0] = 1
                local_data[local_data < 0] = -1
            sample.set_local_data(local_data)
872
873

        # Case 2: normal distribution with zero-mean and a given standard
Ultimanet's avatar
Ultimanet committed
874
875
        ##         deviation or variance
        elif arg[0] == 'gau':
876
            var = arg[3]
877
878
879
880
881
882
883
            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
884

Ultimanet's avatar
Ultimanet committed
885
            gen = lambda s: random.gau(datatype=self.datatype,
886
887
888
889
                                       shape=s,
                                       mean=arg[1],
                                       dev=arg[2],
                                       var=processed_var)
Ultimanet's avatar
Ultimanet committed
890
            sample.apply_generator(gen)
891

Ultimanet's avatar
Ultimanet committed
892
893
            if hermitianizeQ == True:
                sample = utilities.hermitianize(sample)
Ultimanet's avatar
Ultimanet committed
894

895
        # Case 3: uniform distribution
Ultimanet's avatar
Ultimanet committed
896
        elif arg[0] == "uni" and hermitianizeQ == False:
Ultimanet's avatar
Ultimanet committed
897
            gen = lambda s: random.uni(datatype=self.datatype,
898
899
900
                                       shape=s,
                                       vmin=arg[1],
                                       vmax=arg[2])
Ultimanet's avatar
Ultimanet committed
901
            sample.apply_generator(gen)
902

Ultimanet's avatar
Ultimanet committed
903
        elif arg[0] == "uni" and hermitianizeQ == True:
904
905
906
907
908
            # 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.
Ultimanet's avatar
Ultimanet committed
909
            if issubclass(sample.dtype, np.complexfloating):
910
                temp_func = lambda x: erf(x.real) + 1j * erf(x.imag)
Ultimanet's avatar
Ultimanet committed
911
            else:
912
913
914
915
916
                temp_func = lambda x: erf(x / np.sqrt(2))
            sample.apply_scalar_function(function=temp_func,
                                         inplace=True)

            # Shift and stretch the uniform distribution into the given limits
Ultimanet's avatar
Ultimanet committed
917
918
            ## sample = (sample + 1)/2 * (vmax-vmin) + vmin
            vmin = arg[1]
919
920
921
            vmax = arg[2]
            sample *= (vmax - vmin) / 2.
            sample += 1 / 2. * (vmax + vmin)
Marco Selig's avatar
Marco Selig committed
922

923
        elif(arg[0] == "syn"):
Ultimanet's avatar
Ultimanet committed
924
925
926
927
928
929
            spec = arg[1]
            kpack = arg[2]
            harmonic_domain = arg[3]
            log = arg[4]
            nbin = arg[5]
            binbounds = arg[6]
930
931
932
            # 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
Ultimanet's avatar
Ultimanet committed
933
934
            if kpack == None:
                power_indices =\
935
936
937
938
                    harmonic_domain.power_indices.get_index_dict(log=log,
                                                                 nbin=nbin,
                                                                 binbounds=binbounds)

Ultimanet's avatar
Ultimanet committed
939
940
941
942
943
944
                kindex = power_indices['kindex']
                kdict = power_indices['kdict']
                kpack = [power_indices['pindex'], power_indices['kindex']]
            else:
                kindex = kpack[1]
                kdict = harmonic_domain.power_indices.\
945
946
947
948
949
950
951
952
                    _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
953
                if self.paradict['complexity'] == 0:
954
955
956
957
958
                    # set up the sample object. Overwrite the default from
                    # above to be sure, that the distribution strategy matches
                    # with the one from kdict
                    sample = kdict.copy_empty(dtype=self.datatype)
                    # set up the random number generator
Ultimanet's avatar
Ultimanet committed
959
                    gen = lambda s: np.random.normal(loc=0, scale=1, size=s)
960
                    # apply the random number generator
Ultimanet's avatar
Ultimanet committed
961
                    sample.apply_generator(gen)
Marco Selig's avatar
Marco Selig committed
962

963
964
965
966
967
                # 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
968
969
                elif self.paradict['complexity'] == 1:
                    temp_codomain = self.get_codomain()
970
971
972
                    # 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
973
                    sample = kdict.copy_empty(
974
975
                        dtype=temp_codomain.datatype)
                    # set up the random number generator
Ultimanet's avatar
Ultimanet committed
976

Ultimanet's avatar
Ultimanet committed
977
                    gen = lambda s: np.random.normal(loc=0, scale=1, size=s)
978
                    # apply the random number generator
Ultimanet's avatar
Ultimanet committed
979
                    sample.apply_generator(gen)
980
981
982
983
984
985

                    # 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
986
                    sqrt_of_dim = np.sqrt(self.get_dim())
Ultimanet's avatar
Ultimanet committed
987
988
989
                    sample /= sqrt_of_dim
                    sample = temp_codomain.calc_weight(sample, power=-1)

990
                    # tronsform the random field to harmonic space
Ultimanet's avatar
Ultimanet committed
991
                    sample = temp_codomain.\
992
993
994
995
996
997
998
999
1000
1001
                        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
1002
                elif self.paradict['complexity'] == 2:
1003
1004
1005
1006
1007
                    # set up the sample object. Overwrite the default from
                    # above to be sure, that the distribution strategy matches
                    # with the one from kdict
                    sample = kdict.copy_empty(dtype=self.datatype)
                    # set up the random number generator
Ultimanet's avatar
Ultimanet committed
1008
                    gen = lambda s: (
1009
1010
1011
1012
1013
                        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
                    )
                    # apply the random number generator
Ultimanet's avatar
Ultimanet committed
1014
                    sample.apply_generator(gen)
1015
1016
1017

                # apply the powerspectrum renormalization
                # therefore extract the local data from kdict
Ultimanet's avatar
Ultimanet committed
1018
1019
                local_kdict = kdict.get_local_data()
                rescaler = np.sqrt(
1020
1021
                    spec[np.searchsorted(kindex, local_kdict)])
                sample.apply_scalar_function(lambda x: x * rescaler,
Ultimanet's avatar
Ultimanet committed
1022
                                             inplace=True)
1023
            # Case 2: self is a position space
Ultimanet's avatar
Ultimanet committed
1024
            else:
1025
1026
                # get a suitable codomain
                temp_codomain = self.get_codomain()
Ultimanet's avatar
Ultimanet committed
1027

1028
1029
1030
                # 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
1031
                if self.paradict['complexity'] == 0:
1032
                    # check that the codomain is hermitian
Ultimanet's avatar
Ultimanet committed
1033
                    assert(temp_codomain.paradict['complexity'] == 1)
1034
1035
1036
1037

                # 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
1038
                elif self.paradict['complexity'] == 1:
1039
1040
                    # check that the codomain is real
                    assert(temp_codomain.paradict['complexity'] == 0)
Ultimanet's avatar
Ultimanet committed
1041

1042
1043
1044
1045
1046
1047
                # 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
1048

1049
1050
                # Get a hermitian/real/complex sample in harmonic space from
                # the codomain
Ultimanet's avatar
Ultimanet committed
1051
                sample = temp_codomain.get_random_values(
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
                    random='syn',
                    pindex=kpack[0],
                    kindex=kpack[1],
                    spec=spec,
                    codomain=self,
                    log=log,
                    nbin=nbin,
                    binbounds=binbounds
                )
                # Correct the weighting
Ultimanet's avatar
Ultimanet committed
1062
                #sample = self.calc_weight(sample, power=-1)
1063
1064
1065
1066

                # Take the fourier transform
                sample = temp_codomain.calc_transform(sample,
                                                      codomain=self)
Ultimanet's avatar
Ultimanet committed
1067
1068

            if self.paradict['complexity'] == 1:
1069
1070
                sample.hermitian = True

Ultimanet's avatar
Ultimanet committed
1071
1072
        else:
            raise KeyError(about._errors.cstring(
1073
                "ERROR: unsupported random key '" + str(arg[0]) + "'."))
Marco Selig's avatar
Marco Selig committed
1074

1075
        return sample
Marco Selig's avatar
Marco Selig committed
1076

1077
    # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Marco Selig's avatar
Marco Selig committed
1078

1079
    def check_codomain(self, codomain):
Marco Selig's avatar
Marco Selig committed
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
        """
            Checks whether a given codomain is compatible to the space or not.

            Parameters
            ----------
            codomain : nifty.space
                Space to be checked for compatibility.

            Returns
            -------
            check : bool
                Whether or not the given codomain is compatible to the space.
        """
1093
        if codomain is None:
1094
            return False
1095
1096

        if not isinstance(codomain, rg_space):
Marco Selig's avatar
Marco Selig committed
1097
1098
            raise TypeError(about._errors.cstring("ERROR: invalid input."))

1099
1100
1101
        if self.datamodel is not codomain.datamodel:
            return False
        # check number of number and size of axes
Ultimanet's avatar
Ultimanet committed
1102
1103
        if not np.all(self.paradict['num'] == codomain.paradict['num']):
            return False
1104
1105
1106

        # check fourier flag
        if self.harmonic == codomain.fourier:
Ultimanet's avatar
Ultimanet committed
1107
            return False
1108
1109
1110

        # check complexity-type
        # prepare the shorthands
Ultimanet's avatar
Ultimanet committed
1111
1112
        dcomp = self.paradict['complexity']
        cocomp = codomain.paradict['complexity']