field.py 47.7 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
from builtins import zip
Martin Reinecke's avatar
Martin Reinecke committed
21
#from builtins import str
Martin Reinecke's avatar
Martin Reinecke committed
22
from builtins import range
23

24
import ast
25
import itertools
csongor's avatar
csongor committed
26
27
import numpy as np

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

31
from d2o import distributed_data_object,\
32
    STRATEGIES as DISTRIBUTION_STRATEGIES
csongor's avatar
csongor committed
33

Martin Reinecke's avatar
Martin Reinecke committed
34
from .config import nifty_configuration as gc
csongor's avatar
csongor committed
35

Martin Reinecke's avatar
Martin Reinecke committed
36
from .domain_object import DomainObject
37

Martin Reinecke's avatar
Martin Reinecke committed
38
from .spaces.power_space import PowerSpace
csongor's avatar
csongor committed
39

Martin Reinecke's avatar
Martin Reinecke committed
40
41
from . import nifty_utilities as utilities
from .random import Random
Martin Reinecke's avatar
Martin Reinecke committed
42
from functools import reduce
43

csongor's avatar
csongor committed
44

Jait Dixit's avatar
Jait Dixit committed
45
class Field(Loggable, Versionable, object):
Theo Steininger's avatar
Theo Steininger committed
46
47
48
    """ The discrete representation of a continuous field over multiple spaces.

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

52
53
54
55
    Parameters
    ----------
    domain : DomainObject
        One of the space types NIFTY supports. RGSpace, GLSpace, HPSpace,
Theo Steininger's avatar
Theo Steininger committed
56
        LMSpace or PowerSpace. It might also be a FieldArray, which is
57
        an unstructured domain.
Theo Steininger's avatar
Theo Steininger committed
58

59
60
61
62
    val : scalar, numpy.ndarray, distributed_data_object, Field
        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
63

64
65
    dtype : type
        A numpy.type. Most common are int, float and complex.
Theo Steininger's avatar
Theo Steininger committed
66

67
68
69
70
71
72
    distribution_strategy: optional[{'fftw', 'equal', 'not', 'freeform'}]
        Specifies which distributor will be created and used.
        'fftw'      uses the distribution strategy of pyfftw,
        'equal'     tries to  distribute the data as uniform as possible
        'not'       does not distribute the data at all
        'freeform'  distribute the data according to the given local data/shape
Theo Steininger's avatar
Theo Steininger committed
73

74
75
76
77
78
    copy: boolean

    Attributes
    ----------
    val : distributed_data_object
Theo Steininger's avatar
Theo Steininger committed
79

80
81
82
83
84
85
86
    domain : DomainObject
        See Parameters.
    domain_axes : tuple of tuples
        Enumerates the axes of the Field
    dtype : type
        Contains the datatype stored in the Field.
    distribution_strategy : string
Theo Steininger's avatar
Theo Steininger committed
87
88
        Name of the used distribution_strategy.

89
90
91
92
93
94
95
    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
96

97
98
99
100
101
102
103
104
105
106
107
    Examples
    --------
    >>> a = Field(RGSpace([4,5]),val=2)
    >>> a.val
    <distributed_data_object>
    array([[2, 2, 2, 2, 2],
           [2, 2, 2, 2, 2],
           [2, 2, 2, 2, 2],
           [2, 2, 2, 2, 2]])
    >>> a.dtype
    dtype('int64')
Theo Steininger's avatar
Theo Steininger committed
108

109
110
111
112
113
    See Also
    --------
    distributed_data_object

    """
114

theos's avatar
theos committed
115
    # ---Initialization methods---
116

117
    def __init__(self, domain=None, val=None, dtype=None,
118
                 distribution_strategy=None, copy=False):
csongor's avatar
csongor committed
119

120
        self.domain = self._parse_domain(domain=domain, val=val)
121
        self.domain_axes = self._get_axes_tuple(self.domain)
csongor's avatar
csongor committed
122

