nifty_rg.py 75.3 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
35
36
37
38
39
40

"""
from __future__ import division
#from nifty import *
import os
import numpy as np
import pylab as pl
from matplotlib.colors import LogNorm as ln
from matplotlib.ticker import LogFormatter as lf
Ultimanet's avatar
Ultimanet committed
41
42
43

from nifty.nifty_about import about
from nifty.nifty_core import point_space,                                    \
Marco Selig's avatar
Marco Selig committed
44
                             field
Ultimanet's avatar
Ultimanet committed
45
from nifty.nifty_random import random
46
from nifty.nifty_mpi_data import distributed_data_object
Ultimanet's avatar
Ultimanet committed
47
48
from nifty.nifty_paradict import rg_space_paradict

Marco Selig's avatar
Marco Selig committed
49
import nifty.smoothing as gs
50
import powerspectrum as gp
Ultimanet's avatar
Ultimanet committed
51
52
import fft_rg

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


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


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

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

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

161
        complexity = 2-(bool(hermitian) or bool(purelyreal))-bool(purelyreal)
Ultimanet's avatar
Ultimanet committed
162
163
164
        if np.isscalar(num):
            num = (num,)*np.asscalar(np.array(naxes))
            
165
166
167
168
169
        self.paradict = rg_space_paradict(num=num, complexity=complexity, 
                                          zerocenter=zerocenter)        
        
        
        naxes = len(self.paradict['num'])
Marco Selig's avatar
Marco Selig committed
170
171

        ## set data type
Ultimanet's avatar
Ultimanet committed
172
        if  self.paradict['complexity'] == 0:
Marco Selig's avatar
Marco Selig committed
173
174
175
176
177
178
179
180
            self.datatype = np.float64
        else:
            self.datatype = np.complex128

        self.discrete = False

        ## set volume
        if(dist is None):
181
            dist = 1/np.array(self.paradict['num'], dtype=self.datatype)
Marco Selig's avatar
Marco Selig committed
182
        elif(np.isscalar(dist)):
183
184
            dist = self.datatype(dist)*np.ones(naxes,dtype=self.datatype,\
                                                order='C')
Marco Selig's avatar
Marco Selig committed
185
186
        else:
            dist = np.array(dist,dtype=self.datatype)
187
            if(np.size(dist) == 1):
Marco Selig's avatar
Marco Selig committed
188
189
                dist = dist*np.ones(naxes,dtype=self.datatype,order='C')
            if(np.size(dist)!=naxes):
190
191
192
                raise ValueError(about._errors.cstring(\
                    "ERROR: size mismatch ( "+str(np.size(dist))+" <> "+\
                    str(naxes)+" )."))
Marco Selig's avatar
Marco Selig committed
193
        if(np.any(dist<=0)):
194
195
196
            raise ValueError(about._errors.cstring(\
                "ERROR: nonpositive distance(s)."))
        self.vol = np.real(dist)
Marco Selig's avatar
Marco Selig committed
197
198

        self.fourier = bool(fourier)
ultimanet's avatar
ultimanet committed
199
200
        
        ## Initializes the fast-fourier-transform machine, which will be used 
ultimanet's avatar
ultimanet committed
201
        ## to transform the space
ultimanet's avatar
ultimanet committed
202
        self.fft_machine = fft_rg.fft_factory()
203
204
205
206
207
208
209
210
        
        ## Initialize the power_indices object which takes care of kindex,
        ## pindex, rho and the pundex for a given set of parameters
        if self.fourier:        
            self.power_indices = gp.power_indices(shape=self.shape(),
                                dgrid = dist,
                                zerocentered = self.paradict['zerocenter']
                                )
Marco Selig's avatar
Marco Selig committed
211

212
213
214
215
216
217
218
219
220
221
222
223
224
    @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
225
226
227
228
229
230
231

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

    def apply_scalar_function(self, x, function, inplace=False):
        return x.apply_scalar_function(function, inplace=inplace)

    
232
233
234
235
236
237
238
    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++      
    def unary_operation(self, x, op='None', **kwargs):
        """
        x must be a distributed_data_object which is compatible with the space!
        Valid operations are
        
        """
ultimanet's avatar
ultimanet committed
239
        
240
241
242
243
244
245
246
        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')(),
Ultimanet's avatar
Ultimanet committed
247
                        "median" : lambda y: getattr(y, 'median')(),
248
249
250
251
252
253
254
255
256
257
258
259
260
                        "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')(),
                        "None" : lambda y: y}
                        
        return translation[op](x, **kwargs)      


Marco Selig's avatar
Marco Selig committed
261
262
263
264
265
266
267
268
269
270
271
    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    def naxes(self):
        """
            Returns the number of axes of the grid.

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

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

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

            Returns
            -------
            dist : np.ndarray
                Distances between two grid points on each axis.
        """
296
297
298
299
        return self.vol
 
    def shape(self):
        return np.array(self.paradict['num'])
Marco Selig's avatar
Marco Selig committed
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317

    def dim(self,split=False):
        """
            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)
