field.py 43.8 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# NIFTy
# Copyright (C) 2017  Theo Steininger
#
# Author: Theo Steininger
#
# 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/>.

csongor's avatar
csongor committed
19
20
21
from __future__ import division
import numpy as np

Theo Steininger's avatar
Theo Steininger committed
22
23
from keepers import Versionable,\
                    Loggable
Jait Dixit's avatar
Jait Dixit committed
24

25
from d2o import distributed_data_object,\
26
    STRATEGIES as DISTRIBUTION_STRATEGIES
csongor's avatar
csongor committed
27

28
from nifty.config import nifty_configuration as gc
csongor's avatar
csongor committed
29

30
from nifty.domain_object import DomainObject
31

32
from nifty.spaces.power_space import PowerSpace
csongor's avatar
csongor committed
33

csongor's avatar
csongor committed
34
import nifty.nifty_utilities as utilities
35
36
from nifty.random import Random

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

52
53
54
55
    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
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
64
65
    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
66

67
68
69
70
71
    copy: boolean

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

73
74
75
76
77
78
79
    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
80
81
        Name of the used distribution_strategy.

82
83
84
85
86
87
88
    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
89

90
91
92
93
94
95
96
97
98
99
100
    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
101

102
103
104
105
106
    See Also
    --------
    distributed_data_object

    """
Theo Steininger's avatar
Theo Steininger committed
107
    # ---Initialization methods---
108

109
    def __init__(self, domain=None, val=None, dtype=None,
110
                 distribution_strategy=None, copy=False):
csongor's avatar
csongor committed
111

112
        self.domain = self._parse_domain(domain=domain, val=val)
113
        self.domain_axes = self._get_axes_tuple(self.domain)
csongor's avatar
csongor committed
114

Theo Steininger's avatar
Theo Steininger committed
115
        self.dtype = self._infer_dtype(dtype=dtype,
116
                                       val=val)
117

118
119
120
        self.distribution_strategy = self._parse_distribution_strategy(
                                distribution_strategy=distribution_strategy,
                                val=val)
csongor's avatar
csongor committed
121

122
123
124
125
        if val is None:
            self._val = None
        else:
            self.set_val(new_val=val, copy=copy)
csongor's avatar
csongor committed
126

127
    def _parse_domain(self, domain, val=None):
128
        if domain is None:
129
130
131
132
            if isinstance(val, Field):
                domain = val.domain
            else:
                domain = ()
133
        elif isinstance(domain, DomainObject):
134
            domain = (domain,)
135
136
137
        elif not isinstance(domain, tuple):
            domain = tuple(domain)

csongor's avatar
csongor committed
138
        for d in domain:
139
            if not isinstance(d, DomainObject):
140
141
                raise TypeError(
                    "Given domain contains something that is not a "
142
                    "DomainObject instance.")
csongor's avatar
csongor committed
143
144
        return domain

Theo Steininger's avatar
Theo Steininger committed
145
146
147
148
149
150
151
152
153
154
    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)
155

156
    def _infer_dtype(self, dtype, val):
csongor's avatar
csongor committed
157
        if dtype is None:
158
            try:
159
                dtype = val.dtype
160
            except AttributeError:
Theo Steininger's avatar
Theo Steininger committed
161
162
163
                try:
                    if val is None:
                        raise TypeError
164
                    dtype = np.result_type(val)
Theo Steininger's avatar
Theo Steininger committed
165
                except(TypeError):
166
                    dtype = np.dtype(gc['default_field_dtype'])
Theo Steininger's avatar
Theo Steininger committed
167
        else:
168
            dtype = np.dtype(dtype)
169

Theo Steininger's avatar
Theo Steininger committed
170
        return dtype
171

172
173
    def _parse_distribution_strategy(self, distribution_strategy, val):
        if distribution_strategy is None:
174
            if isinstance(val, distributed_data_object):
175
                distribution_strategy = val.distribution_strategy
176
            elif isinstance(val, Field):
177
                distribution_strategy = val.distribution_strategy
178
            else:
179
                self.logger.debug("distribution_strategy set to default!")
180
                distribution_strategy = gc['default_distribution_strategy']
181
        elif distribution_strategy not in DISTRIBUTION_STRATEGIES['global']:
182
183
184
            raise ValueError(
                    "distribution_strategy must be a global-type "
                    "strategy.")
185
        return distribution_strategy
186
187

    # ---Factory methods---
188

189
    @classmethod
190
    def from_random(cls, random_type, domain=None, dtype=None,
191
                    distribution_strategy=None, **kwargs):
192
193
194
195
196
        """ Draws a random field with the given parameters.

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

