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

"""
    ..                  __   ____   __
    ..                /__/ /   _/ /  /_
    ..      __ ___    __  /  /_  /   _/  __   __
    ..    /   _   | /  / /   _/ /  /   /  / /  /
    ..   /  / /  / /  / /  /   /  /_  /  /_/  /
    ..  /__/ /__/ /__/ /__/    \___/  \___   /  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
Ultimanet's avatar
Ultimanet committed
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

Ultimanet's avatar
Ultimanet committed
43
44
from mpi4py import MPI

Ultimanet's avatar
Ultimanet committed
45
46
from nifty.nifty_about import about
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
Ultimanet's avatar
Ultimanet committed
50
from nifty.nifty_paradict import rg_space_paradict
Ultima's avatar
Ultima committed
51
import nifty.nifty_utilities as utilities
Ultimanet's avatar
Ultimanet committed
52
53
import fft_rg

ultimanet's avatar
ultimanet committed
54
'''
Marco Selig's avatar
Marco Selig committed
55
56
57
58
59
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
60
'''
Ultimanet's avatar
Ultimanet committed
61
62


Marco Selig's avatar
Marco Selig committed
63
64
65
66


##-----------------------------------------------------------------------------

67
class rg_space(point_space):
Marco Selig's avatar
Marco Selig committed
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
    """
        ..      _____   _______
        ..    /   __/ /   _   /
        ..   /  /    /  /_/  /
        ..  /__/     \____  /  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.
    """
    epsilon = 0.0001 ## relative precision for comparisons

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

Ultimanet's avatar
Ultimanet committed
165
166
167
        if np.isscalar(num):
            num = (num,)*np.asscalar(np.array(naxes))
            
168
169
        self.paradict = rg_space_paradict(num=num, 
                                          complexity=complexity, 
170
171
172
173
                                          zerocenter=zerocenter)        
        
        
        naxes = len(self.paradict['num'])
Marco Selig's avatar
Marco Selig committed
174

175
        ## set datatype
Ultimanet's avatar
Ultimanet committed
176
        if  self.paradict['complexity'] == 0:
Marco Selig's avatar
Marco Selig committed
177
178
179
            self.datatype = np.float64
        else:
            self.datatype = np.complex128
180
181
182
183
184
185
186
187
        
        ## set datamodel
        if datamodel not in ['np', 'd2o']:
            about.warnings.cprint("WARNING: datamodel set to default.")
            self.datamodel = 'd2o'
        else:
            self.datamodel = datamodel

Marco Selig's avatar
Marco Selig committed
188
189
190
191
192

        self.discrete = False

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

        self.fourier = bool(fourier)
ultimanet's avatar
ultimanet committed
211
212
        
        ## Initializes the fast-fourier-transform machine, which will be used 
ultimanet's avatar
ultimanet committed
213
        ## to transform the space
ultimanet's avatar
ultimanet committed
214
        self.fft_machine = fft_rg.fft_factory()
215
216
217
218
        
        ## Initialize the power_indices object which takes care of kindex,
        ## pindex, rho and the pundex for a given set of parameters
        if self.fourier:        
219
            self.power_indices = power_indices(shape=self.get_shape(),
220
221
222
                                dgrid = dist,
                                zerocentered = self.paradict['zerocenter']
                                )
Marco Selig's avatar
Marco Selig committed
223

224
225
226
227
228
229
230
231
232
233
234
235
236
    @property
    def para(self):
        temp = np.array(self.paradict['num'] + \
                         [self.paradict['complexity']] + \
                         self.paradict['zerocenter'], dtype=int)
        return temp
        
    
    @para.setter
    def para(self, x):
        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
237
238
239

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
## TODO: Remove this dead code block 
## Inherited from point space
#    def apply_scalar_function(self, x, function, inplace=False):
#        return x.apply_scalar_function(function, inplace=inplace)
#
#    
#    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++      
#    def unary_operation(self, x, op='None', **kwargs):
#        """
#        x must be a distributed_data_object which is compatible with the space!
#        Valid operations are
#        
#        """
#        
#        translation = {"pos" : lambda y: getattr(y, '__pos__')(),
#                        "neg" : lambda y: getattr(y, '__neg__')(),
#                        "abs" : lambda y: getattr(y, '__abs__')(),
#                        "nanmin" : lambda y: getattr(y, 'nanmin')(),
#                        "min" : lambda y: getattr(y, 'amin')(),
#                        "nanmax" : lambda y: getattr(y, 'nanmax')(),
#                        "max" : lambda y: getattr(y, 'amax')(),
#                        "median" : lambda y: getattr(y, 'median')(),
#                        "mean" : lambda y: getattr(y, 'mean')(),
#                        "std" : lambda y: getattr(y, 'std')(),
#                        "var" : lambda y: getattr(y, 'var')(),
#                        "argmin" : lambda y: getattr(y, 'argmin')(),
#                        "argmin_flat" : lambda y: getattr(y, 'argmin_flat')(),
#                        "argmax" : lambda y: getattr(y, 'argmax')(),
#                        "argmax_flat" : lambda y: getattr(y, 'argmax_flat')(),
#                        "conjugate" : lambda y: getattr(y, 'conjugate')(),
#                        "sum" : lambda y: getattr(y, 'sum')(),
#                        "prod" : lambda y: getattr(y, 'prod')(),
#                        "None" : lambda y: y}
#                        
#        return translation[op](x, **kwargs)      
275
276