318
319
        if split == True:
            return self.shape()
Marco Selig's avatar
Marco Selig committed
320
        else:
321
            return np.prod(self.shape())
Marco Selig's avatar
Marco Selig committed
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336

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

    def dof(self):
        """
            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
337
338
        if self.paradict['complexity'] < 2:
            return np.prod(self.paradict['num'])
Marco Selig's avatar
Marco Selig committed
339
        else:
340
341
342
343
344
345
            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
346

ultimanet's avatar
ultimanet committed
347

Marco Selig's avatar
Marco Selig committed
348
349
    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

ultimanet's avatar
ultimanet committed
350

351
352
    def enforce_power(self, spec, size=None, kindex=None, codomain=None,
                      log=False, nbin=None, binbounds=None):
Marco Selig's avatar
Marco Selig committed
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
        """
            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*
377
378
379
380
                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
381
            nbin : integer, *optional*
382
383
384
                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
385
386
387
            binbounds : {list, array}, *optional*
                User specific inner boundaries of the bins, which are preferred
                over the above parameters; by default no binning is done
388
                (default: None).
Marco Selig's avatar
Marco Selig committed
389
        """
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
        
        
        
        ## 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
415

416
417
418
419
420
421
422
423
        
        ## 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
424
            try:
425
                spec = np.array(spec(kindex), dtype=self.datatype)
Marco Selig's avatar
Marco Selig committed
426
            except:
427
428
429
430
431
432
433
434
435
436
437
438
439
440
                ## 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
441
        else:
442
443
444
445
446
447
448
449
450
451
452
453
            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
454
        ## check finiteness
455
        if not np.all(np.isfinite(spec)):
Marco Selig's avatar
Marco Selig committed
456
            about.warnings.cprint("WARNING: infinite value(s).")
457
        
Marco Selig's avatar
Marco Selig committed
458
        ## check positivity (excluding null)
459
460
461
462
463
464
465
        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
466
467
        if size == None:
            size = len(kindex)
468
469
470
471
472
473
474
475
476
477
478
479
        
        ## 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
480
            spec = spec[:size]
481
        
Marco Selig's avatar
Marco Selig committed
482
483
        return spec

484

Marco Selig's avatar
Marco Selig committed
485
486
    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Ultimanet's avatar
Ultimanet committed
487
    def set_power_indices(self, log=False, nbin=None, binbounds=None, **kwargs):
Marco Selig's avatar
Marco Selig committed
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
        """
            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.

        """
523
524
525
526
527

        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
528
529
530
        return None

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

    def cast(self, x, verbose=False):
        """
            Computes valid field values from a given object, trying
            to translate the given data into a valid form. Thereby it is as 
            benevolent as possible. 

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

            Returns
            -------
            x : numpy.ndarray, distributed_data_object
                Array containing the field values, which are compatible to the
                space.

            Other parameters
            ----------------
            verbose : bool, *optional*
                Whether the method should raise a warning if information is 
                lost during casting (default: False).
        """
        ## 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)
564
        
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
        ## Case 2: x is a distributed_data_object
        if isinstance(x, distributed_data_object):
            ## Check the shape
            if np.any(x.shape != self.shape()):           
                ## Check if at least the number of degrees of freedom is equal
                if x.dim() == self.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.shape())             
                    ## ... and cast again
                    return self.cast(temp)
              
                else:
                    raise ValueError(about._errors.cstring(\
                    "ERROR: Data has incompatible shape!"))
                    
            ## Check the datatype
            if x.dtype != self.datatype:
                about.warnings.cflush(\
Ultimanet's avatar
Ultimanet committed
587
588
589
590
                "WARNING: Datatypes are uneqal (own: "\
                + str(self.datatype) + " <> foreign: " + str(x.dtype) \
                + ") and will be casted! "\
                + "Potential loss of precision!\n")
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
                temp = x.copy_empty(dtype=self.datatype)
                temp.set_local_data(x.get_local_data())
                temp.hermitian = x.hermitian
                x = temp
            
            ## Check hermitianity/reality
            if self.paradict['complexity'] == 0:
                if x.is_completely_real == False:
                    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:
                    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 = temp
                
            return x
                
        ## Case 3: x is something else
        ## Use general d2o casting 
        x = distributed_data_object(x, global_shape=self.shape(),\
Ultimanet's avatar
Ultimanet committed
621
            dtype=self.datatype)       
622
623
        ## Cast the d2o
        return self.cast(x)
Ultimanet's avatar
Ultimanet committed
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

    def _hermitianize_inverter(self, x):
        ## calculate the number of dimensions the input array has
        dimensions = len(x.shape)
        ## prepare the slicing object which will be used for mirroring
        slice_primitive = [slice(None),]*dimensions
        ## copy the input data
        y = x.copy()
        ## flip in every direction
        for i in xrange(dimensions):
            slice_picker = slice_primitive[:]
            slice_picker[i] = slice(1, None)
            slice_inverter = slice_primitive[:]
            slice_inverter[i] = slice(None, None, -1)
            y[slice_picker] = y[slice_picker][slice_inverter]
        return y
    """
    def hermitianize(self, x, random=None):
        if random == None:
            ## perform the hermitianize flips
            y = self._hermitianize_inverter(x)
            ## make pointwise conjugation             
            y = np.conjugate(y)
            ## and return the pointwise mean
            return self.cast((x+y)/2.)
        
        elif random == 'uni':
            return self.hermitianize(x, random=None)
        
        elif random == 'gau':
            y = self._hermitianize_inverter(x)
            y = np.conjugate(y)