198
199
200
        random_type : String
            'pm1', 'normal', 'uniform' are the supported arguments for this
            method.
Theo Steininger's avatar
Theo Steininger committed
201

202
203
        domain : DomainObject
            The domain of the output random field
Theo Steininger's avatar
Theo Steininger committed
204

205
206
        dtype : type
            The datatype of the output random field
Theo Steininger's avatar
Theo Steininger committed
207

208
209
        distribution_strategy : all supported distribution strategies
            The distribution strategy of the output random field
Theo Steininger's avatar
Theo Steininger committed
210

211
212
213
214
215
216
217
        Returns
        -------
        out : Field
            The output object.

        See Also
        --------
Theo Steininger's avatar
Theo Steininger committed
218
219
        power_synthesise

220
221

        """
Theo Steininger's avatar
Theo Steininger committed
222

223
        # create a initially empty field
224
        f = cls(domain=domain, dtype=dtype,
225
                distribution_strategy=distribution_strategy)
226
227
228
229
230
231
232

        # 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
233
        # extract the distributed_data_object from f and apply the appropriate
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
        # 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
260
        else:
261
262
            raise KeyError(
                "unsupported random key '" + str(random_type) + "'.")
csongor's avatar
csongor committed
263

264
        return random_arguments
csongor's avatar
csongor committed
265

266
267
    # ---Powerspectral methods---

Theo Steininger's avatar
Theo Steininger committed
268
269
270
    def power_analyze(self, spaces=None, logarithmic=False, nbin=None,
                      binbounds=None, decompose_power=True):
        """ Computes the powerspectrum for a subspace of the Field.
Theo Steininger's avatar
Theo Steininger committed
271

Theo Steininger's avatar
Theo Steininger committed
272
273
274
275
        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
        harmonic space.
276
277
278

        Parameters
        ----------
Theo Steininger's avatar
Theo Steininger committed
279
280
281
282
283
284
        spaces : int *optional*
            The subspace for which the powerspectrum shall be computed
            (default : None).
            if spaces==None : Tries to synthesize for the whole domain
        logarithmic : boolean *optional*
            True if the output PowerSpace should use logarithmic binning.
285
            {default : False}
Theo Steininger's avatar
Theo Steininger committed
286
287
288
289
290
291
292
293
294
295
296
297
        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).
            if binbounds==None : bins are inferred. Overwrites nbins and log
        decompose_power : boolean, *optional*
            Whether the analysed signal-space Field is intrinsically real or
            complex and if the power spectrum shall therefore be computed
            for the real and the imaginary part of the Field separately
            (default : True).
Theo Steininger's avatar
Theo Steininger committed
298

299
300
301
302
        Raise
        -----
        ValueError
            Raised if
Theo Steininger's avatar
Theo Steininger committed
303
304
                *len(domain) is != 1 when spaces==None
                *len(spaces) is != 1 if not None
305
                *the analyzed space is not harmonic
Theo Steininger's avatar
Theo Steininger committed
306

307
308
        Returns
        -------
Theo Steininger's avatar
Theo Steininger committed
309
        out : Field
310
311
312
313
314
315
            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
316

