field.py 43.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# 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/>.
Theo Steininger's avatar
Theo Steininger committed
13
14
15
16
17
#
# Copyright(C) 2013-2017 Max-Planck-Society
#
# NIFTy is being developed at the Max-Planck-Institut fuer Astrophysik
# and financially supported by the Studienstiftung des deutschen Volkes.
18

csongor's avatar
csongor committed
19
from __future__ import division
Martin Reinecke's avatar
Martin Reinecke committed
20
21
from builtins import zip
from builtins import range
22

23
import ast
csongor's avatar
csongor committed
24
25
import numpy as np

Theo Steininger's avatar
Theo Steininger committed
26
27
from keepers import Versionable,\
                    Loggable
Jait Dixit's avatar
Jait Dixit committed
28

Martin Reinecke's avatar
Martin Reinecke committed
29
from .domain_object import DomainObject
30

Martin Reinecke's avatar
Martin Reinecke committed
31
from .spaces.power_space import PowerSpace
csongor's avatar
csongor committed
32

Martin Reinecke's avatar
Martin Reinecke committed
33
34
from . import nifty_utilities as utilities
from .random import Random
Martin Reinecke's avatar
Martin Reinecke committed
35
from functools import reduce
36

csongor's avatar
csongor committed
37

Jait Dixit's avatar
Jait Dixit committed
38
class Field(Loggable, Versionable, object):
Theo Steininger's avatar
Theo Steininger committed
39
40
41
    """ The discrete representation of a continuous field over multiple spaces.

    In NIFTY, Fields are used to store data arrays and carry all the needed
42
    metainformation (i.e. the domain) for operators to be able to work on them.
Theo Steininger's avatar
Theo Steininger committed
43
44
    In addition Field has methods to work with power-spectra.

45
46
47
48
    Parameters
    ----------
    domain : DomainObject
        One of the space types NIFTY supports. RGSpace, GLSpace, HPSpace,
Theo Steininger's avatar
Theo Steininger committed
49
        LMSpace or PowerSpace. It might also be a FieldArray, which is
50
        an unstructured domain.
Theo Steininger's avatar
Theo Steininger committed
51

Martin Reinecke's avatar
stage1    
Martin Reinecke committed
52
    val : scalar, numpy.ndarray, Field
53
54
55
        The values the array should contain after init. A scalar input will
        fill the whole array with this scalar. If an array is provided the
        array's dimensions must match the domain's.
Theo Steininger's avatar
Theo Steininger committed
56

57
58
    dtype : type
        A numpy.type. Most common are int, float and complex.
Theo Steininger's avatar
Theo Steininger committed
59

60
61
62
63
    copy: boolean

    Attributes
    ----------
Martin Reinecke's avatar
stage1    
Martin Reinecke committed
64
    val : numpy.ndarray
Theo Steininger's avatar
Theo Steininger committed
65

66
67
68
69
70
71
    domain : DomainObject
        See Parameters.
    domain_axes : tuple of tuples
        Enumerates the axes of the Field
    dtype : type
        Contains the datatype stored in the Field.
Theo Steininger's avatar
Theo Steininger committed
72

73
74
75
76
77
78
79
    Raise
    -----
    TypeError
        Raised if
            *the given domain contains something that is not a DomainObject
             instance
            *val is an array that has a different dimension than the domain
Theo Steininger's avatar
Theo Steininger committed
80

81
    """
82

Theo Steininger's avatar
Theo Steininger committed
83
    # ---Initialization methods---
84

Martin Reinecke's avatar
stage1    
Martin Reinecke committed
85
    def __init__(self, domain=None, val=None, dtype=None, copy=False):
86
        self.domain = self._parse_domain(domain=domain, val=val)
87
        self.domain_axes = self._get_axes_tuple(self.domain)
csongor's avatar
csongor committed
88

Theo Steininger's avatar
Theo Steininger committed
89
        self.dtype = self._infer_dtype(dtype=dtype,
90
                                       val=val)
91

92
93
94
95
        if val is None:
            self._val = None
        else:
            self.set_val(new_val=val, copy=copy)
csongor's avatar
csongor committed
96

97
    def _parse_domain(self, domain, val=None):
98
        if domain is None:
99
100
101
102
            if isinstance(val, Field):
                domain = val.domain
            else:
                domain = ()
103
        elif isinstance(domain, DomainObject):
104
            domain = (domain,)
105
106
107
        elif not isinstance(domain, tuple):
            domain = tuple(domain)

csongor's avatar
csongor committed
108
        for d in domain:
109
            if not isinstance(d, DomainObject):
110
111
                raise TypeError(
                    "Given domain contains something that is not a "
112
                    "DomainObject instance.")
csongor's avatar
csongor committed
113
114
        return domain

Theo Steininger's avatar
Theo Steininger committed
115
116
117
118
119
120
121
122
123
124
    def _get_axes_tuple(self, things_with_shape, start=0):
        i = start
        axes_list = []
        for thing in things_with_shape:
            l = []
            for j in range(len(thing.shape)):
                l += [i]
                i += 1
            axes_list += [tuple(l)]
        return tuple(axes_list)
125

126
    def _infer_dtype(self, dtype, val):
csongor's avatar
csongor committed
127
        if dtype is None:
128
            try:
129
                dtype = val.dtype
130
            except AttributeError:
Theo Steininger's avatar
Theo Steininger committed
131
132
133
                try:
                    if val is None:
                        raise TypeError
134
                    dtype = np.result_type(val)
Theo Steininger's avatar
Theo Steininger committed
135
                except(TypeError):
Martin Reinecke's avatar
more    
Martin Reinecke committed
136
                    dtype = np.dtype(np.float64)
Theo Steininger's avatar
Theo Steininger committed
137
        else:
138
            dtype = np.dtype(dtype)
139

140
141
        dtype = np.result_type(dtype, np.float)

Theo Steininger's avatar
Theo Steininger committed
142
        return dtype
143

144
    # ---Factory methods---
145

146
    @classmethod
Martin Reinecke's avatar
stage1    
Martin Reinecke committed
147
    def from_random(cls, random_type, domain=None, dtype=None, **kwargs):
148
149
150
151
152
        """ Draws a random field with the given parameters.

        Parameters
        ----------
        cls : class
Theo Steininger's avatar
Theo Steininger committed
153

154
155
156
        random_type : String
            'pm1', 'normal', 'uniform' are the supported arguments for this
            method.
Theo Steininger's avatar
Theo Steininger committed
157

158
159
        domain : DomainObject
            The domain of the output random field
Theo Steininger's avatar
Theo Steininger committed
160

161
162
        dtype : type
            The datatype of the output random field
Theo Steininger's avatar
Theo Steininger committed
163

164
165
166
167
168
169
170
        Returns
        -------
        out : Field
            The output object.

        See Also
        --------
171
        power_synthesize
Theo Steininger's avatar
Theo Steininger committed
172

173
174

        """
Theo Steininger's avatar
Theo Steininger committed
175

176
        # create a initially empty field
Martin Reinecke's avatar
stage1    
Martin Reinecke committed
177
        f = cls(domain=domain, dtype=dtype)
178
179
180
181
182
183
184

        # now use the processed input in terms of f in order to parse the
        # random arguments
        random_arguments = cls._parse_random_arguments(random_type=random_type,
                                                       f=f,
                                                       **kwargs)

Martin Reinecke's avatar
stage1    
Martin Reinecke committed
185
        # extract the data from f and apply the appropriate
186
187
188
        # random number generator to it
        sample = f.get_val(copy=False)
        generator_function = getattr(Random, random_type)
189

Martin Reinecke's avatar
stage1    
Martin Reinecke committed
190
191
192
        sample[:]=generator_function(dtype=f.dtype,
                                             shape=sample.shape,
                                             **random_arguments)
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
        return f

    @staticmethod
    def _parse_random_arguments(random_type, f, **kwargs):
        if random_type == "pm1":
            random_arguments = {}

        elif random_type == "normal":
            mean = kwargs.get('mean', 0)
            std = kwargs.get('std', 1)
            random_arguments = {'mean': mean,
                                'std': std}

        elif random_type == "uniform":
            low = kwargs.get('low', 0)
            high = kwargs.get('high', 1)
            random_arguments = {'low': low,
                                'high': high}

csongor's avatar
csongor committed
212
        else:
213
214
            raise KeyError(
                "unsupported random key '" + str(random_type) + "'.")
csongor's avatar
csongor committed
215

216
        return random_arguments
csongor's avatar
csongor committed
217

218
219
    # ---Powerspectral methods---

Martin Reinecke's avatar
Martin Reinecke committed
220
    def power_analyze(self, spaces=None, logarithmic=None, nbin=None,
221
                      binbounds=None, keep_phase_information=False):
Theo Steininger's avatar
Theo Steininger committed
222
        """ Computes the square root power spectrum for a subspace of `self`.
Theo Steininger's avatar
Theo Steininger committed
223

Theo Steininger's avatar
Theo Steininger committed
224
225
226
        Creates a PowerSpace for the space addressed by `spaces` with the given
        binning and computes the power spectrum as a Field over this
        PowerSpace. This can only be done if the subspace to  be analyzed is a
227
        harmonic space. The resulting field has the same units as the initial
Theo Steininger's avatar
Theo Steininger committed
228
        field, corresponding to the square root of the power spectrum.
229
230
231

        Parameters
        ----------
Theo Steininger's avatar
Theo Steininger committed
232
233
234
235
236
        spaces : int *optional*
            The subspace for which the powerspectrum shall be computed
            (default : None).
        logarithmic : boolean *optional*
            True if the output PowerSpace should use logarithmic binning.
Martin Reinecke's avatar
Martin Reinecke committed
237
            {default : None}
Theo Steininger's avatar
Theo Steininger committed
238
239
240
241
242
243
        nbin : int *optional*
            The number of bins the resulting PowerSpace shall have
            (default : None).
            if nbin==None : maximum number of bins is used
        binbounds : array-like *optional*
            Inner bounds of the bins (default : None).
Martin Reinecke's avatar
Martin Reinecke committed
244
245
            Overrides nbin and logarithmic.
            if binbounds==None : bins are inferred.
246
247
248
249
250
251
252
253
254
255
        keep_phase_information : boolean, *optional*
            If False, return a real-valued result containing the power spectrum
            of the input Field.
            If True, return a complex-valued result whose real component
            contains the power spectrum computed from the real part of the
            input Field, and whose imaginary component contains the power
            spectrum computed from the imaginary part of the input Field.
            The absolute value of this result should be identical to the output
            of power_analyze with keep_phase_information=False.
            (default : False).
Theo Steininger's avatar
Theo Steininger committed
256

257
258
259
260
        Raise
        -----
        ValueError
            Raised if
Theo Steininger's avatar
Theo Steininger committed
261
262
                *len(domain) is != 1 when spaces==None
                *len(spaces) is != 1 if not None
263
                *the analyzed space is not harmonic
Theo Steininger's avatar
Theo Steininger committed
264

265
266
        Returns
        -------
Theo Steininger's avatar
Theo Steininger committed
267
        out : Field
Martin Reinecke's avatar
Martin Reinecke committed
268
            The output object. Its domain is a PowerSpace and it contains
269
270
271
272
273
            the power spectrum of 'self's field.

        See Also
        --------
        power_synthesize, PowerSpace
Theo Steininger's avatar
Theo Steininger committed
274

275
        """
Theo Steininger's avatar
Theo Steininger committed
276

Theo Steininger's avatar
Theo Steininger committed
277
        # check if all spaces in `self.domain` are either harmonic or
278
279
280
        # power_space instances
        for sp in self.domain:
            if not sp.harmonic and not isinstance(sp, PowerSpace):
Theo Steininger's avatar
Theo Steininger committed
281
                self.logger.info(
282
                    "Field has a space in `domain` which is neither "
283
284
285
                    "harmonic nor a PowerSpace.")

        # check if the `spaces` input is valid
286
287
        spaces = utilities.cast_axis_to_tuple(spaces, len(self.domain))
        if spaces is None:
Martin Reinecke's avatar
Martin Reinecke committed
288
            spaces = list(range(len(self.domain)))
289
290

        if len(spaces) == 0:
291
292
            raise ValueError(
                "No space for analysis specified.")
293

294
295
296
297
298
299
300
301
302
303
304
305
306
        if keep_phase_information:
            parts_val = self._hermitian_decomposition(
                                              domain=self.domain,
                                              val=self.val,
                                              spaces=spaces,
                                              domain_axes=self.domain_axes,
                                              preserve_gaussian_variance=False)
            parts = [self.copy_empty().set_val(part_val, copy=False)
                     for part_val in parts_val]
        else:
            parts = [self]

        parts = [abs(part)**2 for part in parts]
307
308

        for space_index in spaces:
309
310
            parts = [self._single_power_analyze(
                                work_field=part,
311
312
313
                                space_index=space_index,
                                logarithmic=logarithmic,
                                nbin=nbin,
314
315
                                binbounds=binbounds)
                     for part in parts]
316

317
318
319
320
321
322
        if keep_phase_information:
            result_field = parts[0] + 1j*parts[1]
        else:
            result_field = parts[0]

        return result_field
323
324
325

    @classmethod
    def _single_power_analyze(cls, work_field, space_index, logarithmic, nbin,
326
                              binbounds):
327

328
        if not work_field.domain[space_index].harmonic:
329
330
            raise ValueError(
                "The analyzed space must be harmonic.")
331

332
333
334
335
336
337
        # Create the target PowerSpace instance:
        # If the associated signal-space field was real, we extract the
        # hermitian and anti-hermitian parts of `self` and put them
        # into the real and imaginary parts of the power spectrum.
        # If it was complex, all the power is put into a real power spectrum.

338
        harmonic_domain = work_field.domain[space_index]
339
        power_domain = PowerSpace(harmonic_partner=harmonic_domain,
Theo Steininger's avatar
Theo Steininger committed
340
341
                                  logarithmic=logarithmic, nbin=nbin,
                                  binbounds=binbounds)
342
343
        power_spectrum = cls._calculate_power_spectrum(
                                field_val=work_field.val,
Martin Reinecke's avatar
Martin Reinecke committed
344
                                pdomain=power_domain,
345
                                axes=work_field.domain_axes[space_index])
346
347

        # create the result field and put power_spectrum into it
348
        result_domain = list(work_field.domain)
349
        result_domain[space_index] = power_domain
350
        result_dtype = power_spectrum.dtype
351

352
        result_field = work_field.copy_empty(
353
                   domain=result_domain,
Martin Reinecke's avatar
stage1    
Martin Reinecke committed
354
                   dtype=result_dtype)
355
356
357
358
        result_field.set_val(new_val=power_spectrum, copy=False)

        return result_field

359
    @classmethod
Martin Reinecke's avatar
Martin Reinecke committed
360
    def _calculate_power_spectrum(cls, field_val, pdomain, axes=None):
361

Martin Reinecke's avatar
Martin Reinecke committed
362
363
364
        pindex = pdomain.pindex
        # MR FIXME: how about iterating over slices, instead of replicating
        # pindex? Would save memory and probably isn't slower.
365
        if axes is not None:
366
367
368
369
            pindex = cls._shape_up_pindex(
                            pindex=pindex,
                            target_shape=field_val.shape,
                            axes=axes)
Theo Steininger's avatar
Theo Steininger committed
370

Martin Reinecke's avatar
Martin Reinecke committed
371
        power_spectrum = utilities.bincount_axis(pindex, weights=field_val,
372
                                         axis=axes)
Martin Reinecke's avatar
Martin Reinecke committed
373
        rho = pdomain.rho
374
375
376
377
378
379
380
381
        if axes is not None:
            new_rho_shape = [1, ] * len(power_spectrum.shape)
            new_rho_shape[axes[0]] = len(rho)
            rho = rho.reshape(new_rho_shape)
        power_spectrum /= rho

        return power_spectrum