theos's avatar
theos committed
123
        self.dtype = self._infer_dtype(dtype=dtype,
124
                                       val=val)
125

126
127
128
        self.distribution_strategy = self._parse_distribution_strategy(
                                distribution_strategy=distribution_strategy,
                                val=val)
csongor's avatar
csongor committed
129

130
131
132
133
        if val is None:
            self._val = None
        else:
            self.set_val(new_val=val, copy=copy)
csongor's avatar
csongor committed
134

135
    def _parse_domain(self, domain, val=None):
136
        if domain is None:
137
138
139
140
            if isinstance(val, Field):
                domain = val.domain
            else:
                domain = ()
141
        elif isinstance(domain, DomainObject):
142
            domain = (domain,)
143
144
145
        elif not isinstance(domain, tuple):
            domain = tuple(domain)

csongor's avatar
csongor committed
146
        for d in domain:
147
            if not isinstance(d, DomainObject):
148
149
                raise TypeError(
                    "Given domain contains something that is not a "
150
                    "DomainObject instance.")
csongor's avatar
csongor committed
151
152
        return domain

theos's avatar
theos committed
153
154
155
156
157
158
159
160
161
162
    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)
163

164
    def _infer_dtype(self, dtype, val):
csongor's avatar
csongor committed
165
        if dtype is None:
166
            try:
167
                dtype = val.dtype
168
            except AttributeError:
Theo Steininger's avatar
Theo Steininger committed
169
170
171
                try:
                    if val is None:
                        raise TypeError
172
                    dtype = np.result_type(val)
Theo Steininger's avatar
Theo Steininger committed
173
                except(TypeError):
174
                    dtype = np.dtype(gc['default_field_dtype'])
theos's avatar
theos committed
175
        else:
176
            dtype = np.dtype(dtype)
177

178
179
        dtype = np.result_type(dtype, np.float)

theos's avatar
theos committed
180
        return dtype
181

182
183
    def _parse_distribution_strategy(self, distribution_strategy, val):
        if distribution_strategy is None:
184
            if isinstance(val, distributed_data_object):
185
                distribution_strategy = val.distribution_strategy
186
            elif isinstance(val, Field):
187
                distribution_strategy = val.distribution_strategy
188
            else:
189
                self.logger.debug("distribution_strategy set to default!")
190
                distribution_strategy = gc['default_distribution_strategy']
191
        elif distribution_strategy not in DISTRIBUTION_STRATEGIES['global']:
192
193
194
            raise ValueError(
                    "distribution_strategy must be a global-type "
                    "strategy.")
195
        return distribution_strategy
196
197

    # ---Factory methods---
198

199
    @classmethod
200
    def from_random(cls, random_type, domain=None, dtype=None,
201
                    distribution_strategy=None, **kwargs):
202
203
204
205
206
        """ Draws a random field with the given parameters.

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

208
209
210
        random_type : String
            'pm1', 'normal', 'uniform' are the supported arguments for this
            method.
Theo Steininger's avatar
Theo Steininger committed
211

212
213
        domain : DomainObject
            The domain of the output random field
Theo Steininger's avatar
Theo Steininger committed
214

215
216
        dtype : type
            The datatype of the output random field
Theo Steininger's avatar
Theo Steininger committed
217

218
219
        distribution_strategy : all supported distribution strategies
            The distribution strategy of the output random field
Theo Steininger's avatar
Theo Steininger committed
220

221
222
223
224
225
226
227
        Returns
        -------
        out : Field
            The output object.

        See Also
        --------
228
        power_synthesize
Theo Steininger's avatar
Theo Steininger committed
229

230
231

        """
Theo Steininger's avatar
Theo Steininger committed
232

233
        # create a initially empty field
234
        f = cls(domain=domain, dtype=dtype,
235
                distribution_strategy=distribution_strategy)
236
237
238
239
240
241
242

        # 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
Martin Reinecke committed
243
        # extract the distributed_data_object from f and apply the appropriate
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
        # random number generator to it
        sample = f.get_val(copy=False)
        generator_function = getattr(Random, random_type)
        sample.apply_generator(
            lambda shape: generator_function(dtype=f.dtype,
                                             shape=shape,
                                             **random_arguments))
        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
270
        else:
271
272
            raise KeyError(
                "unsupported random key '" + str(random_type) + "'.")
csongor's avatar
csongor committed
273

274
        return random_arguments
csongor's avatar
csongor committed
275

276
277
    # ---Powerspectral methods---

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

Theo Steininger's avatar
Theo Steininger committed
282
283
284
        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
285
        harmonic space. The resulting field has the same units as the initial
Theo Steininger's avatar
Theo Steininger committed
286
        field, corresponding to the square root of the power spectrum.
287
288
289

        Parameters
        ----------
Theo Steininger's avatar
Theo Steininger committed
290
291
292
293
294
        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
295
            {default : None}
Theo Steininger's avatar
Theo Steininger committed
296
297
298
299
300
301
        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
302
303
            Overrides nbin and logarithmic.
            if binbounds==None : bins are inferred.
304
305
306
307
308
309
310
311
312
313
        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
314

315
316
317
318
        Raise
        -----
        ValueError
            Raised if
Theo Steininger's avatar
Theo Steininger committed
319
320
                *len(domain) is != 1 when spaces==None
                *len(spaces) is != 1 if not None
321
                *the analyzed space is not harmonic
Theo Steininger's avatar
Theo Steininger committed
322

323
324
        Returns
        -------
Theo Steininger's avatar
Theo Steininger committed
325
        out : Field
326
327
328
329
330
331
            The output object. It's domain is a PowerSpace and it contains
            the power spectrum of 'self's field.

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

333
        """
Theo Steininger's avatar
Theo Steininger committed
334

Theo Steininger's avatar
Theo Steininger committed
335
        # check if all spaces in `self.domain` are either harmonic or
336
337
338
        # power_space instances
        for sp in self.domain:
            if not sp.harmonic and not isinstance(sp, PowerSpace):
Theo Steininger's avatar
Theo Steininger committed
339
                self.logger.info(
340
                    "Field has a space in `domain` which is neither "
341
342
343
                    "harmonic nor a PowerSpace.")

        # check if the `spaces` input is valid
344
345
        spaces = utilities.cast_axis_to_tuple(spaces, len(self.domain))
        if spaces is None:
Martin Reinecke's avatar
Martin Reinecke committed
346
            spaces = list(range(len(self.domain)))
347
348

        if len(spaces) == 0:
349
350
            raise ValueError(
                "No space for analysis specified.")
351

352
353
354
355
356
357
358
359
360
361
362
363
364
        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]
365
366

        for space_index in spaces:
367
368
            parts = [self._single_power_analyze(
                                work_field=part,
369
370
371
                                space_index=space_index,
                                logarithmic=logarithmic,
                                nbin=nbin,
372
373
                                binbounds=binbounds)
                     for part in parts]
374

375
376
377
378
379
380
        if keep_phase_information:
            result_field = parts[0] + 1j*parts[1]
        else:
            result_field = parts[0]

        return result_field
381
382
383

    @classmethod
    def _single_power_analyze(cls, work_field, space_index, logarithmic, nbin,
384
                              binbounds):
385

386
        if not work_field.domain[space_index].harmonic:
387
388
            raise ValueError(
                "The analyzed space must be harmonic.")
389

390
391
392
393
394
395
        # 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.

396
        distribution_strategy = \
397
398
            work_field.val.get_axes_local_distribution_strategy(
                work_field.domain_axes[space_index])
399

400
        harmonic_domain = work_field.domain[space_index]
401
        power_domain = PowerSpace(harmonic_partner=harmonic_domain,
402
                                  distribution_strategy=distribution_strategy,
Theo Steininger's avatar
Theo Steininger committed
403
404
                                  logarithmic=logarithmic, nbin=nbin,
                                  binbounds=binbounds)
405

406
407
        power_spectrum = cls._calculate_power_spectrum(
                                field_val=work_field.val,
Martin Reinecke's avatar
Martin Reinecke committed
408
                                pdomain=power_domain,
409
                                axes=work_field.domain_axes[space_index])
410
411

        # create the result field and put power_spectrum into it
412
        result_domain = list(work_field.domain)
413
        result_domain[space_index] = power_domain
414
        result_dtype = power_spectrum.dtype
415

416
        result_field = work_field.copy_empty(
417
                   domain=result_domain,
418
                   dtype=result_dtype,
419
                   distribution_strategy=power_spectrum.distribution_strategy)
420
421
422
423
        result_field.set_val(new_val=power_spectrum, copy=False)

        return result_field

424
    @classmethod
Martin Reinecke's avatar
Martin Reinecke committed
425
    def _calculate_power_spectrum(cls, field_val, pdomain, axes=None):
426

Martin Reinecke's avatar
Martin Reinecke committed
427
428
429
        pindex = pdomain.pindex
        # MR FIXME: how about iterating over slices, instead of replicating
        # pindex? Would save memory and probably isn't slower.
430
        if axes is not None:
431
432
433
434
435
436
            pindex = cls._shape_up_pindex(
                            pindex=pindex,
                            target_shape=field_val.shape,
                            target_strategy=field_val.distribution_strategy,
                            axes=axes)
        power_spectrum = pindex.bincount(weights=field_val,
437
                                         axis=axes)
Martin Reinecke's avatar
Martin Reinecke committed
438
        rho = pdomain.rho
439
440
441
442
443
444
445
446
        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

447
448
    @staticmethod
    def _shape_up_pindex(pindex, target_shape, target_strategy, axes):
449
450
        if pindex.distribution_strategy not in \
                DISTRIBUTION_STRATEGIES['global']:
451
            raise ValueError("pindex's distribution strategy must be "
452
453
454
455
456
457
                             "global-type")

        if pindex.distribution_strategy in DISTRIBUTION_STRATEGIES['slicing']:
            if ((0 not in axes) or
                    (target_strategy is not pindex.distribution_strategy)):
                raise ValueError(
458
                    "A slicing distributor shall not be reshaped to "
459
460
461
462
463
464
465
466
467
468
469
470
471
                    "something non-sliced.")

        semiscaled_shape = [1, ] * len(target_shape)
        for i in axes:
            semiscaled_shape[i] = target_shape[i]
        local_data = pindex.get_local_data(copy=False)
        semiscaled_local_data = local_data.reshape(semiscaled_shape)
        result_obj = pindex.copy_empty(global_shape=target_shape,
                                       distribution_strategy=target_strategy)
        result_obj.set_full_data(semiscaled_local_data, copy=False)

        return result_obj

472
    def power_synthesize(self, spaces=None, real_power=True, real_signal=True,
473
                         mean=None, std=None, distribution_strategy=None):
Theo Steininger's avatar
Theo Steininger committed
474
        """ Yields a sampled field with `self`**2 as its power spectrum.
Theo Steininger's avatar
Theo Steininger committed
475

Theo Steininger's avatar
Theo Steininger committed
476
477
        This method draws a Gaussian random field in the harmonic partner
        domain of this fields domains, using this field as power spectrum.
Theo Steininger's avatar
Theo Steininger committed
478

479
480
481
        Parameters
        ----------
        spaces : {tuple, int, None} *optional*
Theo Steininger's avatar
Theo Steininger committed
482
483
484
            Specifies the subspace containing all the PowerSpaces which
            should be converted (default : None).
            if spaces==None : Tries to convert the whole domain.
485
        real_power : boolean *optional*
Theo Steininger's avatar
Theo Steininger committed
486
487
            Determines whether the power spectrum is treated as intrinsically
            real or complex (default : True).
488
        real_signal : boolean *optional*
Theo Steininger's avatar
Theo Steininger committed
489
490
491
492
493
494
            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
495
        std : float *optional*
Theo Steininger's avatar
Theo Steininger committed
496
497
498
            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
499

500
501
502
503
        Returns
        -------
        out : Field
            The output object. A random field created with the power spectrum
Theo Steininger's avatar
Theo Steininger committed
504
            stored in the `spaces` in `self`.
505

Theo Steininger's avatar
Theo Steininger committed
506
507
508
509
510
511
        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.

512
513
514
        See Also
        --------
        power_analyze
Theo Steininger's avatar
Theo Steininger committed
515
516
517
518
519

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

520
        """
Theo Steininger's avatar
Theo Steininger committed
521

522
523
524
        # check if the `spaces` input is valid
        spaces = utilities.cast_axis_to_tuple(spaces, len(self.domain))

Theo Steininger's avatar
Theo Steininger committed
525
        if spaces is None:
Martin Reinecke's avatar
Martin Reinecke committed
526
            spaces = list(range(len(self.domain)))
Theo Steininger's avatar
Theo Steininger committed
527

528
529
530
531
532
        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.")
533
534
535

        # create the result domain
        result_domain = list(self.domain)
536
537
        for power_space_index in spaces:
            power_space = self.domain[power_space_index]
538
            harmonic_domain = power_space.harmonic_partner
539
            result_domain[power_space_index] = harmonic_domain
540
541
542

        # create random samples: one or two, depending on whether the
        # power spectrum is real or complex
543
        if real_power:
544
            result_list = [None]
545
546
        else:
            result_list = [None, None]
547

548
549
550
        if distribution_strategy is None:
            distribution_strategy = gc['default_distribution_strategy']

551
552
        result_list = [self.__class__.from_random(
                             'normal',
553
554
555
                             mean=mean,
                             std=std,
                             domain=result_domain,
556
                             dtype=np.complex,
557
                             distribution_strategy=distribution_strategy)
558
559
560
561
562
563
                       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
564
565

        spec = self.val.get_full_data()
566
567
        spec = np.sqrt(spec)

568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
        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
        result_val_list[0].apply_scalar_function(
                                            lambda x: x * local_rescaler.real,
                                            inplace=True)

        if not real_power:
            result_val_list[1].apply_scalar_function(
                                            lambda x: x * local_rescaler.imag,
                                            inplace=True)

584
        if real_signal:
585
            result_val_list = [self._hermitian_decomposition(
586
587
588
589
590
                                            result_domain,
                                            result_val,
                                            spaces,
                                            result_list[0].domain_axes,
                                            preserve_gaussian_variance=True)[0]
591
                               for result_val in result_val_list]
592
593
594
595
596
597
598

        # 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]
599
        else:
600
601
602
603
            result = result_list[0] + 1j*result_list[1]

        return result

604
    @staticmethod
605
606
    def _hermitian_decomposition(domain, val, spaces, domain_axes,
                                 preserve_gaussian_variance=False):
607
608
609
610
611
612
613
614
615

        flipped_val = val
        for space in spaces:
            flipped_val = domain[space].hermitianize_inverter(
                                                    x=flipped_val,
                                                    axes=domain_axes[space])
        flipped_val = flipped_val.conjugate()
        h = (val + flipped_val)/2.
        a = val - h
616
617

        # correct variance
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
        if preserve_gaussian_variance:
            h *= np.sqrt(2)
            a *= np.sqrt(2)

            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)
652
653
        return (h, a)

654
655
    def _spec_to_rescaler(self, spec, result_list, power_space_index):
        power_space = self.domain[power_space_index]
656
657
658

        # weight the random fields with the power spectrum
        # therefore get the pindex from the power space
659
        pindex = power_space.pindex
660
661
662
663
664
665
666
        # take the local data from pindex. This data must be compatible to the
        # local data of the field given the slice of the PowerSpace
        local_distribution_strategy = \
            result_list[0].val.get_axes_local_distribution_strategy(
                result_list[0].domain_axes[power_space_index])

        if pindex.distribution_strategy is not local_distribution_strategy:
667
            self.logger.warn(
Martin Reinecke's avatar
Martin Reinecke committed
668
                "The distribution_strategy of pindex does not fit the "
669
670
671
672
673
674
675
                "slice_local distribution strategy of the synthesized field.")

        # 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
        local_pindex = pindex.get_local_data(copy=False)

676
677
678
679
680
        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
681
        # here, the power_spectrum is distributed into the new shape
682
683
        local_rescaler = spec[local_blow_up]
        return local_rescaler
684

theos's avatar
theos committed
685
    # ---Properties---
686

theos's avatar
theos committed
687
    def set_val(self, new_val=None, copy=False):
Theo Steininger's avatar
Theo Steininger committed
688
        """ Sets the fields distributed_data_object.
689
690
691

        Parameters
        ----------
Theo Steininger's avatar
Theo Steininger committed
692
        new_val : scalar, array-like, Field, None *optional*
693
694
            The values to be stored in the field.
            {default : None}
Theo Steininger's avatar
Theo Steininger committed
695

696
        copy : boolean, *optional*
Theo Steininger's avatar
Theo Steininger committed
697
698
            If False, Field tries to not copy the input data but use it
            directly.
699
700
701
702
703
704
            {default : False}
        See Also
        --------
        val

        """
Theo Steininger's avatar
Theo Steininger committed
705

706
707
        new_val = self.cast(new_val)
        if copy:
theos's avatar
theos committed
708
709
            new_val = new_val.copy()
        self._val = new_val
theos's avatar
theos committed
710
        return self
csongor's avatar
csongor committed
711

712
    def get_val(self, copy=False):
Theo Steininger's avatar
Theo Steininger committed
713
        """ Returns the distributed_data_object associated with this Field.
714
715
716
717

        Parameters
        ----------
        copy : boolean
Theo Steininger's avatar
Theo Steininger committed
718
719
            If true, a copy of the Field's underlying distributed_data_object
            is returned.
Theo Steininger's avatar
Theo Steininger committed
720

721
722
723
724
725
726
727
728
729
        Returns
        -------
        out : distributed_data_object

        See Also
        --------
        val

        """
Theo Steininger's avatar
Theo Steininger committed
730

731
732
733
        if self._val is None:
            self.set_val(None)

734
        if copy:
theos's avatar
theos committed
735
            return self._val.copy()
736
        else:
theos's avatar
theos committed
737
            return self._val
csongor's avatar
csongor committed
738

theos's avatar
theos committed
739
740
    @property
    def val(self):
Theo Steininger's avatar
Theo Steininger committed
741
        """ Returns the distributed_data_object associated with this Field.
Theo Steininger's avatar
Theo Steininger committed
742

743
744
745
746
747
748
749
750
751
        Returns
        -------
        out : distributed_data_object

        See Also
        --------
        get_val

        """
Theo Steininger's avatar
Theo Steininger committed
752

753
        return self.get_val(copy=False)
csongor's avatar
csongor committed
754

theos's avatar
theos committed
755
756
    @val.setter
    def val(self, new_val):
757
        self.set_val(new_val=new_val, copy=False)
csongor's avatar
csongor committed
758

759
760
    @property
    def shape(self):
Theo Steininger's avatar
Theo Steininger committed
761
        """ Returns the total shape of the Field's data array.
Theo Steininger's avatar
Theo Steininger committed
762

763
764
765
        Returns
        -------
        out : tuple
Martin Reinecke's avatar
Martin Reinecke committed
766
            The output object. The tuple contains the dimensions of the spaces
767
768
769
770
771
772
773
            in domain.

        See Also
        --------
        dim

        """
Theo Steininger's avatar
Theo Steininger committed
774

775
        shape_tuple = tuple(sp.shape for sp in self.domain)
776
777
778
779
        try:
            global_shape = reduce(lambda x, y: x + y, shape_tuple)
        except TypeError:
            global_shape = ()
csongor's avatar
csongor committed
780

781
        return global_shape
csongor's avatar
csongor committed
782

783
784
    @property
    def dim(self):
Theo Steininger's avatar
Theo Steininger committed
785
        """ Returns the total number of pixel-dimensions the field has.
Theo Steininger's avatar
Theo Steininger committed
786

Theo Steininger's avatar
Theo Steininger committed
787
        Effectively, all values from shape are multiplied.
Theo Steininger's avatar
Theo Steininger committed
788

789
790
791
792
793
794
795
796
797
798
        Returns
        -------
        out : int
            The dimension of the Field.

        See Also
        --------
        shape

        """
Theo Steininger's avatar
Theo Steininger committed
799

800
        dim_tuple = tuple(sp.dim for sp in self.domain)
theos's avatar
theos committed
801
        try:
Martin Reinecke's avatar
Martin Reinecke committed
802
            return int(reduce(lambda x, y: x * y, dim_tuple))
theos's avatar
theos committed
803
804
        except TypeError:
            return 0
csongor's avatar
csongor committed
805

806
807
    @property
    def dof(self):
Theo Steininger's avatar
Theo Steininger committed
808
809
810
811
812
813
        """ 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`.

        """

theos's avatar
theos committed
814
815
816
817
818
819
820
        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
821
822
823
        """ Returns the total volume of all spaces in the domain.
        """

theos's avatar
theos committed
824
        volume_tuple = tuple(sp.total_volume for sp in self.domain)
825
        try:
theos's avatar
theos committed
826
            return reduce(lambda x, y: x * y, volume_tuple)
827
        except TypeError:
Theo Steininger's avatar
Theo Steininger committed
828
            return 0.
829

theos's avatar
theos committed
830
    # ---Special unary/binary operations---
831

csongor's avatar
csongor committed
832
    def cast(self, x=None, dtype=None):
Theo Steininger's avatar
Theo Steininger committed
833
        """ Transforms x to a d2o with the correct dtype and shape.
Theo Steininger's avatar
Theo Steininger committed
834

835
836
        Parameters
        ----------
Theo Steininger's avatar
Theo Steininger committed
837
        x : scalar, d2o, Field, array_like
838
839
            The input that shall be casted on a d2o of the same shape like the
            domain.
Theo Steininger's avatar
Theo Steininger committed
840

841
        dtype : type
Theo Steininger's avatar
Theo Steininger committed
842
843
            The datatype the output shall have. This can be used to override
            the fields dtype.
Theo Steininger's avatar
Theo Steininger committed
844

845
846
847
848
849
850
851
852
853
854
        Returns
        -------
        out : distributed_data_object
            The output object.

        See Also
        --------
        _actual_cast

        """
csongor's avatar
csongor committed
855
856
        if dtype is None:
            dtype = self.dtype
857
858
        else:
            dtype = np.dtype(dtype)
859

860
861
        casted_x = x

862
        for ind, sp in enumerate(self.domain):
863
            casted_x = sp.pre_cast(casted_x,
864
865
866
                                   axes=self.domain_axes[ind])

        casted_x = self._actual_cast(casted_x, dtype=dtype)
867
868

        for ind, sp in enumerate(self.domain):
869
870
            casted_x = sp.post_cast(casted_x,
                                    axes=self.domain_axes[ind])
871

872
        return casted_x
csongor's avatar
csongor committed
873

theos's avatar
theos committed
874
    def _actual_cast(self, x, dtype=None):
875
        if isinstance(x, Field):
csongor's avatar
csongor committed
876
877
878
879
880
            x = x.get_val()

        if dtype is None:
            dtype = self.dtype

881
        return_x = distributed_data_object(
882
883
884
                            global_shape=self.shape,
                            dtype=dtype,
                            distribution_strategy=self.distribution_strategy)
885
886
        return_x.set_full_data(x, copy=False)
        return return_x
theos's avatar
theos committed
887

888
    def copy(self, domain=None, dtype=None, distribution_strategy=None):
889
        """ Returns a full copy of the Field.
Theo Steininger's avatar
Theo Steininger committed
890

891
892
893
894
895
896
897
898
899
        If no keyword arguments are given, the returned object will be an
        identical copy of the original Field. By explicit specification one is
        able to define the domain, the dtype and the distribution_strategy of
        the returned Field.

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

901
902
        dtype : type
            The new dtype the Field shall have.
Theo Steininger's avatar
Theo Steininger committed
903

904
        distribution_strategy : all supported distribution strategies
Theo Steininger's avatar
Theo Steininger committed
905
906
            The new distribution strategy the Field shall have.

907
908
909
910
911
912
913
914
915
916
        Returns
        -------
        out : Field
            The output object. An identical copy of 'self'.

        See Also
        --------
        copy_empty

        """
Theo Steininger's avatar
Theo Steininger committed
917

theos's avatar
theos committed
918
        copied_val = self.get_val(copy=True)
919
920
921
922
        new_field = self.copy_empty(
                                domain=domain,
                                dtype=dtype,
                                distribution_strategy=distribution_strategy)
theos's avatar
theos committed
923
924
        new_field.set_val(new_val=copied_val, copy=False)
        return new_field
csongor's avatar
csongor committed
925

926
    def copy_empty(self, domain=None, dtype=None, distribution_strategy=None):
927
928
929
        """ 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
930
931
932
933
934
        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
        to change the domain, the dtype and the distribution_strategy of the
        returned Field.
Theo Steininger's avatar
Theo Steininger committed
935

936
937
938
939
        Parameters
        ----------
        domain : DomainObject
            The new domain the Field shall have.
Theo Steininger's avatar
Theo Steininger committed
940

941
942
        dtype : type
            The new dtype the Field shall have.
Theo Steininger's avatar
Theo Steininger committed
943

Theo Steininger's avatar
Theo Steininger committed
944
        distribution_strategy : string, all supported distribution strategies
945
            The distribution strategy the new Field should have.
Theo Steininger's avatar
Theo Steininger committed
946

947
948
949
        Returns
        -------
        out : Field
Theo Steininger's avatar
Theo Steininger committed
950
            The output object.
951
952
953
954
955
956

        See Also
        --------
        copy

        """
Theo Steininger's avatar
Theo Steininger committed
957

theos's avatar
theos committed
958
959
        if domain is None:
            domain = self.domain
csongor's avatar
csongor committed
960
        else:
theos's avatar
theos committed
961
            domain = self._parse_domain(domain)
csongor's avatar
csongor committed
962

theos's avatar
theos committed
963
964
965
966
        if dtype is None:
            dtype = self.dtype
        else:
            dtype = np.dtype(dtype)
csongor's avatar
csongor committed
967

968
969
        if distribution_strategy is None:
            distribution_strategy = self.distribution_strategy
csongor's avatar
csongor committed
970

theos's avatar
theos committed
971
972
        fast_copyable = True
        try:
Martin Reinecke's avatar
Martin Reinecke committed
973
            for i in range(len(self.domain)):
theos's avatar
theos committed
974
975
976
977
978
979
980
                if self.domain[i] is not domain[i]:
                    fast_copyable = False
                    break
        except IndexError:
            fast_copyable = False

        if (fast_copyable and dtype == self.dtype and
981
                distribution_strategy == self.distribution_strategy):
theos's avatar
theos committed
982
983
984
985
            new_field = self._fast_copy_empty()
        else:
            new_field = Field(domain=domain,
                              dtype=dtype,
986
                              distribution_strategy=distribution_strategy)
theos's avatar
theos committed
987
        return new_field
csongor's avatar
csongor committed
988

theos's avatar
theos committed
989
990
991
992
993
994
    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
995
        for key, value in list(self.__dict__.items()):
996
            if key != '_val':
theos's avatar
theos committed
997
998
999
1000
                new_field.__dict__[key] = value
            else:
                new_field.__dict__[key] = self.val.copy_empty()
        return new_field
For faster browsing, not all history is shown. View entire blame