317
        """
Theo Steininger's avatar
Theo Steininger committed
318

Theo Steininger's avatar
Theo Steininger committed
319
        # check if all spaces in `self.domain` are either harmonic or
320
321
322
        # power_space instances
        for sp in self.domain:
            if not sp.harmonic and not isinstance(sp, PowerSpace):
Theo Steininger's avatar
Theo Steininger committed
323
                self.logger.info(
324
                    "Field has a space in `domain` which is neither "
325
326
327
                    "harmonic nor a PowerSpace.")

        # check if the `spaces` input is valid
328
329
330
331
332
        spaces = utilities.cast_axis_to_tuple(spaces, len(self.domain))
        if spaces is None:
            if len(self.domain) == 1:
                spaces = (0,)
            else:
333
334
335
                raise ValueError(
                    "Field has multiple spaces as domain "
                    "but `spaces` is None.")
336
337

        if len(spaces) == 0:
338
339
            raise ValueError(
                "No space for analysis specified.")
340
        elif len(spaces) > 1:
341
342
            raise ValueError(
                "Conversion of only one space at a time is allowed.")
343
344
345
346

        space_index = spaces[0]

        if not self.domain[space_index].harmonic:
347
348
            raise ValueError(
                "The analyzed space must be harmonic.")
349

350
351
352
353
354
355
        # 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.

356
357
358
359
        distribution_strategy = \
            self.val.get_axes_local_distribution_strategy(
                self.domain_axes[space_index])

360
        harmonic_domain = self.domain[space_index]
361
        power_domain = PowerSpace(harmonic_partner=harmonic_domain,
362
                                  distribution_strategy=distribution_strategy,
Theo Steininger's avatar
Theo Steininger committed
363
364
                                  logarithmic=logarithmic, nbin=nbin,
                                  binbounds=binbounds)
365

366
        # extract pindex and rho from power_domain
367
368
        pindex = power_domain.pindex
        rho = power_domain.rho
369

Theo Steininger's avatar
Theo Steininger committed
370
        if decompose_power:
371
            hermitian_part, anti_hermitian_part = \
372
                harmonic_domain.hermitian_decomposition(
373
374
375
376
377
378
379
380
381
382
383
384
385
386
                                            self.val,
                                            axes=self.domain_axes[space_index])

            [hermitian_power, anti_hermitian_power] = \
                [self._calculate_power_spectrum(
                                            x=part,
                                            pindex=pindex,
                                            rho=rho,
                                            axes=self.domain_axes[space_index])
                 for part in [hermitian_part, anti_hermitian_part]]

            power_spectrum = hermitian_power + 1j * anti_hermitian_power
        else:
            power_spectrum = self._calculate_power_spectrum(
387
388
389
390
391
392
393
394
395
                                            x=self.val,
                                            pindex=pindex,
                                            rho=rho,
                                            axes=self.domain_axes[space_index])

        # create the result field and put power_spectrum into it
        result_domain = list(self.domain)
        result_domain[space_index] = power_domain

Theo Steininger's avatar
Theo Steininger committed
396
        if decompose_power:
397
398
399
400
            result_dtype = np.complex
        else:
            result_dtype = np.float

401
402
        result_field = self.copy_empty(
                   domain=result_domain,
403
                   dtype=result_dtype,
404
                   distribution_strategy=power_spectrum.distribution_strategy)
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
        result_field.set_val(new_val=power_spectrum, copy=False)

        return result_field

    def _calculate_power_spectrum(self, x, pindex, rho, axes=None):
        fieldabs = abs(x)
        fieldabs **= 2

        if axes is not None:
            pindex = self._shape_up_pindex(
                                    pindex=pindex,
                                    target_shape=x.shape,
                                    target_strategy=x.distribution_strategy,
                                    axes=axes)
        power_spectrum = pindex.bincount(weights=fieldabs,
                                         axis=axes)
        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

        power_spectrum **= 0.5
        return power_spectrum

    def _shape_up_pindex(self, pindex, target_shape, target_strategy, axes):
        if pindex.distribution_strategy not in \
                DISTRIBUTION_STRATEGIES['global']:
433
            raise ValueError("pindex's distribution strategy must be "
434
435
436
437
438
439
                             "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(
440
                    "A slicing distributor shall not be reshaped to "
441
442
443
444
445
446
447
448
449
450
451
452
453
                    "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

454
455
    def power_synthesize(self, spaces=None, real_power=True, real_signal=True,
                         mean=None, std=None):
Theo Steininger's avatar
Theo Steininger committed
456
        """ Converts a power spectrum into a random field realization.