382
    @staticmethod
Martin Reinecke's avatar
Martin Reinecke committed
383
    def _shape_up_pindex(pindex, target_shape, axes):
Theo Steininger's avatar
Theo Steininger committed
384
        semiscaled_local_shape = [1, ] * len(target_shape)
Theo Steininger's avatar
Theo Steininger committed
385
        for i in range(len(axes)):
Martin Reinecke's avatar
Martin Reinecke committed
386
387
            semiscaled_local_shape[axes[i]] = pindex.shape[i]
        local_data = pindex
Theo Steininger's avatar
Theo Steininger committed
388
        semiscaled_local_data = local_data.reshape(semiscaled_local_shape)
Martin Reinecke's avatar
Martin Reinecke committed
389
390
        result_obj = np.empty(target_shape, dtype=pindex.dtype)
        result_obj[:] = semiscaled_local_data
391
392
393

        return result_obj

394
    def power_synthesize(self, spaces=None, real_power=True, real_signal=True,
Martin Reinecke's avatar
stage1    
Martin Reinecke committed
395
                         mean=None, std=None):
Theo Steininger's avatar
Theo Steininger committed
396
        """ Yields a sampled field with `self`**2 as its power spectrum.
Theo Steininger's avatar
Theo Steininger committed
397

Theo Steininger's avatar
Theo Steininger committed
398
        This method draws a Gaussian random field in the harmonic partner
Martin Reinecke's avatar
typos    
Martin Reinecke committed
399
        domain of this field's domains, using this field as power spectrum.
Theo Steininger's avatar
Theo Steininger committed
400

401
402
403
        Parameters
        ----------
        spaces : {tuple, int, None} *optional*
Theo Steininger's avatar
Theo Steininger committed
404
405
406
            Specifies the subspace containing all the PowerSpaces which
            should be converted (default : None).
            if spaces==None : Tries to convert the whole domain.
407
        real_power : boolean *optional*
Theo Steininger's avatar
Theo Steininger committed
408
409
            Determines whether the power spectrum is treated as intrinsically
            real or complex (default : True).
410
        real_signal : boolean *optional*
Theo Steininger's avatar
Theo Steininger committed
411
412
413
414
415
416
            True will result in a purely real signal-space field
            (default : True).
        mean : float *optional*
            The mean of the Gaussian noise field which is used for the Field
            synthetization (default : None).
            if mean==None : mean will be set to 0
417
        std : float *optional*
Theo Steininger's avatar
Theo Steininger committed
418
419
420
            The standard deviation of the Gaussian noise field which is used
            for the Field synthetization (default : None).
            if std==None : std will be set to 1
Theo Steininger's avatar
Theo Steininger committed
421

422
423
424
425
        Returns
        -------
        out : Field
            The output object. A random field created with the power spectrum
Theo Steininger's avatar
Theo Steininger committed
426
            stored in the `spaces` in `self`.
427

Theo Steininger's avatar
Theo Steininger committed
428
429
430
431
432
433
        Notes
        -----
        For this the spaces specified by `spaces` must be a PowerSpace.
        This expects this field to be the square root of a power spectrum, i.e.
        to have the unit of the field to be sampled.

434
435
436
        See Also
        --------
        power_analyze
Theo Steininger's avatar
Theo Steininger committed
437
438
439
440
441

        Raises
        ------
        ValueError : If domain specified by `spaces` is not a PowerSpace.

442
        """
Theo Steininger's avatar
Theo Steininger committed
443

444
445
446
        # check if the `spaces` input is valid
        spaces = utilities.cast_axis_to_tuple(spaces, len(self.domain))

Theo Steininger's avatar
Theo Steininger committed
447
        if spaces is None:
Martin Reinecke's avatar
Martin Reinecke committed
448
            spaces = list(range(len(self.domain)))
Theo Steininger's avatar
Theo Steininger committed
449

450
451
452
453
454
        for power_space_index in spaces:
            power_space = self.domain[power_space_index]
            if not isinstance(power_space, PowerSpace):
                raise ValueError("A PowerSpace is needed for field "
                                 "synthetization.")
455
456
457

        # create the result domain
        result_domain = list(self.domain)
458
459
        for power_space_index in spaces:
            power_space = self.domain[power_space_index]
460
            harmonic_domain = power_space.harmonic_partner
461
            result_domain[power_space_index] = harmonic_domain
462
463
464

        # create random samples: one or two, depending on whether the
        # power spectrum is real or complex
465
        if real_power:
466
            result_list = [None]
467
468
        else:
            result_list = [None, None]
469

470
471
        result_list = [self.__class__.from_random(
                             'normal',
472
473
474
                             mean=mean,
                             std=std,
                             domain=result_domain,
Martin Reinecke's avatar
stage1    
Martin Reinecke committed
475
                             dtype=np.complex)
476
477
478
479
480
481
                       for x in result_list]

        # from now on extract the values from the random fields for further
        # processing without killing the fields.
        # if the signal-space field should be real, hermitianize the field
        # components
482

Martin Reinecke's avatar
stage1    
Martin Reinecke committed
483
        spec = self.val.copy()
484
485
        spec = np.sqrt(spec)