656
            
Ultimanet's avatar
Ultimanet committed
657
658
    """ 
    
Marco Selig's avatar
Marco Selig committed
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
    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).
        """
680
681
        about.warnings.cflush(\
            "WARNING: enforce_values is deprecated function. Please use self.cast")
Marco Selig's avatar
Marco Selig committed
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
749
750
751
        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):
                    x = self.datatype(x)*np.ones(self.dim(split=True),dtype=self.datatype,order='C')
                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):
            x = gp.nhermitianize_fast(x,self.para[-((np.size(self.para)-1)//2):].astype(np.bool),special=False)

        ## 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
752
                A compatible codomain (default: None).
Marco Selig's avatar
Marco Selig committed
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
            log : bool, *optional*
                Flag specifying if the spectral binning is performed on logarithmic
                scale or not; if set, the number of used bins is set
                automatically (if not given otherwise); by default no binning
                is done (default: None).
            nbin : integer, *optional*
                Number of used spectral bins; if given `log` is set to ``False``;
                integers below the minimum of 3 induce an automatic setting;
                by default no binning is done (default: None).
            binbounds : {list, array}, *optional*
                User specific inner boundaries of the bins, which are preferred
                over the above parameters; by default no binning is done
                (default: None).            vmin : {scalar, list, ndarray, field}, *optional*
                Lower limit of the uniform distribution if ``random == "uni"``
                (default: 0).            vmin : float, *optional*
                Lower limit for a uniform distribution (default: 0).
            vmax : float, *optional*
                Upper limit for a uniform distribution (default: 1).
        """
Ultimanet's avatar
Ultimanet committed
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
        
        ## Parse the keyword arguments
        arg = random.parse_arguments(self,**kwargs)
        
        ## Prepare the empty distributed_data_object
        sample = distributed_data_object(global_shape=self.shape(), 
                                         dtype=self.datatype)

        ## Case 1: uniform distribution over {-1,+1}/{1,i,-1,-i}
        if arg[0] == 'pm1':
            gen = lambda s: random.pm1(datatype=self.datatype,
                                       shape = s)
            sample.apply_generator(gen)
                        
            
        ## Case 2: normal distribution with zero-mean and a given standard
        ##         deviation or variance
        elif arg[0] == 'gau':
            gen = lambda s: random.gau(datatype=self.datatype,
                                       shape = s,
                                       mean = None,
                                       dev = arg[2],
                                       var = arg[3])
            sample.apply_generator(gen)

        elif arg[0] == "uni":
            gen = lambda s: random.uni(datatype=self.datatype,
                                       shape = s,
                                       vmin = arg[1],
                                       vmax = arg[2])
            sample.apply_generator(gen)
Marco Selig's avatar
Marco Selig committed
803
804

        elif(arg[0]=="syn"):
Ultimanet's avatar
Ultimanet committed
805
            """
Marco Selig's avatar
Marco Selig committed
806
807
808
809
810
            naxes = (np.size(self.para)-1)//2
            x = gp.draw_vector_nd(self.para[:naxes],self.vol,arg[1],symtype=self.para[naxes],fourier=self.fourier,zerocentered=self.para[-naxes:].astype(np.bool),kpack=arg[2])
            ## correct for 'ifft'
            if(not self.fourier):
                x = self.calc_weight(x,power=-1)
Ultimanet's avatar
Ultimanet committed
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
            """
            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
835

Ultimanet's avatar
Ultimanet committed
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
            ## 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
851

Ultimanet's avatar
Ultimanet committed
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
                
                ## 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.
                elif self.paradict['complexity'] == 1:
                    temp_codomain = self.get_codomain()
                    ## 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 = temp_codomain.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)
                    ## tronsform the random field to harmonic space
                    sample = self.get_codomain().\
                                        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)
Marco Selig's avatar
Marco Selig committed
876

Ultimanet's avatar
Ultimanet committed
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
                    
                ## subcase 3: self is fully complex
                ## -> generate a complex random field in harmonic space and
                ## weight the modes accordingly to the powerspectrum
                elif self.paradict['complexity'] == 2:
                    ## 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/np.sqrt(2), size=s)+
                        np.random.normal(loc=0, scale=1/np.sqrt(2), size=s)*1.j
                        )
                    ## apply the random number generator                    
                    sample.apply_generator(gen)
                
                ## apply the powerspectrum renormalization
                ## therefore extract the local data from kdict
                local_kdict = kdict.get_local_data()
                rescaler = np.sqrt(
                            spec[np.searchsorted(kindex,local_kdict)])
                sample.apply_scalar_function(lambda x: x*rescaler, 
                                             inplace=True)
            ## Case 2: self is a position space
            else:
                ## get a suitable codomain
                temp_codomain = self.get_codomain()                   

                ## subcase 1: self is a real space. 
                ## -> generate a hermitian sample with the codomain in harmonic
                ## space and make a fourier transformation.
                if self.paradict['complexity'] == 0:
                    ## check that the codomain is hermitian
                    assert(temp_codomain.paradict['complexity'] == 1)
                                                          
                ## subcase 2: self is hermitian but probably complex
                ## -> generate a real-valued random sample in fourier space
                ## and transform it to real space
                elif self.paradict['complexity'] == 1:
                    ## check that the codomain is real
                    assert(temp_codomain.paradict['complexity'] == 0)            
                
                ## 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)            


                ## Get a hermitian/real/complex sample in harmonic space from 
                ## the codomain
                sample = temp_codomain.get_random_values(
                                                    random='syn',
                                                    pindex = kpack[0],
                                                    kindex = kpack[1],
                                                    spec = spec,
                                                    codomain = self,
                                                    log = log,
                                                    nbin = nbin,
                                                    binbounds = binbounds
                                                    )
                ## Take the fourier transform
                sample = temp_codomain.calc_transform(sample, 
                                                      codomain=self)

            if self.paradict['complexity'] == 1:
               sample.hermitian = True
           
        else:
            raise KeyError(about._errors.cstring(
                        "ERROR: unsupported random key '"+str(arg[0])+"'."))
     
       
Marco Selig's avatar
Marco Selig committed
952
        ## hermitianize if ...
Ultimanet's avatar
Ultimanet committed
953
954
955
956
957
958
959
960
#        if(about.hermitianize.status)and(self.para[(np.size(self.para)-1)//2]==1):
#            x = gp.nhermitianize_fast(x,self.para[-((np.size(self.para)-1)//2):].astype(np.bool),special=(arg[0] in ["gau","pm1"]))

        #sample = self.cast(sample)       
        return sample



Marco Selig's avatar
Marco Selig committed
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978


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

    def check_codomain(self,codomain):
        """
            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.
        """
979
980
981
        if codomain == None:
            return False
            
Ultimanet's avatar
Ultimanet committed
982
        if(not isinstance(codomain,rg_space)):
Marco Selig's avatar
Marco Selig committed
983
984
            raise TypeError(about._errors.cstring("ERROR: invalid input."))

Ultimanet's avatar
Ultimanet committed
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
        ## check number of number and size of axes 
        if not np.all(self.paradict['num'] == codomain.paradict['num']):
            return False
            
        ## check fourier flag
        if self.fourier == codomain.fourier:
            return False
            
        ## check complexity-type
        ## prepare the shorthands
        dcomp = self.paradict['complexity']
        cocomp = codomain.paradict['complexity']
        
        ## Case 1: if the domain is copmleteley complex 
        ## -> the codomain must be complex, too
        if dcomp == 2: