nifty_rg.py 116 KB
Newer Older
1
2
# NIFTY (Numerical Information Field Theory) has been developed at the
# Max-Planck-Institute for Astrophysics.
Marco Selig's avatar
Marco Selig committed
3
##
4
# Copyright (C) 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
from nifty.keepers import about,\
Ultima's avatar
Ultima committed
44
45
                          global_dependency_injector as gdi,\
                          global_configuration as gc
46
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

import nifty_fft

Ultima's avatar
Ultima committed
57
MPI = gdi[gc['mpi_module']]
58
59

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

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

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

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

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

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

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

197
        # set volume
Marco Selig's avatar
Marco Selig committed
198
        if(dist is None):
199
            dist = 1 / np.array(self.paradict['num'], dtype=self.datatype)
Marco Selig's avatar
Marco Selig committed
200
        elif(np.isscalar(dist)):
201
202
            dist = self.datatype(dist) * np.ones(naxes, dtype=self.datatype,
                                                 order='C')
Marco Selig's avatar
Marco Selig committed
203
        else:
204
            dist = np.array(dist, dtype=self.datatype)
205
            if(np.size(dist) == 1):
206
207
208
209
210
211
212
                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(
213
214
                "ERROR: nonpositive distance(s)."))
        self.vol = np.real(dist)
Marco Selig's avatar
Marco Selig committed
215

216
        # TODO: Deprecate self.fourier
Marco Selig's avatar
Marco Selig committed
217
        self.fourier = bool(fourier)
218
        self.harmonic = self.fourier
Ultima's avatar
Ultima committed
219

220
221
        # Initializes the fast-fourier-transform machine, which will be used
        # to transform the space
Ultima's avatar
Ultima committed
222
223
224
        if not gc.validQ('fft_module', fft_module):
            fft_module = gc['fft_module']
        self.fft_machine = nifty_fft.fft_factory(fft_module)
225
226
227
228
229
230
231
232
233
234
235

        # 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)

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

243
244
    @para.setter
    def para(self, x):
245
246
247
        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
248
249


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

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

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

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

    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.
        """
283
        # return self.para[-(np.size(self.para)-1)//2:][::-1].astype(np.bool)
284
        return self.paradict['zerocenter']
Marco Selig's avatar
Marco Selig committed
285
286
287
288
289
290
291
292
293
294

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

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

297
    def get_shape(self):
298
        return np.array(self.paradict['num'])
Marco Selig's avatar
Marco Selig committed
299

300
    def get_dim(self, split=False):
Marco Selig's avatar
Marco Selig committed
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
        """
            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)
317
        if split == True:
318
            return self.get_shape()
Marco Selig's avatar
Marco Selig committed
319
        else:
320
            return np.prod(self.get_shape())
Marco Selig's avatar
Marco Selig committed
321

322
    # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Marco Selig's avatar
Marco Selig committed
323

324
    def get_dof(self):
Marco Selig's avatar
Marco Selig committed
325
326
327
328
329
330
331
332
333
334
        """
            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.
        """
335
        # dof ~ dim
336
337
        if self.paradict['complexity'] < 2:
            return np.prod(self.paradict['num'])
Marco Selig's avatar
Marco Selig committed
338
        else:
339
            return 2 * np.prod(self.paradict['num'])
340
341
342
343

#        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:
344
345
# 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
346

347
    # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
ultimanet's avatar
ultimanet committed
348

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

        # 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:
395
396
                kindex_supply_space = self
            else:
397
398
                # Check if the given codomain is compatible with the space
                try:
399
400
401
                    assert(self.check_codomain(codomain))
                    kindex_supply_space = codomain
                except(AssertionError):
402
403
404
405
                    about.warnings.cprint("WARNING: Supplied codomain is " +
                                          "incompatible. Generating a " +
                                          "generic codomain. This can " +
                                          "be expensive!")
406
407
                    kindex_supply_space = self.get_codomain()
            kindex = kindex_supply_space.\
408
409
410
411
412
413
414
415
                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
416
        if callable(spec) == True:
417
            # Try to plug in the kindex array in the function directly
Marco Selig's avatar
Marco Selig committed
418
            try:
419
                spec = np.array(spec(kindex), dtype=self.datatype)