Marco Selig's avatar
Marco Selig committed
277
    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
278
279
280
281
282
283
284
    def copy(self):
        return rg_space(num = self.paradict['num'],
                        complexity = self.paradict['complexity'],
                        zerocenter = self.paradict['zerocenter'],
                        dist = self.vol,
                        fourier = self.fourier,
                        datamodel = self.datamodel)
Marco Selig's avatar
Marco Selig committed
285

286
287
288
289
290

    def num(self):
        np.prod(self.get_shape())
        
    def get_naxes(self):
Marco Selig's avatar
Marco Selig committed
291
292
293
294
295
296
297
298
        """
            Returns the number of axes of the grid.

            Returns
            -------
            naxes : int
                Number of axes of the regular grid.
        """
299
#        return (np.size(self.para)-1)//2
300
        return len(self.get_shape())
Marco Selig's avatar
Marco Selig committed
301
302
303
304
305
306
307
308
309
310

    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.
        """
311
312
        #return self.para[-(np.size(self.para)-1)//2:][::-1].astype(np.bool)
        return self.paradict['zerocenter']
Marco Selig's avatar
Marco Selig committed
313
314
315
316
317
318
319
320
321
322

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

            Returns
            -------
            dist : np.ndarray
                Distances between two grid points on each axis.
        """
323
324
        return self.vol
 
325
    def get_shape(self):
326
        return np.array(self.paradict['num'])
Marco Selig's avatar
Marco Selig committed
327

328
    def get_dim(self, split=False):
Marco Selig's avatar
Marco Selig committed
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
        """
            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)
345
        if split == True:
346
            return self.get_shape()
Marco Selig's avatar
Marco Selig committed
347
        else:
348
            return np.prod(self.get_shape())
Marco Selig's avatar
Marco Selig committed
349
350
351

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

352
    def get_dof(self):
Marco Selig's avatar
Marco Selig committed
353
354
355
356
357
358
359
360
361
362
363
        """
            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.
        """
        ## dof ~ dim
364
365
        if self.paradict['complexity'] < 2:
            return np.prod(self.paradict['num'])
Marco Selig's avatar
Marco Selig committed
366
        else:
367
368
369
370
371
372
            return 2*np.prod(self.paradict['num'])

#        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:
#            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
373

ultimanet's avatar
ultimanet committed
374

Marco Selig's avatar
Marco Selig committed
375
376
    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

ultimanet's avatar
ultimanet committed
377

378
379
    def enforce_power(self, spec, size=None, kindex=None, codomain=None,
                      log=False, nbin=None, binbounds=None):
Marco Selig's avatar
Marco Selig committed
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
        """
            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*
404
405
406
407
                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).
Marco Selig's avatar
Marco Selig committed
408
            nbin : integer, *optional*
409
410
411
                Number of used spectral bins; if given `log` is set to 
                ``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
412
413
414
            binbounds : {list, array}, *optional*
                User specific inner boundaries of the bins, which are preferred
                over the above parameters; by default no binning is done
415
                (default: None).
Marco Selig's avatar
Marco Selig committed
416
        """
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
        
        
        
        ## 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 == None and (size == None or callable(spec) == True):
            ## Determine which space should be used to get the kindex
            if self.fourier == True:
                kindex_supply_space = self
            else:
                ## Check if the given codomain is compatible with the space  
                try:                
                    assert(self.check_codomain(codomain))
                    kindex_supply_space = codomain
                except(AssertionError):
                    about.warnings.cprint("WARNING: Supplied codomain is "+\
                    "incompatible. Generating a generic codomain. This can "+\
                    "be expensive!")
                    kindex_supply_space = self.get_codomain()
            kindex = kindex_supply_space.\
                        power_indices.get_index_dict(log=log, nbin=nbin,
                                                     binbounds=binbounds)\
                                                     ['kindex']
        
Marco Selig's avatar
Marco Selig committed
442

443
444
445
446
447
448
449
450
        
        ## 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
        if callable(spec) == True:
            ## Try to plug in the kindex array in the function directly            
Marco Selig's avatar
Marco Selig committed
451
            try:
452
                spec = np.array(spec(kindex), dtype=self.datatype)
Marco Selig's avatar
Marco Selig committed
453
            except:
454
455
456
457
458
459
460
461
462
463
464
465
466
467
                ## Second try: Use a vectorized version of the function.
                ## This is slower, but better than nothing
                try:
                    spec = np.vectorize(spec)(kindex)
                except:
                    raise TypeError(about._errors.cstring(
                        "ERROR: invalid power spectra function.")) 
    
        ## Case 2: spec is a field:
        elif isinstance(spec, field):
            spec = spec[:]
            spec = np.array(spec, dtype = self.datatype).flatten()
            
        ## Case 3: spec is a scalar or something else:
Marco Selig's avatar
Marco Selig committed
468
        else:
469
470
471
472
473
474
475
476
477
478
479
480
            spec = np.array(spec, dtype = self.datatype).flatten()
        
            
        ## Make some sanity checks
        ## Drop imaginary part
        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
        
Marco Selig's avatar
Marco Selig committed
481
        ## check finiteness
482
        if not np.all(np.isfinite(spec)):
Marco Selig's avatar
Marco Selig committed
483
            about.warnings.cprint("WARNING: infinite value(s).")
484
        
Marco Selig's avatar
Marco Selig committed
485
        ## check positivity (excluding null)
486
487
488
489
490
491
492
        if np.any(spec<0):
            raise ValueError(about._errors.cstring(
                                "ERROR: nonpositive value(s)."))
        if np.any(spec==0):
            about.warnings.cprint("WARNING: nonpositive value(s).")            
        
        ## Set the size parameter        
Ultimanet's avatar
Ultimanet committed
493
494
        if size == None:
            size = len(kindex)
495
496
497
498
499
500
501
502
503
504
505
506
        
        ## Fix the size of the spectrum
        ## If spec is singlevalued, expand it
        if np.size(spec) == 1:
            spec = spec*np.ones(size, dtype=spec.dtype, order='C')
        ## If the size does not fit at all, throw an exception
        elif np.size(spec) < size:
            raise ValueError(about._errors.cstring("ERROR: size mismatch ( "+\
                             str(np.size(spec))+" < "+str(size)+" )."))
        elif np.size(spec) > size:
            about.warnings.cprint("WARNING: power spectrum cut to size ( == "+\
                                str(size)+" ).")
Marco Selig's avatar
Marco Selig committed
507
            spec = spec[:size]
508
        
Marco Selig's avatar
Marco Selig committed
509
510
        return spec

511

Marco Selig's avatar
Marco Selig committed
512
513
    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Ultimanet's avatar
Ultimanet committed
514
    def set_power_indices(self, log=False, nbin=None, binbounds=None, **kwargs):
Marco Selig's avatar
Marco Selig committed
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
        """
            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
                If ``self.fourier == False``.
            ValueError
                If the binning leaves one or more bins empty.

        """
550
551
552
553
554

        about.warnings.cflush("WARNING: set_power_indices is a deprecated"+\
                                "function. Please use the interface of"+\
                                "self.power_indices in future!")
        self.power_indices.set_default(log=log, nbin=nbin, binbounds=binbounds)
Marco Selig's avatar
Marco Selig committed
555
556
557
        return None

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
558

559
560
    def _cast_to_d2o(self, x, dtype = None, ignore_complexity = False,
                     verbose=False, **kwargs):
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
        """
            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).
        """
583
584
        if dtype is None:
            dtype = self.datatype
585
586
587
588
589
590
591
592
        ## 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
593
            return self.cast(x.val, dtype=dtype)
594
        
595
596
597
        ## Case 2: x is a distributed_data_object
        if isinstance(x, distributed_data_object):
            ## Check the shape
598
            if np.any(x.shape != self.get_shape()):           
599
                ## Check if at least the number of degrees of freedom is equal
600
                if x.get_dim() == self.get_dim():
601
602
603
604
605
                    ## 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()
606
                    temp = np.reshape(temp, self.get_shape())             
607
                    ## ... and cast again
608
                    return self.cast(temp, dtype=dtype)
609
610
611
612
613
614
              
                else:
                    raise ValueError(about._errors.cstring(\
                    "ERROR: Data has incompatible shape!"))
                    
            ## Check the datatype
615
616
617
            if np.dtype(x.dtype) != np.dtype(dtype):
                if np.dtype(x.dtype) > np.dtype(dtype):
                    about.warnings.cflush(\
618
            "WARNING: Datatypes are uneqal/of conflicting precision (own: "\
619
620
621
622
                        + str(dtype) + " <> foreign: " + str(x.dtype) \
                        + ") and will be casted! "\
                        + "Potential loss of precision!\n")
                temp = x.copy_empty(dtype=dtype)
623
624
625
626
                temp.set_local_data(x.get_local_data())
                temp.hermitian = x.hermitian
                x = temp
            
627
628
629
630
631
632
633
634
635
636
            if ignore_complexity == False:
                ## 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
637
                
638
639
640
641
642
643
644
645
646
647
                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)
                    
648
649
650
651
            return x
                
        ## Case 3: x is something else
        ## Use general d2o casting 
652
        x = distributed_data_object(x, global_shape=self.get_shape(),\
653
            dtype=dtype)       
654
        ## Cast the d2o
655
        return self.cast(x, dtype=dtype)
Ultimanet's avatar
Ultimanet committed
656

657
658
    def _cast_to_np(self, x, dtype = None, ignore_complexity = False, 
                    verbose = False, **kwargs):
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
        """
            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).
        """
681
682
        if dtype is None:
            dtype = self.datatype
683
684
685
686
687
688
689
690
        ## 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
691
            return self.cast(x.val, dtype=dtype)
692
693
694
695
696
697
        
        ## 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
698
            return self.cast(temp, dtype=dtype)
699
700
701
702
703
704
705
706
707
        
        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
708
                    return self.cast(temp, dtype=dtype)
709
710
                elif x.size == 1:
                    temp = np.empty(shape = self.get_shape(),
711
                                    dtype = dtype)
712
                    temp[:] = x
713
                    return self.cast(temp, dtype=dtype)
714
715
716
717
718
                else:
                    raise ValueError(about._errors.cstring(\
                    "ERROR: Data has incompatible shape!"))
                    
            ## Check the datatype
719
            if x.dtype != dtype:
720
721
                about.warnings.cflush(\
            "WARNING: Datatypes are uneqal/of conflicting precision (own: "\
722
                + str(dtype) + " <> foreign: " + str(x.dtype) \
723
724
725
                + ") and will be casted! "\
                + "Potential loss of precision!\n")
                ## Fix the datatype...
726
                temp = x.astype(dtype)
727
                ##... and cast again
728
                return self.cast(temp, dtype=dtype)
729
            
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
            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)
748
749
750
751
752
753
                
            return x
                
        ## Case 3: x is something else
        ## Use general numpy casting 
        else:
754
            temp = np.empty(self.get_shape(), dtype = dtype)
755
756
757
            temp[:] = x
            return temp
            
Marco Selig's avatar
Marco Selig committed
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
    def enforce_values(self,x,extend=True):
        """
            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).
        """
779
780
        about.warnings.cflush(\
            "WARNING: enforce_values is deprecated function. Please use self.cast")
Marco Selig's avatar
Marco Selig committed
781
782
783
784
785
786
787
788
789
790
791
        if(isinstance(x,field)):
            if(self==x.domain):
                if(self.datatype is not x.domain.datatype):
                    raise TypeError(about._errors.cstring("ERROR: inequal data types ( '"+str(np.result_type(self.datatype))+"' <> '"+str(np.result_type(x.domain.datatype))+"' )."))
                else:
                    x = np.copy(x.val)
            else:
                raise ValueError(about._errors.cstring("ERROR: inequal domains."))
        else:
            if(np.size(x)==1):
                if(extend):
792
                    x = self.datatype(x)*np.ones(self.get_dim(split=True),dtype=self.datatype,order='C')
Marco Selig's avatar
Marco Selig committed
793
794
795
796
797
798
799
800
801
802
                else:
                    if(np.isscalar(x)):
                        x = np.array([x],dtype=self.datatype)
                    else:
                        x = np.array(x,dtype=self.datatype)
            else:
                x = self.enforce_shape(np.array(x,dtype=self.datatype))

        ## 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
803
804
            #x = gp.nhermitianize_fast(x,self.para[-((np.size(self.para)-1)//2):].astype(np.bool),special=False)
            x = utilities.hermitianize(x)
Marco Selig's avatar
Marco Selig committed
805
806
807
808
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
846
847
848
849
850
        ## check finiteness
        if(not np.all(np.isfinite(x))):
            about.warnings.cprint("WARNING: infinite value(s).")

        return x

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    def get_random_values(self,**kwargs):
        """
            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
851
                A compatible codomain (default: None).
Marco Selig's avatar
Marco Selig committed
852
853
854
855
856
857
858
859
860
861
862
863
864
865
            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"``
Ultimanet's avatar
Ultimanet committed
866
867
                (default: 0).            
            vmin : float, *optional*
Marco Selig's avatar
Marco Selig committed
868
869
870
871
                Lower limit for a uniform distribution (default: 0).
            vmax : float, *optional*
                Upper limit for a uniform distribution (default: 1).
        """
872
873
        ## TODO: Without hermitianization the random-methods from pointspace 
        ## could be used.
Ultimanet's avatar
Ultimanet committed
874
875
        
        ## Parse the keyword arguments
876
        arg = random.parse_arguments(self, **kwargs)
Ultimanet's avatar
Ultimanet committed
877
878
        
        ## Prepare the empty distributed_data_object
879
        sample = distributed_data_object(global_shape=self.get_shape(), 
Ultimanet's avatar
Ultimanet committed
880
881
                                         dtype=self.datatype)

882
883
884
885
886
887
        ## Should the output be hermitianized? This does not depend on the 
        ## hermitianize boolean in about, as it would yield in wrong,
        ## not recoverable results

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

Ultimanet's avatar
Ultimanet committed
889
        ## Case 1: uniform distribution over {-1,+1}/{1,i,-1,-i}
Ultimanet's avatar
Ultimanet committed
890
        if arg[0] == 'pm1' and hermitianizeQ == False:
Ultimanet's avatar
Ultimanet committed
891
892
893
894
            gen = lambda s: random.pm1(datatype=self.datatype,
                                       shape = s)
            sample.apply_generator(gen)
                        
Ultimanet's avatar
Ultimanet committed
895
896
897
898
899
900
901
902
903
904
905
906
907
        elif arg[0] == 'pm1' and hermitianizeQ == True:
            sample = self.get_random_values(random = 'uni', vmin=-1, vmax=1)
            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
                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
            else:
                local_data[local_data >= 0] = 1
                local_data[local_data < 0] = -1
            sample.set_local_data(local_data)
Ultimanet's avatar
Ultimanet committed
908
909
910
911
            
        ## Case 2: normal distribution with zero-mean and a given standard
        ##         deviation or variance
        elif arg[0] == 'gau':
912
913
914
915
916
917
918
919
920
            var = arg[3]            
            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
                    
Ultimanet's avatar
Ultimanet committed
921
922
            gen = lambda s: random.gau(datatype=self.datatype,
                                       shape = s,
Ultimanet's avatar
Ultimanet committed
923
                                       mean = arg[1],
Ultimanet's avatar
Ultimanet committed
924
                                       dev = arg[2],
925
                                       var = processed_var)
Ultimanet's avatar
Ultimanet committed
926
            sample.apply_generator(gen)
Ultimanet's avatar
Ultimanet committed
927
928
929
            
            if hermitianizeQ == True:
                sample = utilities.hermitianize(sample)
Ultimanet's avatar
Ultimanet committed
930

Ultimanet's avatar
Ultimanet committed
931
932
        ## Case 3: uniform distribution
        elif arg[0] == "uni" and hermitianizeQ == False:
Ultimanet's avatar
Ultimanet committed
933
934
935
936
937
            gen = lambda s: random.uni(datatype=self.datatype,
                                       shape = s,
                                       vmin = arg[1],
                                       vmax = arg[2])
            sample.apply_generator(gen)
Ultimanet's avatar
Ultimanet committed
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
            
        elif arg[0] == "uni" and hermitianizeQ == True:
            ## 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.
            if issubclass(sample.dtype, np.complexfloating):
                temp_func = lambda x: erf(x.real) + 1j*erf(x.imag)                  
            else:
                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
            ## sample = (sample + 1)/2 * (vmax-vmin) + vmin
            vmin = arg[1]
            vmax = arg[2]            
            sample *= (vmax-vmin)/2.
            sample += 1/2.*(vmax+vmin)
            
Marco Selig's avatar
Marco Selig committed
959
960

        elif(arg[0]=="syn"):
Ultimanet's avatar
Ultimanet committed
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
            spec = arg[1]
            kpack = arg[2]
            harmonic_domain = arg[3]
            log = arg[4]
            nbin = arg[5]
            binbounds = arg[6]
            ## 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
            if kpack == None:
                power_indices =\
                    harmonic_domain.power_indices.get_index_dict(log = log,
                                                        nbin = nbin,
                                                        binbounds = binbounds)
                
                kindex = power_indices['kindex']
                kdict = power_indices['kdict']
                kpack = [power_indices['pindex'], power_indices['kindex']]
            else:
                kindex = kpack[1]
                kdict = harmonic_domain.power_indices.\
                    __compute_kdict_from_pindex_kindex__(kpack[0], kpack[1])           
                
Marco Selig's avatar
Marco Selig committed
984

Ultimanet's avatar
Ultimanet committed
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
            ## draw the random samples
            ## Case 1: self is a harmonic space
            if self.fourier:
                ## subcase 1: self is real
                ## -> simply generate a random field in fourier space and 
                ## weight the entries accordingly to the powerspectrum
                if self.paradict['complexity'] == 0:
                    ## 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
                    gen = lambda s: np.random.normal(loc=0, scale=1, size=s)
                    ## apply the random number generator                    
                    sample.apply_generator(gen)
Marco Selig's avatar
Marco Selig committed
1000