486
487
488
489
490
491
492
        for power_space_index in spaces:
            spec = self._spec_to_rescaler(spec, result_list, power_space_index)
        local_rescaler = spec

        result_val_list = [x.val for x in result_list]

        # apply the rescaler to the random fields
Martin Reinecke's avatar
Martin Reinecke committed
493
        result_val_list[0] *= local_rescaler.real
494
495

        if not real_power:
Martin Reinecke's avatar
Martin Reinecke committed
496
            result_val_list[1] *= local_rescaler.imag
497

498
        if real_signal:
499
            result_val_list = [self._hermitian_decomposition(
500
501
502
503
504
                                            result_domain,
                                            result_val,
                                            spaces,
                                            result_list[0].domain_axes,
                                            preserve_gaussian_variance=True)[0]
505
                               for result_val in result_val_list]
506
507
508
509
510
511
512

        # store the result into the fields
        [x.set_val(new_val=y, copy=False) for x, y in
            zip(result_list, result_val_list)]

        if real_power:
            result = result_list[0]
513
514
515
            if not issubclass(result_val_list[0].dtype.type,
                              np.complexfloating):
                result = result.real
516
        else:
517
518
519
520
            result = result_list[0] + 1j*result_list[1]

        return result

521
    @staticmethod
522
523
    def _hermitian_decomposition(domain, val, spaces, domain_axes,
                                 preserve_gaussian_variance=False):
524
525
526
527
528
529

        flipped_val = val
        for space in spaces:
            flipped_val = domain[space].hermitianize_inverter(
                                                    x=flipped_val,
                                                    axes=domain_axes[space])
530
531
        # if no flips at all where performed `h` is a real field.
        # if all spaces use the default implementation of doing nothing when
Theo Steininger's avatar
Theo Steininger committed
532
        # no flips are applied, one can use `is` to infer this case.
533
534

        if flipped_val is val:
Martin Reinecke's avatar
Martin Reinecke committed
535
536
            h = flipped_val.real.copy()
            a = 1j * flipped_val.imag.copy()
537
538
539
540
        else:
            flipped_val = flipped_val.conjugate()
            h = (val + flipped_val)/2.
            a = val - h
541
542

        # correct variance
543
        if preserve_gaussian_variance:
Martin Reinecke's avatar
Martin Reinecke committed
544
545
            assert issubclass(val.dtype.type, np.complexfloating),\
                    "complex input field is needed here"
546
547
548
            h *= np.sqrt(2)
            a *= np.sqrt(2)

549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
#            The code below should not be needed in practice, since it would
#            only ever be called when hermitianizing a purely real field.
#            However it might be of educational use and keep us from forgetting
#            how these things are done ...

#            if not issubclass(val.dtype.type, np.complexfloating):
#                # in principle one must not correct the variance for the fixed
#                # points of the hermitianization. However, for a complex field
#                # the input field loses half of its power at its fixed points
#                # in the `hermitian` part. Hence, here a factor of sqrt(2) is
#                # also necessary!
#                # => The hermitianization can be done on a space level since
#                # either nothing must be done (LMSpace) or ALL points need a
#                # factor of sqrt(2)
#                # => use the preserve_gaussian_variance flag in the
#                # hermitian_decomposition method above.
#
#                # This code is for educational purposes:
#                fixed_points = [domain[i].hermitian_fixed_points()
#                                for i in spaces]
#                fixed_points = [[fp] if fp is None else fp
#                                for fp in fixed_points]
#
#                for product_point in itertools.product(*fixed_points):
#                    slice_object = np.array((slice(None), )*len(val.shape),
#                                            dtype=np.object)
#                    for i, sp in enumerate(spaces):
#                        point_component = product_point[i]
#                        if point_component is None:
#                            point_component = slice(None)
#                        slice_object[list(domain_axes[sp])] = point_component
#
#                    slice_object = tuple(slice_object)
#                    h[slice_object] /= np.sqrt(2)
#                    a[slice_object] /= np.sqrt(2)

585
586
        return (h, a)

587
588
    def _spec_to_rescaler(self, spec, result_list, power_space_index):
        power_space = self.domain[power_space_index]
589
590
591

        # weight the random fields with the power spectrum
        # therefore get the pindex from the power space
592
        pindex = power_space.pindex
593
594
595
596

        # Now use numpy advanced indexing in order to put the entries of the
        # power spectrum into the appropriate places of the pindex array.
        # Do this for every 'pindex-slice' in parallel using the 'slice(None)'s
Martin Reinecke's avatar
Martin Reinecke committed
597
        local_pindex = pindex
598

599
600
601
602
603
        local_blow_up = [slice(None)]*len(spec.shape)
        # it is important to count from behind, since spec potentially grows
        # with every iteration
        index = self.domain_axes[power_space_index][0]-len(self.shape)
        local_blow_up[index] = local_pindex
604
        # here, the power_spectrum is distributed into the new shape
605
606
        local_rescaler = spec[local_blow_up]
        return local_rescaler
607

Theo Steininger's avatar
Theo Steininger committed
608
    # ---Properties---
609

Theo Steininger's avatar
Theo Steininger committed
610
    def set_val(self, new_val=None, copy=False):
Martin Reinecke's avatar
stage1    
Martin Reinecke committed
611
        """ Sets the field's data object.
612
613
614

        Parameters
        ----------
Theo Steininger's avatar
Theo Steininger committed
615
        new_val : scalar, array-like, Field, None *optional*
616
617
            The values to be stored in the field.
            {default : None}
Theo Steininger's avatar
Theo Steininger committed
618

619
        copy : boolean, *optional*
Theo Steininger's avatar
Theo Steininger committed
620
621
            If False, Field tries to not copy the input data but use it
            directly.
622
623
624
625
626
627
            {default : False}
        See Also
        --------
        val

        """
Theo Steininger's avatar
Theo Steininger committed
628

629
630
        new_val = self.cast(new_val)
        if copy:
Theo Steininger's avatar
Theo Steininger committed
631
632
            new_val = new_val.copy()
        self._val = new_val
633
        return self
csongor's avatar
csongor committed
634

635
    def get_val(self, copy=False):
Martin Reinecke's avatar
stage1    
Martin Reinecke committed
636
        """ Returns the data object associated with this Field.
637
638
639
640

        Parameters
        ----------
        copy : boolean
Martin Reinecke's avatar
stage1    
Martin Reinecke committed
641
            If true, a copy of the Field's underlying data object
Theo Steininger's avatar
Theo Steininger committed
642
            is returned.
Theo Steininger's avatar
Theo Steininger committed
643

644
645
        Returns
        -------
Martin Reinecke's avatar
stage1    
Martin Reinecke committed
646
        out : numpy.ndarray
647
648
649
650
651
652

        See Also
        --------
        val

        """
Theo Steininger's avatar
Theo Steininger committed
653

654
655
656
        if self._val is None:
            self.set_val(None)

657
        if copy:
Theo Steininger's avatar
Theo Steininger committed
658
            return self._val.copy()
659
        else:
Theo Steininger's avatar
Theo Steininger committed
660
            return self._val
csongor's avatar
csongor committed
661

Theo Steininger's avatar
Theo Steininger committed
662
663
    @property
    def val(self):
Martin Reinecke's avatar
stage1    
Martin Reinecke committed
664
        """ Returns the data object associated with this Field.
Theo Steininger's avatar
Theo Steininger committed
665

666
667
        Returns
        -------
Martin Reinecke's avatar
stage1    
Martin Reinecke committed
668
        out : numpy.ndarray
669
670
671
672
673
674

        See Also
        --------
        get_val

        """
Theo Steininger's avatar
Theo Steininger committed
675

676
        return self.get_val(copy=False)
csongor's avatar
csongor committed
677

Theo Steininger's avatar
Theo Steininger committed
678
679
    @val.setter
    def val(self, new_val):
680
        self.set_val(new_val=new_val, copy=False)
csongor's avatar
csongor committed
681

682
683
    @property
    def shape(self):
Theo Steininger's avatar
Theo Steininger committed
684
        """ Returns the total shape of the Field's data array.
Theo Steininger's avatar
Theo Steininger committed
685

686
687
688
        Returns
        -------
        out : tuple
Martin Reinecke's avatar
Martin Reinecke committed
689
            The output object. The tuple contains the dimensions of the spaces
690
691
692
693
694
695
696
            in domain.

        See Also
        --------
        dim

        """
Theo Steininger's avatar
Theo Steininger committed
697
698
699
700
701
702
703
704
        if not hasattr(self, '_shape'):
            shape_tuple = tuple(sp.shape for sp in self.domain)
            try:
                global_shape = reduce(lambda x, y: x + y, shape_tuple)
            except TypeError:
                global_shape = ()
            self._shape = global_shape
        return self._shape
csongor's avatar
csongor committed
705

706
707
    @property
    def dim(self):
Theo Steininger's avatar
Theo Steininger committed
708
        """ Returns the total number of pixel-dimensions the field has.
Theo Steininger's avatar
Theo Steininger committed
709

Theo Steininger's avatar
Theo Steininger committed
710
        Effectively, all values from shape are multiplied.
Theo Steininger's avatar
Theo Steininger committed
711

712
713
714
715
716
717
718
719
720
721
        Returns
        -------
        out : int
            The dimension of the Field.

        See Also
        --------
        shape

        """
Theo Steininger's avatar
Theo Steininger committed
722

723
        dim_tuple = tuple(sp.dim for sp in self.domain)
Theo Steininger's avatar
Theo Steininger committed
724
        try:
Martin Reinecke's avatar
Martin Reinecke committed
725
            return int(reduce(lambda x, y: x * y, dim_tuple))
Theo Steininger's avatar
Theo Steininger committed
726
727
        except TypeError:
            return 0
csongor's avatar
csongor committed
728

729
730
    @property
    def dof(self):
Theo Steininger's avatar
Theo Steininger committed
731
732
733
734
735
736
        """ Returns the total number of degrees of freedom the Field has. For
        real Fields this is equal to `self.dim`. For complex Fields it is
        2*`self.dim`.

        """

Theo Steininger's avatar
Theo Steininger committed
737
738
739
740
741
742
743
        dof = self.dim
        if issubclass(self.dtype.type, np.complexfloating):
            dof *= 2
        return dof

    @property
    def total_volume(self):
Theo Steininger's avatar
Theo Steininger committed
744
745
746
        """ Returns the total volume of all spaces in the domain.
        """

Theo Steininger's avatar
Theo Steininger committed
747
        volume_tuple = tuple(sp.total_volume for sp in self.domain)
748
        try:
Theo Steininger's avatar
Theo Steininger committed
749
            return reduce(lambda x, y: x * y, volume_tuple)