Theo Steininger's avatar
Theo Steininger committed
457

Theo Steininger's avatar
Theo Steininger committed
458
459
        This method draws a Gaussian random field in the harmic partner domain
        of a PowerSpace.
Theo Steininger's avatar
Theo Steininger committed
460

461
462
        Notes
        -----
Theo Steininger's avatar
Theo Steininger committed
463
        For this the spaces specified by `spaces` must be a PowerSpaces.
Theo Steininger's avatar
Theo Steininger committed
464

465
466
467
        Parameters
        ----------
        spaces : {tuple, int, None} *optional*
Theo Steininger's avatar
Theo Steininger committed
468
469
470
            Specifies the subspace containing all the PowerSpaces which
            should be converted (default : None).
            if spaces==None : Tries to convert the whole domain.
471
        real_power : boolean *optional*
Theo Steininger's avatar
Theo Steininger committed
472
473
            Determines whether the power spectrum is treated as intrinsically
            real or complex (default : True).
474
        real_signal : boolean *optional*
Theo Steininger's avatar
Theo Steininger committed
475
476
477
478
479
480
            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
481
        std : float *optional*
Theo Steininger's avatar
Theo Steininger committed
482
483
            The standard deviation of the Gaussian noise field which is used
            for the Field synthetization (default : None).
484
            {default : None}
Theo Steininger's avatar
Theo Steininger committed
485
            if std==None : std will be set to 1
Theo Steininger's avatar
Theo Steininger committed
486

487
488
489
490
        Returns
        -------
        out : Field
            The output object. A random field created with the power spectrum
Theo Steininger's avatar
Theo Steininger committed
491
            stored in the `spaces` in `self`.
492
493
494
495

        See Also
        --------
        power_analyze
496

497
        """
Theo Steininger's avatar
Theo Steininger committed
498

499
500
501
        # check if the `spaces` input is valid
        spaces = utilities.cast_axis_to_tuple(spaces, len(self.domain))

Theo Steininger's avatar
Theo Steininger committed
502
503
504
        if spaces is None:
            spaces = range(len(self.domain))

505
506
507
508
509
        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.")
510
511
512

        # create the result domain
        result_domain = list(self.domain)
513
514
        for power_space_index in spaces:
            power_space = self.domain[power_space_index]
515
            harmonic_domain = power_space.harmonic_partner
516
            result_domain[power_space_index] = harmonic_domain
517
518
519

        # create random samples: one or two, depending on whether the
        # power spectrum is real or complex
520
        if real_power:
521
            result_list = [None]
522
523
        else:
            result_list = [None, None]
524

525
526
        result_list = [self.__class__.from_random(
                             'normal',
527
528
529
                             mean=mean,
                             std=std,
                             domain=result_domain,
530
                             dtype=np.complex,
531
                             distribution_strategy=self.distribution_strategy)
532
533
534
535
536
537
                       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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555

        spec = self.val.get_full_data()
        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)

556
        if real_signal:
557
            for power_space_index in spaces:
558
559
                harmonic_domain = result_domain[power_space_index]
                result_val_list = [harmonic_domain.hermitian_decomposition(
560
561
562
563
564
                                    result_val,
                                    axes=result.domain_axes[power_space_index],
                                    preserve_gaussian_variance=True)[0]
                                   for (result, result_val)
                                   in zip(result_list, result_val_list)]
565
566
567
568
569
570
571

        # 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]
572
        else:
573
574
575
576
577
578
            result = result_list[0] + 1j*result_list[1]

        return result

    def _spec_to_rescaler(self, spec, result_list, power_space_index):
        power_space = self.domain[power_space_index]
579
580
581

        # weight the random fields with the power spectrum
        # therefore get the pindex from the power space
582
        pindex = power_space.pindex
583
584
585
586
587
588
589
        # 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:
590
            self.logger.warn(
591
                "The distribution_stragey of pindex does not fit the "
592
593
594
595
596
597
598
599
600
601
                "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)

        local_blow_up = [slice(None)]*len(self.shape)
        local_blow_up[self.domain_axes[power_space_index][0]] = local_pindex
        # here, the power_spectrum is distributed into the new shape
602
603
        local_rescaler = spec[local_blow_up]
        return local_rescaler
604

Theo Steininger's avatar
Theo Steininger committed
605
    # ---Properties---
606

Theo Steininger's avatar
Theo Steininger committed
607
    def set_val(self, new_val=None, copy=False):
Theo Steininger's avatar
Theo Steininger committed
608
        """ Sets the fields distributed_data_object.
609
610
611

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

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

        """
Theo Steininger's avatar
Theo Steininger committed
625

626
627
        new_val = self.cast(new_val)
        if copy:
Theo Steininger's avatar
Theo Steininger committed
628
629
            new_val = new_val.copy()
        self._val = new_val
630
        return self
csongor's avatar
csongor committed
631

632
    def get_val(self, copy=False):
Theo Steininger's avatar
Theo Steininger committed
633
        """ Returns the distributed_data_object associated with this Field.
634
635
636
637

        Parameters
        ----------
        copy : boolean
Theo Steininger's avatar
Theo Steininger committed
638
639
            If true, a copy of the Field's underlying distributed_data_object
            is returned.
Theo Steininger's avatar
Theo Steininger committed
640

641
642
643
644
645
646
647
648
649
        Returns
        -------
        out : distributed_data_object

        See Also
        --------
        val

        """
Theo Steininger's avatar
Theo Steininger committed
650

651
652
653
        if self._val is None:
            self.set_val(None)

654
        if copy:
Theo Steininger's avatar
Theo Steininger committed
655
            return self._val.copy()
656
        else:
Theo Steininger's avatar
Theo Steininger committed
657
            return self._val
csongor's avatar
csongor committed
658

Theo Steininger's avatar
Theo Steininger committed
659
660
    @property
    def val(self):
Theo Steininger's avatar
Theo Steininger committed
661
        """ Returns the distributed_data_object associated with this Field.
Theo Steininger's avatar
Theo Steininger committed
662

663
664
665
666
667
668
669
670
671
        Returns
        -------
        out : distributed_data_object

        See Also
        --------
        get_val

        """
Theo Steininger's avatar
Theo Steininger committed
672

673
        return self.get_val(copy=False)
csongor's avatar
csongor committed
674

Theo Steininger's avatar
Theo Steininger committed
675
676
    @val.setter
    def val(self, new_val):
677
        self.set_val(new_val=new_val, copy=False)
csongor's avatar
csongor committed
678

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

683
684
685
686
687
688
689
690
691
692
693
        Returns
        -------
        out : tuple
            The output object. The tuple contains the dimansions of the spaces
            in domain.

        See Also
        --------
        dim

        """
Theo Steininger's avatar
Theo Steininger committed
694

695
        shape_tuple = tuple(sp.shape for sp in self.domain)
696
697
698
699
        try:
            global_shape = reduce(lambda x, y: x + y, shape_tuple)
        except TypeError:
            global_shape = ()
csongor's avatar
csongor committed
700

701
        return global_shape
csongor's avatar
csongor committed
702

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

Theo Steininger's avatar
Theo Steininger committed
707
        Effectively, all values from shape are multiplied.
Theo Steininger's avatar
Theo Steininger committed
708

709
710
711
712
713
714
715
716
717
718
        Returns
        -------
        out : int
            The dimension of the Field.

        See Also
        --------
        shape

        """
Theo Steininger's avatar
Theo Steininger committed
719

720
        dim_tuple = tuple(sp.dim for sp in self.domain)
Theo Steininger's avatar
Theo Steininger committed
721
722
723
724
        try:
            return reduce(lambda x, y: x * y, dim_tuple)
        except TypeError:
            return 0
csongor's avatar
csongor committed
725

726
727
    @property
    def dof(self):
Theo Steininger's avatar
Theo Steininger committed
728
729
730
731
732
733
        """ 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
734
735
736
737
738
739
740
        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
741
742
743
        """ Returns the total volume of all spaces in the domain.
        """

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

Theo Steininger's avatar
Theo Steininger committed
750
    # ---Special unary/binary operations---
751

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

755
756
        Parameters
        ----------
Theo Steininger's avatar
Theo Steininger committed
757
        x : scalar, d2o, Field, array_like
758
759
            The input that shall be casted on a d2o of the same shape like the
            domain.
Theo Steininger's avatar
Theo Steininger committed
760

761
        dtype : type
Theo Steininger's avatar
Theo Steininger committed
762
763
            The datatype the output shall have. This can be used to override
            the fields dtype.
Theo Steininger's avatar
Theo Steininger committed
764

765
766
767
768
769
770
771
772
773
774
        Returns
        -------
        out : distributed_data_object
            The output object.

        See Also
        --------
        _actual_cast

        """
csongor's avatar
csongor committed
775
776
        if dtype is None:
            dtype = self.dtype
777
778
        else:
            dtype = np.dtype(dtype)
779

780
781
        casted_x = x

782
        for ind, sp in enumerate(self.domain):
783
            casted_x = sp.pre_cast(casted_x,
784
785
786
                                   axes=self.domain_axes[ind])

        casted_x = self._actual_cast(casted_x, dtype=dtype)
787
788

        for ind, sp in enumerate(self.domain):
789
790
            casted_x = sp.post_cast(casted_x,
                                    axes=self.domain_axes[ind])
791

792
        return casted_x
csongor's avatar
csongor committed
793

Theo Steininger's avatar
Theo Steininger committed
794
    def _actual_cast(self, x, dtype=None):
795
        if isinstance(x, Field):
csongor's avatar
csongor committed
796
797
798
799
800
            x = x.get_val()

        if dtype is None:
            dtype = self.dtype

801
        return_x = distributed_data_object(
802
803
804
                            global_shape=self.shape,
                            dtype=dtype,
                            distribution_strategy=self.distribution_strategy)
805
806
        return_x.set_full_data(x, copy=False)
        return return_x
Theo Steininger's avatar
Theo Steininger committed
807

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

811
812
813
814
815
816
817
818
819
        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
820

821
822
        dtype : type
            The new dtype the Field shall have.
Theo Steininger's avatar
Theo Steininger committed
823

824
        distribution_strategy : all supported distribution strategies
Theo Steininger's avatar
Theo Steininger committed
825
826
            The new distribution strategy the Field shall have.

827
828
829
830
831
832
833
834
835
836
        Returns
        -------
        out : Field
            The output object. An identical copy of 'self'.

        See Also
        --------
        copy_empty

        """
Theo Steininger's avatar
Theo Steininger committed
837

Theo Steininger's avatar
Theo Steininger committed
838
        copied_val = self.get_val(copy=True)
839
840
841
842
        new_field = self.copy_empty(
                                domain=domain,
                                dtype=dtype,
                                distribution_strategy=distribution_strategy)
Theo Steininger's avatar
Theo Steininger committed
843
844
        new_field.set_val(new_val=copied_val, copy=False)
        return new_field
csongor's avatar
csongor committed
845

846
    def copy_empty(self, domain=None, dtype=None, distribution_strategy=None):
847
848
849
        """ 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
850
851
852
853
854
        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
855

856
857
858
859
        Parameters
        ----------
        domain : DomainObject
            The new domain the Field shall have.
Theo Steininger's avatar
Theo Steininger committed
860

861
862
        dtype : type
            The new dtype the Field shall have.
Theo Steininger's avatar
Theo Steininger committed
863

Theo Steininger's avatar
Theo Steininger committed
864
        distribution_strategy : string, all supported distribution strategies
865
            The distribution strategy the new Field should have.
Theo Steininger's avatar
Theo Steininger committed
866

867
868
869
        Returns
        -------
        out : Field
Theo Steininger's avatar
Theo Steininger committed
870
            The output object.
871
872
873
874
875
876

        See Also
        --------
        copy

        """