Marco Selig's avatar
Marco Selig committed
420
            except:
421
422
                # Second try: Use a vectorized version of the function.
                # This is slower, but better than nothing
423
424
425
426
                try:
                    spec = np.vectorize(spec)(kindex)
                except:
                    raise TypeError(about._errors.cstring(
427
428
429
                        "ERROR: invalid power spectra function."))

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

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

        # Make some sanity checks
        # Drop imaginary part
440
441
442
443
444
445
        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
446
447

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

        # check positivity (excluding null)
        if np.any(spec < 0):
453
            raise ValueError(about._errors.cstring(
454
455
456
457
458
                "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
459
460
        if size == None:
            size = len(kindex)
461
462
463

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

475
        return spec
476

477
    # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Marco Selig's avatar
Marco Selig committed
478

Ultimanet's avatar
Ultimanet committed
479
    def set_power_indices(self, log=False, nbin=None, binbounds=None, **kwargs):
Marco Selig's avatar
Marco Selig committed
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
        """
            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
510
                If ``self.harmonic == False``.
Marco Selig's avatar
Marco Selig committed
511
512
513
514
            ValueError
                If the binning leaves one or more bins empty.

        """
515

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

522
    # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
523

Ultima's avatar
Ultima committed
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
    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)

        return casted_x

#    def _cast_to_d2o(self, x, dtype=None, ignore_complexity=False,
#                     verbose=False, **kwargs):
#        """
#            Computes valid field values from a given object, trying
#            to translate the given data into a valid form. Thereby it is as
#            benevolent as possible.
#
#            Parameters
#            ----------
#            x : {float, numpy.ndarray, nifty.field}
#                Object to be transformed into an array of valid field values.
#
#            Returns
#            -------
#            x : numpy.ndarray, distributed_data_object
#                Array containing the field values, which are compatible to the
#                space.
#
#            Other parameters
#            ----------------
#            verbose : bool, *optional*
#                Whether the method should raise a warning if information is
#                lost during casting (default: False).
#        """
#        if dtype is None:
#            dtype = self.datatype
#        # Case 1: x is a field
#        if isinstance(x, field):
#            if verbose:
#                # Check if the domain matches
#                if(self != x.domain):
#                    about.warnings.cflush(
#                        "WARNING: Getting data from foreign domain!")
#            # Extract the data, whatever it is, and cast it again
#            return self.cast(x.val, dtype=dtype)
#
#        # Case 2: x is a distributed_data_object
#        if isinstance(x, distributed_data_object):
#            # Check the shape
#            if np.any(x.shape != self.get_shape()):
#                # Check if at least the number of degrees of freedom is equal
#                if x.get_dim() == self.get_dim():
#                    # 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")
#                    temp = x.get_full_data()
#                    temp = np.reshape(temp, self.get_shape())
#                    # ... and cast again
#                    return self.cast(temp, dtype=dtype)
#
#                else:
#                    raise ValueError(about._errors.cstring(
#                        "ERROR: Data has incompatible shape!"))
#
#            # Check the datatype
#            if np.dtype(x.dtype) != np.dtype(dtype):
#                if np.dtype(x.dtype) > np.dtype(dtype):
#                    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")
#                temp = x.copy_empty(dtype=dtype)
#                temp.set_local_data(x.get_local_data())
#                temp.hermitian = x.hermitian
#                x = temp
#
#            if not ignore_complexity:
#                # Check hermitianity/reality
#                if self.paradict['complexity'] == 0:
#                    if x.iscomplex().any() == True:
#                        about.warnings.cflush(
#                            "WARNING: Data is not completely real. Imaginary part " +
#                            "will be discarded!\n")
#                        temp = x.copy_empty()
#                        temp.set_local_data(np.real(x.get_local_data()))
#                        x = temp
#
#                elif self.paradict['complexity'] == 1:
#                    if x.hermitian == False and about.hermitianize.status == True:
#                        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(),
#                        #    (False, )*len(x.shape)))
#                        x = utilities.hermitianize(x)
#
#            return x
#
#        # 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
#        return self.cast(x, dtype=dtype)


    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 and \
           not casted_x.hermitian:
            about.warnings.cflush(
                 "WARNING: Data gets hermitianized. This operation is " +
                 "extremely expensive\n")
            casted_x = utilities.hermitianize(casted_x)

        return casted_x

#    def _cast_to_np(self, x, dtype=None, ignore_complexity=False,
#                    verbose=False, **kwargs):
#        """
#            Computes valid field values from a given object, trying
#            to translate the given data into a valid form. Thereby it is as
#            benevolent as possible.
#
#            Parameters
#            ----------
#            x : {float, numpy.ndarray, nifty.field}
#                Object to be transformed into an array of valid field values.
#
#            Returns
#            -------
#            x : numpy.ndarray, distributed_data_object
#                Array containing the field values, which are compatible to the
#                space.
#
#            Other parameters
#            ----------------
#            verbose : bool, *optional*
#                Whether the method should raise a warning if information is
#                lost during casting (default: False).
#        """
#        if dtype is None:
#            dtype = self.datatype
#        # Case 1: x is a field
#        if isinstance(x, field):
#            if verbose:
#                # Check if the domain matches
#                if(self != x.domain):
#                    about.warnings.cflush(
#                        "WARNING: Getting data from foreign domain!")
#            # Extract the data, whatever it is, and cast it again
#            return self.cast(x.val, dtype=dtype)
#
#        # Case 2: x is a distributed_data_object
#        if isinstance(x, distributed_data_object):
#            # Extract the data
#            temp = x.get_full_data()
#            # Cast the resulting numpy array again
#            return self.cast(temp, dtype=dtype)
#
#        elif isinstance(x, np.ndarray):
#            # Check the shape
#            if np.any(x.shape != self.get_shape()):
#                # Check if at least the number of degrees of freedom is equal
#                if x.size == self.get_dim():
#                    # If the number of dof is equal or 1, use np.reshape...
#                    temp = x.reshape(self.get_shape())
#                    # ... and cast again
#                    return self.cast(temp, dtype=dtype)
#                elif x.size == 1:
#                    temp = np.empty(shape=self.get_shape(),
#                                    dtype=dtype)
#                    temp[:] = x
#                    return self.cast(temp, dtype=dtype)
#                else:
#                    raise ValueError(about._errors.cstring(
#                        "ERROR: Data has incompatible shape!"))
#
#            # Check the datatype
#            if x.dtype != dtype:
#                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...
#                temp = x.astype(dtype)
#                # ... and cast again
#                return self.cast(temp, dtype=dtype)
#
#            if ignore_complexity == False:
#                # Check hermitianity/reality
#                if self.paradict['complexity'] == 0:
#                    if not np.all(np.isreal(x)) == True:
#                        about.warnings.cflush(
#                            "WARNING: Data is not completely real. Imaginary part " +
#                            "will be discarded!\n")
#                        x = np.real(x)
#
#                elif self.paradict['complexity'] == 1:
#                    if about.hermitianize.status == True:
#                        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(),
#                        #    (False, )*len(x.shape)))
#                        x = utilities.hermitianize(x)
#
#            return x
#
#        # Case 3: x is something else
#        # Use general numpy casting
#        else:
#            temp = np.empty(self.get_shape(), dtype=dtype)
#            temp[:] = x
#            return temp
749
750

    def enforce_values(self, x, extend=True):
Marco Selig's avatar
Marco Selig committed
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
        """
            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).
        """
771
        about.warnings.cflush(
772
            "WARNING: enforce_values is deprecated function. Please use self.cast")
773
774
        if(isinstance(x, field)):
            if(self == x.domain):
Marco Selig's avatar
Marco Selig committed
775
                if(self.datatype is not x.domain.datatype):
776
777
                    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
778
779
780
                else:
                    x = np.copy(x.val)
            else:
781
782
                raise ValueError(about._errors.cstring(
                    "ERROR: inequal domains."))
Marco Selig's avatar
Marco Selig committed
783
        else:
784
            if(np.size(x) == 1):
Marco Selig's avatar
Marco Selig committed
785
                if(extend):
786
787
                    x = self.datatype(
                        x) * np.ones(self.get_dim(split=True), dtype=self.datatype, order='C')
Marco Selig's avatar
Marco Selig committed
788
789
                else:
                    if(np.isscalar(x)):
790
                        x = np.array([x], dtype=self.datatype)
Marco Selig's avatar
Marco Selig committed
791
                    else:
792
                        x = np.array(x, dtype=self.datatype)
Marco Selig's avatar
Marco Selig committed
793
            else:
794
                x = self.enforce_shape(np.array(x, dtype=self.datatype))
Marco Selig's avatar
Marco Selig committed
795

796
797
        # 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
798
799
            #x = gp.nhermitianize_fast(x,self.para[-((np.size(self.para)-1)//2):].astype(np.bool),special=False)
            x = utilities.hermitianize(x)
800
        # check finiteness
Marco Selig's avatar
Marco Selig committed
801
802
803
804
805
        if(not np.all(np.isfinite(x))):
            about.warnings.cprint("WARNING: infinite value(s).")

        return x

806
    # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Marco Selig's avatar
Marco Selig committed
807

808
    def get_random_values(self, **kwargs):
Marco Selig's avatar
Marco Selig committed
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
        """
            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
846
                A compatible codomain (default: None).
Marco Selig's avatar
Marco Selig committed
847
848
849
850
851
852
853
854
855
856
857
858
859
860
            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"``
861
                (default: 0).
Ultimanet's avatar
Ultimanet committed
862
            vmin : float, *optional*
Marco Selig's avatar
Marco Selig committed
863
864
865
866
                Lower limit for a uniform distribution (default: 0).
            vmax : float, *optional*
                Upper limit for a uniform distribution (default: 1).
        """
867
868
869
870
        # TODO: Without hermitianization the random-methods from pointspace
        # could be used.

        # Parse the keyword arguments
871
        arg = random.parse_arguments(self, **kwargs)
872
873
874

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

877
878
879
        # Should the output be hermitianized? This does not depend on the
        # hermitianize boolean in about, as it would yield in wrong,
        # not recoverable results
880

881
882
        #hermitianizeQ = about.hermitianize.status and self.paradict['complexity']
        hermitianizeQ = self.paradict['complexity']
Ultimanet's avatar
Ultimanet committed
883

884
        # Case 1: uniform distribution over {-1,+1}/{1,i,-1,-i}
Ultimanet's avatar
Ultimanet committed
885
        if arg[0] == 'pm1' and hermitianizeQ == False:
Ultimanet's avatar
Ultimanet committed
886
            gen = lambda s: random.pm1(datatype=self.datatype,
887
                                       shape=s)
Ultimanet's avatar
Ultimanet committed
888
            sample.apply_generator(gen)
889

Ultimanet's avatar
Ultimanet committed
890
        elif arg[0] == 'pm1' and hermitianizeQ == True:
891
            sample = self.get_random_values(random='uni', vmin=-1, vmax=1)
Ultimanet's avatar
Ultimanet committed
892
893
894
895
            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
896
897
898
                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
899
900
901
902
            else:
                local_data[local_data >= 0] = 1
                local_data[local_data < 0] = -1
            sample.set_local_data(local_data)
903
904

        # Case 2: normal distribution with zero-mean and a given standard
Ultimanet's avatar
Ultimanet committed
905
906
        ##         deviation or variance
        elif arg[0] == 'gau':
907
            var = arg[3]
908
909
910
911
912
913
914
            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
915

Ultimanet's avatar
Ultimanet committed
916
            gen = lambda s: random.gau(datatype=self.datatype,
917
918
919
920
                                       shape=s,
                                       mean=arg[1],
                                       dev=arg[2],
                                       var=processed_var)
Ultimanet's avatar
Ultimanet committed
921
            sample.apply_generator(gen)
922

Ultimanet's avatar
Ultimanet committed
923
924
            if hermitianizeQ == True:
                sample = utilities.hermitianize(sample)
Ultimanet's avatar
Ultimanet committed
925

926
        # Case 3: uniform distribution
Ultimanet's avatar
Ultimanet committed
927
        elif arg[0] == "uni" and hermitianizeQ == False:
Ultimanet's avatar
Ultimanet committed
928
            gen = lambda s: random.uni(datatype=self.datatype,
929
930
931
                                       shape=s,
                                       vmin=arg[1],
                                       vmax=arg[2])
Ultimanet's avatar
Ultimanet committed
932
            sample.apply_generator(gen)
933

Ultimanet's avatar
Ultimanet committed
934
        elif arg[0] == "uni" and hermitianizeQ == True:
935
936
937
938
939
            # 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
940
            if issubclass(sample.dtype, np.complexfloating):
941
                temp_func = lambda x: erf(x.real) + 1j * erf(x.imag)
Ultimanet's avatar
Ultimanet committed
942
            else:
943
944
945
946
947
                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
948
949
            ## sample = (sample + 1)/2 * (vmax-vmin) + vmin
            vmin = arg[1]
950
951
952
            vmax = arg[2]
            sample *= (vmax - vmin) / 2.
            sample += 1 / 2. * (vmax + vmin)
Marco Selig's avatar
Marco Selig committed
953

954
        elif(arg[0] == "syn"):
Ultimanet's avatar
Ultimanet committed
955
956
957
958
959
960
            spec = arg[1]
            kpack = arg[2]
            harmonic_domain = arg[3]
            log = arg[4]
            nbin = arg[5]
            binbounds = arg[6]
961
962
963
            # 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
964
965
            if kpack == None:
                power_indices =\
966
967
968
969
                    harmonic_domain.power_indices.get_index_dict(log=log,
                                                                 nbin=nbin,
                                                                 binbounds=binbounds)

Ultimanet's avatar
Ultimanet committed
970
971
972
973
974
975
                kindex = power_indices['kindex']
                kdict = power_indices['kdict']
                kpack = [power_indices['pindex'], power_indices['kindex']]
            else:
                kindex = kpack[1]
                kdict = harmonic_domain.power_indices.\
976
977
978
979
980
981
982
983
                    _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
984
                if self.paradict['complexity'] == 0:
985
986
987
988
989
                    # 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
990
                    gen = lambda s: np.random.normal(loc=0, scale=1, size=s)
991
                    # apply the random number generator
Ultimanet's avatar
Ultimanet committed
992
                    sample.apply_generator(gen)
Marco Selig's avatar
Marco Selig committed
993

994
995
996
997
998
                # 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
999
1000
                elif self.paradict['complexity'] == 1:
                    temp_codomain = self.get_codomain()
1001
1002
1003
                    # 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
1004
                    sample = kdict.copy_empty(
1005
1006
                        dtype=temp_codomain.datatype)
                    # set up the random number generator
Ultimanet's avatar
Ultimanet committed
1007

Ultimanet's avatar
Ultimanet committed
1008
                    gen = lambda s: np.random.normal(loc=0, scale=1, size=s)
1009
                    # apply the random number generator
Ultimanet's avatar
Ultimanet committed
1010
                    sample.apply_generator(gen)
1011
1012
1013
1014
1015
1016

                    # 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
1017
                    sqrt_of_dim = np.sqrt(self.get_dim())
Ultimanet's avatar
Ultimanet committed
1018
1019
1020
                    sample /= sqrt_of_dim
                    sample = temp_codomain.calc_weight(sample, power=-1)

1021
                    # tronsform the random field to harmonic space
Ultimanet's avatar
Ultimanet committed
1022
                    sample = temp_codomain.\
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
                        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
1033
                elif self.paradict['complexity'] == 2:
1034
1035
1036
1037
1038
                    # 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
1039
                    gen = lambda s: (
1040
1041
1042
1043
1044
                        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
1045
                    sample.apply_generator(gen)
1046
1047
1048

                # apply the powerspectrum renormalization
                # therefore extract the local data from kdict
Ultimanet's avatar
Ultimanet committed
1049
1050
                local_kdict = kdict.get_local_data()
                rescaler = np.sqrt(
1051
1052
                    spec[np.searchsorted(kindex, local_kdict)])
                sample.apply_scalar_function(lambda x: x * rescaler,
Ultimanet's avatar
Ultimanet committed
1053
                                             inplace=True)
1054
            # Case 2: self is a position space
Ultimanet's avatar
Ultimanet committed
1055
            else:
1056
1057
                # get a suitable codomain
                temp_codomain = self.get_codomain()
Ultimanet's avatar
Ultimanet committed
1058

1059
1060
1061
                # 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
1062
                if self.paradict['complexity'] == 0:
1063
                    # check that the codomain is hermitian
Ultimanet's avatar
Ultimanet committed
1064
                    assert(temp_codomain.paradict['complexity'] == 1)
1065
1066
1067
1068

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

1073
1074
1075
1076
1077
1078
                # 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
1079

1080
1081
                # Get a hermitian/real/complex sample in harmonic space from
                # the codomain
Ultimanet's avatar
Ultimanet committed
1082
                sample = temp_codomain.get_random_values(
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
                    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
1093
                #sample = self.calc_weight(sample, power=-1)
1094
1095
1096
1097

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

            if self.paradict['complexity'] == 1:
1100
1101
                sample.hermitian = True

Ultimanet's avatar
Ultimanet committed
1102
1103
        else:
            raise KeyError(about._errors.cstring(
1104
                "ERROR: unsupported random key '" + str(arg[0]) + "'."))
Marco Selig's avatar
Marco Selig committed
1105

1106
        return sample
Marco Selig's avatar
Marco Selig committed
1107

1108
    # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Marco Selig's avatar
Marco Selig committed
1109

1110
    def check_codomain(self, codomain):
Marco Selig's avatar
Marco Selig committed
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
        """
            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.
        """
1124
        if codomain is None:
1125
            return False
1126
1127

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

1130
1131
1132
        if self.datamodel is not codomain.datamodel:
            return False
        # check number of number and size of axes
Ultimanet's avatar
Ultimanet committed
1133
1134
        if not np.all(self.paradict['num'] == codomain.paradict['num']):
            return False
1135
1136
1137

        # check fourier flag
        if self.harmonic == codomain.fourier:
Ultimanet's avatar
Ultimanet committed
1138
            return False
1139
1140
1141

        # check complexity-type
        # prepare the shorthands
Ultimanet's avatar
Ultimanet committed
1142
1143
        dcomp = self.paradict['complexity']
        cocomp = codomain.paradict['complexity']
1144
1145
1146

        # Case 1: if the domain is copmleteley complex
        # -> the codomain must be complex, too
Ultimanet's avatar
Ultimanet committed
1147
1148
1149
        if dcomp == 2:
            if cocomp != 2:
                return False
1150
1151
1152
        # Case 2: domain is hermitian
        # -> codmomain can be real. If it is marked as hermitian or even
        # fully complex, a warning is raised
Ultimanet's avatar
Ultimanet committed
1153
1154
        elif dcomp == 1:
            if cocomp > 0:
1155
1156
1157
1158
1159
1160
                about.warnings.cprint("WARNING: Unrecommended codomain! " +
                                      "The domain is hermitian, hence the codomain should " +
                                      "be restricted to real values!")

        # Case 3: domain is real
        # -> codmain should be hermitian
Ultimanet's avatar
Ultimanet committed
1161
1162
        elif dcomp == 0:
            if cocomp == 2:
1163
1164
1165
                about.warnings.cprint("WARNING: Unrecommended codomain! " +
                                      "The domain is real, hence the codomain should " +
                                      "be restricted to hermitian configurations!")
Ultimanet's avatar
Ultimanet committed
1166
1167
1168
            elif cocomp == 0:
                return False

1169
        # Check if the distances match, i.e. dist'=1/(num*dist)
Ultimanet's avatar
Ultimanet committed
1170
        if not np.all(
1171
1172
1173
                np.absolute(self.paradict['num'] *
                            self.vol *
                            codomain.vol - 1) < self.epsilon):
Ultimanet's avatar
Ultimanet committed
1174
            return False
1175

Ultimanet's avatar
Ultimanet committed
1176
        return True
Marco Selig's avatar
Marco Selig committed
1177

1178
    # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Marco Selig's avatar
Marco Selig committed
1179

Ultimanet's avatar
Ultimanet committed
1180
    def get_codomain(self, coname=None, cozerocenter=None, **kwargs):
Marco Selig's avatar
Marco Selig committed
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
        """
            Generates a compatible codomain to which transformations are
            reasonable, i.e.\  either a shifted grid or a Fourier conjugate
            grid.

            Parameters
            ----------
            coname : string, *optional*
                String specifying a desired codomain (default: None).
            cozerocenter : {bool, numpy.ndarray}, *optional*
                Whether or not the grid is zerocentered for each axis or not
                (default: None).

            Returns
            -------
            codomain : nifty.rg_space
                A compatible codomain.

            Notes
            -----
            Possible arguments for `coname` are ``'f'`` in which case the
1202
1203
            codomain arises from a Fourier transformation, ``'i'`` in which
            case it arises from an inverse Fourier transformation.If no
Ultimanet's avatar
Ultimanet committed
1204
            `coname` is given, the Fourier conjugate grid is produced.
Marco Selig's avatar
Marco Selig committed
1205
        """
1206
1207
        naxes = self.get_naxes()
        # Parse the cozerocenter input
Marco Selig's avatar
Marco Selig committed
1208
        if(cozerocenter is None):
Ultimanet's avatar
Ultimanet committed
1209
            cozerocenter = self.paradict['zerocenter']
1210
        # if the input is something scalar, cast it to a boolean
Marco Selig's avatar
Marco Selig committed
1211
1212
        elif(np.isscalar(cozerocenter)):
            cozerocenter = bool(cozerocenter)
1213
        # if it is not a scalar...
Marco Selig's avatar
Marco Selig committed
1214
        else:
1215
1216
1217
1218
            # ...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):
Marco Selig's avatar
Marco Selig committed
1219
                cozerocenter = np.asscalar(cozerocenter)
1220
1221
1222
            # if the length of the input does not match the number of
            # dimensions, raise an exception
            elif(np.size(cozerocenter) != naxes):
Ultimanet's avatar
Ultimanet committed
1223
                raise ValueError(about._errors.cstring(
1224
1225
1226
1227
                    "ERROR: size mismatch ( " +
                    str(np.size(cozerocenter)) + " <> " + str(naxes) + " )."))

        # Set up the initialization variables
Ultimanet's avatar
Ultimanet committed
1228
        num = self.paradict['num']
1229
        purelyreal = (self.paradict['complexity'] == 1)
Ultimanet's avatar
Ultimanet committed
1230
        hermitian = (self.paradict['complexity'] < 2)
1231
        dist = 1 / (self.paradict['num'] * self.vol)
1232
        datamodel = self.datamodel
1233

Ultimanet's avatar
Ultimanet committed
1234
        if coname == None:
1235
            fourier = bool(not self.harmonic)
Ultimanet's avatar
Ultimanet committed
1236
1237
1238
1239
1240
1241
        elif coname[0] == 'f':
            fourier = True
        elif coname[0] == 'i':
            fourier = False
        else:
            raise ValueError(about._errors.cstring(
1242
                "ERROR: Unknown coname keyword"))
Ultimanet's avatar
Ultimanet committed
1243
        new_space = rg_space(num,
1244
1245
1246
1247
1248
1249
                             zerocenter=cozerocenter,
                             hermitian=hermitian,
                             purelyreal=purelyreal,
                             dist=dist,
                             fourier=fourier,
                             datamodel=datamodel)
Ultimanet's avatar
Ultimanet committed
1250
        return new_space
Marco Selig's avatar
Marco Selig committed
1251

1252
    # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Marco Selig's avatar
Marco Selig committed
1253

Ultimanet's avatar
Ultimanet committed
1254
    def get_meta_volume(self, total=False):
Marco Selig's avatar
Marco Selig committed
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
        """
            Calculates the meta volumes.

            The meta volumes are the volumes associated with each component of
            a field, taking into account field components that are not
            explicitly included in the array of field values but are determined
            by symmetry conditions. In the case of an :py:class:`rg_space`, the
            meta volumes are simply the pixel volumes.

            Parameters
            ----------
            total : bool, *optional*
                Whether to return the total meta volume of the space or the
                individual ones of each pixel (default: False).

            Returns
            -------
            mol : {numpy.ndarray, float}
                Meta volume of the pixels or the complete space.
        """
1275
        if total == True:
1276
            return self.get_dim() * np.prod(self.vol)
Marco Selig's avatar
Marco Selig committed
1277
        else:
1278
1279
1280
            mol = np.ones(self.get_shape(),
                          dtype=self.vol.dtype)
            return self.calc_weight(mol, power=1)
Marco Selig's avatar
Marco Selig committed
1281