750
        except TypeError:
Theo Steininger's avatar
Theo Steininger committed
751
            return 0.
752

Theo Steininger's avatar
Theo Steininger committed
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
    @property
    def real(self):
        """ The real part of the field (data is not copied).
        """
        real_part = self.val.real
        result = self.copy_empty(dtype=real_part.dtype)
        result.set_val(new_val=real_part, copy=False)
        return result

    @property
    def imag(self):
        """ The imaginary part of the field (data is not copied).
        """
        real_part = self.val.imag
        result = self.copy_empty(dtype=real_part.dtype)
        result.set_val(new_val=real_part, copy=False)
        return result

Theo Steininger's avatar
Theo Steininger committed
771
    # ---Special unary/binary operations---
772

csongor's avatar
csongor committed
773
    def cast(self, x=None, dtype=None):
Martin Reinecke's avatar
stage1    
Martin Reinecke committed
774
        """ Transforms x to an object with the correct dtype and shape.
Theo Steininger's avatar
Theo Steininger committed
775

776
777
        Parameters
        ----------
Martin Reinecke's avatar
stage1    
Martin Reinecke committed
778
779
780
        x : scalar, numpy.ndarray, Field, array_like
            The input that shall be casted on a numpy.ndarray of the same shape
            like the domain.
Theo Steininger's avatar
Theo Steininger committed
781

782
        dtype : type
Theo Steininger's avatar
Theo Steininger committed
783
            The datatype the output shall have. This can be used to override
Martin Reinecke's avatar
typos    
Martin Reinecke committed
784
            the field's dtype.
Theo Steininger's avatar
Theo Steininger committed
785

786
787
        Returns
        -------
Martin Reinecke's avatar
stage1    
Martin Reinecke committed
788
        out : numpy.ndarray
789
790
791
792
793
794
795
            The output object.

        See Also
        --------
        _actual_cast

        """
csongor's avatar
csongor committed
796
797
        if dtype is None:
            dtype = self.dtype
798
799
        else:
            dtype = np.dtype(dtype)
800

801
802
        casted_x = x

803
        for ind, sp in enumerate(self.domain):
804
            casted_x = sp.pre_cast(casted_x,
805
806
807
                                   axes=self.domain_axes[ind])

        casted_x = self._actual_cast(casted_x, dtype=dtype)
808
809

        for ind, sp in enumerate(self.domain):
810
811
            casted_x = sp.post_cast(casted_x,
                                    axes=self.domain_axes[ind])
812

813
        return casted_x
csongor's avatar
csongor committed
814

Theo Steininger's avatar
Theo Steininger committed
815
    def _actual_cast(self, x, dtype=None):
816
        if isinstance(x, Field):
csongor's avatar
csongor committed
817
818
819
820
            x = x.get_val()

        if dtype is None:
            dtype = self.dtype
Martin Reinecke's avatar
stage1    
Martin Reinecke committed
821
        if x is not None:
Martin Reinecke's avatar
more    
Martin Reinecke committed
822
823
            if np.isscalar(x):
                return np.full(self.shape,x, dtype=dtype)
Martin Reinecke's avatar
stage1    
Martin Reinecke committed
824
825
826
            return np.asarray(x, dtype=dtype).reshape(self.shape)
        else:
            return np.empty(self.shape, dtype=dtype)
csongor's avatar
csongor committed
827

Martin Reinecke's avatar
stage1    
Martin Reinecke committed
828
    def copy(self, domain=None, dtype=None):
829
        """ Returns a full copy of the Field.
Theo Steininger's avatar
Theo Steininger committed
830

831
832
        If no keyword arguments are given, the returned object will be an
        identical copy of the original Field. By explicit specification one is
Martin Reinecke's avatar
stage1    
Martin Reinecke committed
833
        able to define the domain and the dtype of the returned Field.
834
835
836
837
838

        Parameters
        ----------
        domain : DomainObject
            The new domain the Field shall have.
Theo Steininger's avatar
Theo Steininger committed
839

840
841
        dtype : type
            The new dtype the Field shall have.
Theo Steininger's avatar
Theo Steininger committed
842

843
844
845
846
847
848
849
850
851
852
        Returns
        -------
        out : Field
            The output object. An identical copy of 'self'.

        See Also
        --------
        copy_empty

        """
Theo Steininger's avatar
Theo Steininger committed
853

Theo Steininger's avatar
Theo Steininger committed
854
        copied_val = self.get_val(copy=True)
855
856
        new_field = self.copy_empty(
                                domain=domain,
Martin Reinecke's avatar
stage1    
Martin Reinecke committed
857
                                dtype=dtype)
Theo Steininger's avatar
Theo Steininger committed
858
859
        new_field.set_val(new_val=copied_val, copy=False)
        return new_field
csongor's avatar
csongor committed
860

Martin Reinecke's avatar
stage1    
Martin Reinecke committed
861
    def copy_empty(self, domain=None, dtype=None):