Theo Steininger's avatar
Theo Steininger committed
877

Theo Steininger's avatar
Theo Steininger committed
878
879
        if domain is None:
            domain = self.domain
csongor's avatar
csongor committed
880
        else:
Theo Steininger's avatar
Theo Steininger committed
881
            domain = self._parse_domain(domain)
csongor's avatar
csongor committed
882

Theo Steininger's avatar
Theo Steininger committed
883
884
885
886
        if dtype is None:
            dtype = self.dtype
        else:
            dtype = np.dtype(dtype)
csongor's avatar
csongor committed
887

888
889
        if distribution_strategy is None:
            distribution_strategy = self.distribution_strategy
csongor's avatar
csongor committed
890

Theo Steininger's avatar
Theo Steininger committed
891
892
893
894
895
896
897
898
899
900
        fast_copyable = True
        try:
            for i in xrange(len(self.domain)):
                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
901
                distribution_strategy == self.distribution_strategy):
Theo Steininger's avatar
Theo Steininger committed
902
903
904
905
            new_field = self._fast_copy_empty()
        else:
            new_field = Field(domain=domain,
                              dtype=dtype,
906
                              distribution_strategy=distribution_strategy)
Theo Steininger's avatar
Theo Steininger committed
907
        return new_field
csongor's avatar
csongor committed
908

Theo Steininger's avatar
Theo Steininger committed
909
910
911
912
913
914
915
    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
        for key, value in self.__dict__.items():
916
            if key != '_val':
Theo Steininger's avatar
Theo Steininger committed
917
918
919
920
921
922
                new_field.__dict__[key] = value
            else:
                new_field.__dict__[key] = self.val.copy_empty()
        return new_field

    def weight(self, power=1, inplace=False, spaces=None):
Theo Steininger's avatar
Theo Steininger committed
923
        """ Weights the pixels of `self` with their invidual pixel-volume.
924
925
926
927

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

930
        inplace : boolean
Theo Steininger's avatar
Theo Steininger committed
931
932
            If True, `self` will be weighted and returned. Otherwise, a copy
            is made.
Theo Steininger's avatar
Theo Steininger committed
933

Theo Steininger's avatar
Theo Steininger committed
934
935
        spaces : tuple of ints
            Determines on which subspace the operation takes place.
Theo Steininger's avatar
Theo Steininger committed
936

937
938
939
        Returns
        -------
        out : Field
Theo Steininger's avatar
Theo Steininger committed
940
            The weighted field.
941
942

        """
943
        if inplace:
csongor's avatar
csongor committed
944
945
946
947
            new_field = self
        else:
            new_field = self.copy_empty()

948
        new_val = self.get_val(copy=False)
csongor's avatar
csongor committed
949

950
        spaces = utilities.cast_axis_to_tuple(spaces, len(self.domain))
csongor's avatar
csongor committed
951
        if spaces is None:
Theo Steininger's avatar
Theo Steininger committed
952
            spaces = range(len(self.domain))
csongor's avatar
csongor committed
953

954
        for ind, sp in enumerate(self.domain):
Theo Steininger's avatar
Theo Steininger committed
955
956
957
958
959
            if ind in spaces:
                new_val = sp.weight(new_val,
                                    power=power,
                                    axes=self.domain_axes[ind],
                                    inplace=inplace)
960
961

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

964
    def dot(self, x=None, spaces=None, bare=False):
Theo Steininger's avatar
Theo Steininger committed
965
        """ Computes the volume-factor-aware dot product of 'self' with x.
Theo Steininger's avatar
Theo Steininger committed
966

967
968
969
        Parameters
        ----------
        x : Field
Theo Steininger's avatar
Theo Steininger committed
970
            The domain of x must contain `self.domain`
Theo Steininger's avatar
Theo Steininger committed
971

Theo Steininger's avatar
Theo Steininger committed
972
973
974
        spaces : tuple of ints
            If the domain of `self` and `x` are not the same, `spaces` specfies
            the mapping.
Theo Steininger's avatar
Theo Steininger committed
975

976
        bare : boolean
Theo Steininger's avatar
Theo Steininger committed
977
            If true, no volume factors will be included in the computation.
Theo Steininger's avatar
Theo Steininger committed
978

979
980
981
        Returns
        -------
        out : float, complex
Theo Steininger's avatar
Theo Steininger committed
982

983
        """
984
985
986
        if not isinstance(x, Field):
            raise ValueError("The dot-partner must be an instance of " +
                             "the NIFTy field class")
Theo Steininger's avatar
Theo Steininger committed
987

Martin Reinecke's avatar
Martin Reinecke committed
988
        # Compute the dot respecting the fact of discrete/continuous spaces
Theo Steininger's avatar
Theo Steininger committed
989
990
991
992
993
        if bare:
            y = self
        else:
            y = self.weight(power=1)

994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
        if spaces is None:
            x_val = x.get_val(copy=False)
            y_val = y.get_val(copy=False)
            result = (x_val.conjugate() * y_val).sum()
            return result
        else:
            # create a diagonal operator which is capable of taking care of the
            # axes-matching
            from nifty.operators.diagonal_operator import DiagonalOperator
            diagonal = y.val.conjugate()
            diagonalOperator = DiagonalOperator(domain=y.domain,
                                                diagonal=diagonal,
                                                copy=False)
            dotted = diagonalOperator(x, spaces=spaces)
            return dotted.sum(spaces=spaces)
Theo Steininger's avatar
Theo Steininger committed
1009

1010
    def norm(self, q=2):
1011
        """ Computes the Lq-norm of the field values.
csongor's avatar
csongor committed
1012

Theo Steininger's avatar
Theo Steininger committed
1013
1014
1015
1016
        Parameters
        ----------
        q : scalar
            Parameter q of the Lq-norm (default: 2).
csongor's avatar
csongor committed
1017

Theo Steininger's avatar
Theo Steininger committed
1018
1019
1020
1021
        Returns
        -------
        norm : scalar
            The Lq-norm of the field values.
csongor's avatar
csongor committed
1022
1023

        """
Theo Steininger's avatar
Theo Steininger committed
1024

1025
        if q == 2:
1026
            return (self.dot(x=self)) ** (1 / 2)
csongor's avatar
csongor committed
1027
        else:
1028
            return self.dot(x=self ** (q - 1)) ** (1 / q)
csongor's avatar
csongor committed
1029
1030

    def conjugate(self, inplace=False):
1031
        """ Retruns the complex conjugate of the field.
Theo Steininger's avatar
Theo Steininger committed
1032

1033
1034
1035
        Parameters
        ----------
        inplace : boolean
Theo Steininger's avatar
Theo Steininger committed
1036
            Decides whether the conjugation should be performed inplace.
Theo Steininger's avatar
Theo Steininger committed
1037

1038
1039
1040
1041
        Returns
        -------
        cc : field
            The complex conjugated field.
csongor's avatar
csongor committed
1042
1043

        """
Theo Steininger's avatar
Theo Steininger committed
1044

csongor's avatar
csongor committed
1045
1046
1047
1048
1049
        if inplace:
            work_field = self
        else:
            work_field = self.copy_empty()

1050
        new_val = self.get_val(copy=False)
Theo Steininger's avatar
Theo Steininger committed
1051
        new_val = new_val.conjugate()
1052
        work_field.set_val(new_val=new_val, copy=False)
csongor's avatar
csongor committed
1053
1054
1055

        return work_field

Theo Steininger's avatar
Theo Steininger committed
1056
    # ---General unary/contraction methods---
1057

Theo Steininger's avatar
Theo Steininger committed
1058
    def __pos__(self):
1059
1060
1061
        """ x.__pos__() <==> +x

        Returns a (positive) copy of `self`.
Theo Steininger's avatar
Theo Steininger committed
1062

1063
        """
Theo Steininger's avatar
Theo Steininger committed
1064

Theo Steininger's avatar
Theo Steininger committed
1065
        return self.copy()