862
863
864
        """ Returns an empty copy of the Field.

        If no keyword arguments are given, the returned object will be an
Theo Steininger's avatar
Theo Steininger committed
865
866
867
        identical copy of the original Field. The memory for the data array
        is only allocated but not actively set to any value
        (c.f. numpy.ndarray.copy_empty). By explicit specification one is able
Martin Reinecke's avatar
stage1    
Martin Reinecke committed
868
        to change the domain and the dtype of the returned Field.
Theo Steininger's avatar
Theo Steininger committed
869

870
871
872
873
        Parameters
        ----------
        domain : DomainObject
            The new domain the Field shall have.
Theo Steininger's avatar
Theo Steininger committed
874

875
876
        dtype : type
            The new dtype the Field shall have.
Theo Steininger's avatar
Theo Steininger committed
877

878
879
880
        Returns
        -------
        out : Field
Theo Steininger's avatar
Theo Steininger committed
881
            The output object.
882
883
884
885
886
887

        See Also
        --------
        copy

        """
Theo Steininger's avatar
Theo Steininger committed
888

Theo Steininger's avatar
Theo Steininger committed
889
890
        if domain is None:
            domain = self.domain
csongor's avatar
csongor committed
891
        else:
Theo Steininger's avatar
Theo Steininger committed
892
            domain = self._parse_domain(domain)
csongor's avatar
csongor committed
893

Theo Steininger's avatar
Theo Steininger committed
894
895
896
897
        if dtype is None:
            dtype = self.dtype
        else:
            dtype = np.dtype(dtype)
csongor's avatar
csongor committed
898

Theo Steininger's avatar
Theo Steininger committed
899
900
        fast_copyable = True
        try:
Martin Reinecke's avatar
Martin Reinecke committed
901
            for i in range(len(self.domain)):
Theo Steininger's avatar
Theo Steininger committed
902
903
904
905
906
907
                if self.domain[i] is not domain[i]:
                    fast_copyable = False
                    break
        except IndexError:
            fast_copyable = False

Martin Reinecke's avatar
stage1    
Martin Reinecke committed
908
        if (fast_copyable and dtype == self.dtype):
Theo Steininger's avatar
Theo Steininger committed
909
910
            new_field = self._fast_copy_empty()
        else:
Martin Reinecke's avatar
stage1    
Martin Reinecke committed
911
            new_field = Field(domain=domain, dtype=dtype)
Theo Steininger's avatar
Theo Steininger committed
912
        return new_field
csongor's avatar
csongor committed
913

Theo Steininger's avatar
Theo Steininger committed
914
915
916
917
918
919
    def _fast_copy_empty(self):
        # make an empty field
        new_field = EmptyField()
        # repair its class
        new_field.__class__ = self.__class__
        # copy domain, codomain and val
Martin Reinecke's avatar
Martin Reinecke committed
920
        for key, value in list(self.__dict__.items()):
921
            if key != '_val':
Theo Steininger's avatar
Theo Steininger committed
922
923
                new_field.__dict__[key] = value
            else:
Martin Reinecke's avatar
stage1    
Martin Reinecke committed
924
                new_field.__dict__[key] = np.empty_like(self.val)
Theo Steininger's avatar
Theo Steininger committed
925
926
927
        return new_field

    def weight(self, power=1, inplace=False, spaces=None):
Theo Steininger's avatar
Theo Steininger committed
928
        """ Weights the pixels of `self` with their invidual pixel-volume.
929
930
931
932

        Parameters
        ----------
        power : number
Theo Steininger's avatar
Theo Steininger committed
933
            The pixels get weighted with the volume-factor**power.
Theo Steininger's avatar
Theo Steininger committed
934

935
        inplace : boolean
Theo Steininger's avatar
Theo Steininger committed
936
937
            If True, `self` will be weighted and returned. Otherwise, a copy
            is made.
Theo Steininger's avatar
Theo Steininger committed
938

Theo Steininger's avatar
Theo Steininger committed
939
940
        spaces : tuple of ints
            Determines on which subspace the operation takes place.
Theo Steininger's avatar
Theo Steininger committed
941

942
943
944
        Returns
        -------
        out : Field
Theo Steininger's avatar
Theo Steininger committed
945
            The weighted field.
946
947

        """
948
        if inplace:
csongor's avatar
csongor committed
949
950
951
952
            new_field = self
        else:
            new_field = self.copy_empty()

953
        new_val = self.get_val(copy=False)
csongor's avatar
csongor committed
954

955
        spaces = utilities.cast_axis_to_tuple(spaces, len(self.domain))
csongor's avatar
csongor committed
956
        if spaces is None:
Martin Reinecke's avatar
Martin Reinecke committed
957
            spaces = list(range(len(self.domain)))
csongor's avatar
csongor committed
958

959
        for ind, sp in enumerate(self.domain):
Theo Steininger's avatar
Theo Steininger committed
960
961
962
963
964
            if ind in spaces:
                new_val = sp.weight(new_val,
                                    power=power,
                                    axes=self.domain_axes[ind],
                                    inplace=inplace)
965
966

        new_field.set_val(new_val=new_val, copy=False)
csongor's avatar
csongor committed
967
968
        return new_field

Martin Reinecke's avatar
Martin Reinecke committed
969
    def vdot(self, x=None, spaces=None, bare=False):
Theo Steininger's avatar
Theo Steininger committed
970
        """ Computes the volume-factor-aware dot product of 'self' with x.
Theo Steininger's avatar
Theo Steininger committed
971

972
973
974
        Parameters
        ----------
        x : Field
Theo Steininger's avatar
Theo Steininger committed
975
            The domain of x must contain `self.domain`
Theo Steininger's avatar
Theo Steininger committed
976

Theo Steininger's avatar
Theo Steininger committed
977
978