field.py 30.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
Theo Steininger's avatar
Theo Steininger committed
13
14
15
16
17
#
# Copyright(C) 2013-2017 Max-Planck-Society
#
# NIFTy is being developed at the Max-Planck-Institut fuer Astrophysik
# and financially supported by the Studienstiftung des deutschen Volkes.
18

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

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

Martin Reinecke's avatar
Martin Reinecke committed
26
from .domain_object import DomainObject
27

Martin Reinecke's avatar
Martin Reinecke committed
28
from .spaces.power_space import PowerSpace
csongor's avatar
csongor committed
29

Martin Reinecke's avatar
Martin Reinecke committed
30
31
from . import nifty_utilities as utilities
from .random import Random
Martin Reinecke's avatar
Martin Reinecke committed
32
from functools import reduce
33

csongor's avatar
csongor committed
34

Martin Reinecke's avatar
Martin Reinecke committed
35
class Field(object):
Theo Steininger's avatar
Theo Steininger committed
36
37
38
    """ The discrete representation of a continuous field over multiple spaces.

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

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

Martin Reinecke's avatar
stage1    
Martin Reinecke committed
49
    val : scalar, numpy.ndarray, Field
50
51
52
        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
53

54
    dtype : type
Martin Reinecke's avatar
updates    
Martin Reinecke committed
55
        A numpy.type. Most common are float and complex.
Theo Steininger's avatar
Theo Steininger committed
56

57
58
59
60
    copy: boolean

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

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

70
71
72
73
74
75
76
    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
77

78
    """
79

Theo Steininger's avatar
Theo Steininger committed
80
    # ---Initialization methods---
81

Martin Reinecke's avatar
stage1    
Martin Reinecke committed
82
    def __init__(self, domain=None, val=None, dtype=None, copy=False):
83
        self.domain = self._parse_domain(domain=domain, val=val)
84
        self.domain_axes = self._get_axes_tuple(self.domain)
85

Martin Reinecke's avatar
Martin Reinecke committed
86
87
88
        shape_tuple = tuple(sp.shape for sp in self.domain)
        if len(shape_tuple)==0:
            global_shape = ()
89
        else:
Martin Reinecke's avatar
Martin Reinecke committed
90
91
            global_shape = reduce(lambda x, y: x + y, shape_tuple)
        dtype = self._infer_dtype(dtype=dtype, val=val)
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
        if isinstance(val, Field):
            if self.domain!=val.domain:
                raise ValueError("Domain mismatch")
            self._val = np.array(val.val,dtype=dtype,copy=copy)
        elif (np.isscalar(val)):
            self._val=np.full(global_shape,dtype=dtype,fill_value=val)
        elif isinstance(val, np.ndarray):
            if global_shape==val.shape:
                self._val = np.array(val,dtype=dtype,copy=copy)
            else:
                raise ValueError("Shape mismatch")
        elif val is None:
            self._val = np.empty(global_shape,dtype=dtype)
        else:
            raise TypeError("unknown source type")
csongor's avatar
csongor committed
107

108
    def _parse_domain(self, domain, val=None):
109
        if domain is None:
110
111
            if isinstance(val, Field):
                domain = val.domain
Martin Reinecke's avatar
Martin Reinecke committed
112
            elif np.isscalar(val):
113
                domain = ()
Martin Reinecke's avatar
Martin Reinecke committed
114
115
            else:
                raise TypeError("could not infer domain from value")
116
        elif isinstance(domain, DomainObject):
117
            domain = (domain,)
118
119
120
        elif not isinstance(domain, tuple):
            domain = tuple(domain)

csongor's avatar
csongor committed
121
        for d in domain:
122
            if not isinstance(d, DomainObject):
123
124
                raise TypeError(
                    "Given domain contains something that is not a "
125
                    "DomainObject instance.")
csongor's avatar
csongor committed
126
127
        return domain

128
129
    def _get_axes_tuple(self, things_with_shape):
        i = 0
Theo Steininger's avatar
Theo Steininger committed
130
131
        axes_list = []
        for thing in things_with_shape:
132
133
134
            nax = len(thing.shape)
            axes_list += [tuple(range(i,i+nax))]
            i += nax
Theo Steininger's avatar
Theo Steininger committed
135
        return tuple(axes_list)
136

137
    def _infer_dtype(self, dtype, val):
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
138
139
        if val is None:
            return np.float64 if dtype is None else dtype
csongor's avatar
csongor committed
140
        if dtype is None:
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
141
142
143
            if isinstance(val,Field):
                return val.dtype
            return np.result_type(val)
144

145
    # ---Factory methods---
146

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

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

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

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

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

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

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

174
175

        """
Theo Steininger's avatar
Theo Steininger committed
176

Martin Reinecke's avatar
stage1    
Martin Reinecke committed
177
        f = cls(domain=domain, dtype=dtype)
178
        generator_function = getattr(Random, random_type)
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
179
        f.val=generator_function(dtype=f.dtype, shape=f.shape, **kwargs)
180
181
        return f

182
183
    # ---Powerspectral methods---

Martin Reinecke's avatar
Martin Reinecke committed
184
185
    def power_analyze(self, spaces=None, binbounds=None,
                      keep_phase_information=False):
Theo Steininger's avatar
Theo Steininger committed
186
        """ Computes the square root power spectrum for a subspace of `self`.
Theo Steininger's avatar
Theo Steininger committed
187

Theo Steininger's avatar
Theo Steininger committed
188
189
190
        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
191
        harmonic space. The resulting field has the same units as the initial
Theo Steininger's avatar
Theo Steininger committed
192
        field, corresponding to the square root of the power spectrum.
193
194
195

        Parameters
        ----------
Theo Steininger's avatar
Theo Steininger committed
196
197
198
199
200
        spaces : int *optional*
            The subspace for which the powerspectrum shall be computed
            (default : None).
        binbounds : array-like *optional*
            Inner bounds of the bins (default : None).
Martin Reinecke's avatar
Martin Reinecke committed
201
            if binbounds==None : bins are inferred.
202
203
204
205
206
207
208
209
210
211
        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
212

213
214
215
216
        Raise
        -----
        ValueError
            Raised if
Theo Steininger's avatar
Theo Steininger committed
217
218
                *len(domain) is != 1 when spaces==None
                *len(spaces) is != 1 if not None
219
                *the analyzed space is not harmonic
Theo Steininger's avatar
Theo Steininger committed
220

221
222
        Returns
        -------
Theo Steininger's avatar
Theo Steininger committed
223
        out : Field
Martin Reinecke's avatar
Martin Reinecke committed
224
            The output object. Its domain is a PowerSpace and it contains
225
226
227
228
229
            the power spectrum of 'self's field.

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

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

Theo Steininger's avatar
Theo Steininger committed
233
        # check if all spaces in `self.domain` are either harmonic or
234
235
236
        # power_space instances
        for sp in self.domain:
            if not sp.harmonic and not isinstance(sp, PowerSpace):
Martin Reinecke's avatar
Martin Reinecke committed
237
                raise TypeError(
238
                    "Field has a space in `domain` which is neither "
239
240
241
                    "harmonic nor a PowerSpace.")

        # check if the `spaces` input is valid
242
243
        spaces = utilities.cast_axis_to_tuple(spaces, len(self.domain))
        if spaces is None:
Martin Reinecke's avatar
Martin Reinecke committed
244
            spaces = list(range(len(self.domain)))
245
246

        if len(spaces) == 0:
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
247
            raise ValueError("No space for analysis specified.")
248

249
250
251
252
253
254
255
256
257
258
        if keep_phase_information:
            parts_val = self._hermitian_decomposition(
                                              val=self.val,
                                              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]
259
260

        for space_index in spaces:
261
262
            parts = [self._single_power_analyze(
                                work_field=part,
263
                                space_index=space_index,
264
265
                                binbounds=binbounds)
                     for part in parts]
266

267
        if keep_phase_information:
Martin Reinecke's avatar
updates    
Martin Reinecke committed
268
            return parts[0] + 1j*parts[1]
269
        else:
Martin Reinecke's avatar
updates    
Martin Reinecke committed
270
            return parts[0]
271
272

    @classmethod
Martin Reinecke's avatar
Martin Reinecke committed
273
    def _single_power_analyze(cls, work_field, space_index, binbounds):
274

275
        if not work_field.domain[space_index].harmonic:
276
277
            raise ValueError(
                "The analyzed space must be harmonic.")
278

279
280
281
282
283
284
        # 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.

285
        harmonic_domain = work_field.domain[space_index]
286
        power_domain = PowerSpace(harmonic_partner=harmonic_domain,
Theo Steininger's avatar
Theo Steininger committed
287
                                  binbounds=binbounds)
288
289
        power_spectrum = cls._calculate_power_spectrum(
                                field_val=work_field.val,
Martin Reinecke's avatar
Martin Reinecke committed
290
                                pdomain=power_domain,
291
                                axes=work_field.domain_axes[space_index])
292
293

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

Martin Reinecke's avatar
updates    
Martin Reinecke committed
297
298
        return Field(domain=result_domain,val=power_spectrum,
                     dtype=power_spectrum.dtype)
299

300
    @classmethod
Martin Reinecke's avatar
Martin Reinecke committed
301
    def _calculate_power_spectrum(cls, field_val, pdomain, axes=None):
302

Martin Reinecke's avatar
Martin Reinecke committed
303
        pindex = pdomain.pindex
304
        if axes is not None:
305
306
307
308
            pindex = cls._shape_up_pindex(
                            pindex=pindex,
                            target_shape=field_val.shape,
                            axes=axes)
Theo Steininger's avatar
Theo Steininger committed
309

Martin Reinecke's avatar
Martin Reinecke committed
310
        power_spectrum = utilities.bincount_axis(pindex, weights=field_val,
311
                                         axis=axes)
Martin Reinecke's avatar
Martin Reinecke committed
312
        rho = pdomain.rho
313
314
315
316
317
318
319
320
        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

321
    @staticmethod
Martin Reinecke's avatar
Martin Reinecke committed
322
    def _shape_up_pindex(pindex, target_shape, axes):
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
323
        semiscaled_local_shape = [1] * len(target_shape)
Theo Steininger's avatar
Theo Steininger committed
324
        for i in range(len(axes)):
Martin Reinecke's avatar
Martin Reinecke committed
325
            semiscaled_local_shape[axes[i]] = pindex.shape[i]
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
326
        semiscaled_local_data = pindex.reshape(semiscaled_local_shape)
Martin Reinecke's avatar
Martin Reinecke committed
327
        result_obj = np.empty(target_shape, dtype=pindex.dtype)
328
        result_obj[()] = semiscaled_local_data
329
330
        return result_obj

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

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

338
339
340
        Parameters
        ----------
        spaces : {tuple, int, None} *optional*
Theo Steininger's avatar
Theo Steininger committed
341
342
343
            Specifies the subspace containing all the PowerSpaces which
            should be converted (default : None).
            if spaces==None : Tries to convert the whole domain.
344
        real_power : boolean *optional*
Theo Steininger's avatar
Theo Steininger committed
345
346
            Determines whether the power spectrum is treated as intrinsically
            real or complex (default : True).
347
        real_signal : boolean *optional*
Theo Steininger's avatar
Theo Steininger committed
348
349
350
351
352
353
            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
354
        std : float *optional*
Theo Steininger's avatar
Theo Steininger committed
355
356
357
            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
358

359
360
361
362
        Returns
        -------
        out : Field
            The output object. A random field created with the power spectrum
Theo Steininger's avatar
Theo Steininger committed
363
            stored in the `spaces` in `self`.
364

Theo Steininger's avatar
Theo Steininger committed
365
366
367
368
369
370
        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.

371
372
373
        See Also
        --------
        power_analyze
Theo Steininger's avatar
Theo Steininger committed
374
375
376
377
378

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

379
        """
Theo Steininger's avatar
Theo Steininger committed
380

381
382
        # check if the `spaces` input is valid
        spaces = utilities.cast_axis_to_tuple(spaces, len(self.domain))
Theo Steininger's avatar
Theo Steininger committed
383
        if spaces is None:
Martin Reinecke's avatar
Martin Reinecke committed
384
            spaces = list(range(len(self.domain)))
Theo Steininger's avatar
Theo Steininger committed
385

386
387
388
389
390
        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.")
391
392
393

        # create the result domain
        result_domain = list(self.domain)
394
395
        for power_space_index in spaces:
            power_space = self.domain[power_space_index]
396
            harmonic_domain = power_space.harmonic_partner
397
            result_domain[power_space_index] = harmonic_domain
398
399
400

        # create random samples: one or two, depending on whether the
        # power spectrum is real or complex
401
402
        result_list = [self.__class__.from_random(
                             'normal',
403
404
405
                             mean=mean,
                             std=std,
                             domain=result_domain,
Martin Reinecke's avatar
stage1    
Martin Reinecke committed
406
                             dtype=np.complex)
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
407
                       for x in range(1 if real_power else 2)]
408
409
410
411
412

        # 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
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
413
        spec = np.sqrt(self.val)
414
        for power_space_index in spaces:
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
415
            spec = self._spec_to_rescaler(spec, power_space_index)
416
417

        # apply the rescaler to the random fields
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
418
        result_list[0].val *= spec.real
419
        if not real_power:
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
420
            result_list[1].val *= spec.imag
421

422
        if real_signal:
Martin Reinecke's avatar
Martin Reinecke committed
423
424
425
426
            result_list=[Field(i.domain,self._hermitian_decomposition(
                                     i.val,
                                     preserve_gaussian_variance=True)[0])
                         for i in result_list]
427
428
429

        if real_power:
            result = result_list[0]
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
430
            if not issubclass(result_list[0].dtype.type,
431
432
                              np.complexfloating):
                result = result.real
433
        else:
434
435
436
437
            result = result_list[0] + 1j*result_list[1]

        return result

438
    @staticmethod
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
439
    def _hermitian_decomposition(val, preserve_gaussian_variance=False):
440
        if preserve_gaussian_variance:
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
441
442
443
444
445
            if not issubclass(val.dtype.type, np.complexfloating):
                raise TypeError("complex input field is needed here")
            return (val.real*np.sqrt(2.), val.imag*np.sqrt(2.))
        else:
            return (val.real.copy(), val.imag.copy())
446

Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
447
    def _spec_to_rescaler(self, spec, power_space_index):
448
        power_space = self.domain[power_space_index]
449

450
451
452
453
        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)
454
        local_blow_up[index] = power_space.pindex
455
        # here, the power_spectrum is distributed into the new shape
456
        return spec[local_blow_up]
457

Theo Steininger's avatar
Theo Steininger committed
458
    # ---Properties---
459

Theo Steininger's avatar
Theo Steininger committed
460
    def set_val(self, new_val=None, copy=False):
Martin Reinecke's avatar
stage1    
Martin Reinecke committed
461
        """ Sets the field's data object.
462
463
464

        Parameters
        ----------
Theo Steininger's avatar
Theo Steininger committed
465
        new_val : scalar, array-like, Field, None *optional*
466
467
            The values to be stored in the field.
            {default : None}
Theo Steininger's avatar
Theo Steininger committed
468

469
        copy : boolean, *optional*
Theo Steininger's avatar
Theo Steininger committed
470
471
            If False, Field tries to not copy the input data but use it
            directly.
472
473
474
475
476
477
            {default : False}
        See Also
        --------
        val

        """
Theo Steininger's avatar
Theo Steininger committed
478

Martin Reinecke's avatar
Martin Reinecke committed
479
480
481
482
483
484
485
486
        if new_val is None:
            pass
        elif isinstance(new_val, Field):
            if self.domain!=new_val.domain:
                raise ValueError("Domain mismatch")
            if copy:
                self._val[()] = new_val.val
            else:
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
487
                self._val = np.array(new_val.val,dtype=self.dtype,copy=False)
Martin Reinecke's avatar
Martin Reinecke committed
488
489
490
491
492
493
494
495
        elif (np.isscalar(new_val)):
            self._val[()]=new_val
        elif isinstance(new_val, np.ndarray):
            if copy:
                self._val[()] = new_val
            else:
                if self.shape!=new_val.shape:
                    raise ValueError("Shape mismatch")
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
496
                self._val = np.array(new_val,dtype=self.dtype,copy=False)
Martin Reinecke's avatar
Martin Reinecke committed
497
498
        else:
            raise TypeError("unknown source type")
499
        return self
csongor's avatar
csongor committed
500

501
    def get_val(self, copy=False):
Martin Reinecke's avatar
stage1    
Martin Reinecke committed
502
        """ Returns the data object associated with this Field.
503
504
505
506

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

510
511
        Returns
        -------
Martin Reinecke's avatar
stage1    
Martin Reinecke committed
512
        out : numpy.ndarray
513
514
515
516
517
518

        See Also
        --------
        val

        """
Theo Steininger's avatar
Theo Steininger committed
519

Martin Reinecke's avatar
Martin Reinecke committed
520
        return self._val.copy() if copy else self._val
csongor's avatar
csongor committed
521

Theo Steininger's avatar
Theo Steininger committed
522
523
    @property
    def val(self):
Martin Reinecke's avatar
stage1    
Martin Reinecke committed
524
        """ Returns the data object associated with this Field.
Theo Steininger's avatar
Theo Steininger committed
525

526
527
        Returns
        -------
Martin Reinecke's avatar
stage1    
Martin Reinecke committed
528
        out : numpy.ndarray
529
530
531
532
533
534

        See Also
        --------
        get_val

        """
Theo Steininger's avatar
Theo Steininger committed
535

Martin Reinecke's avatar
Martin Reinecke committed
536
        return self._val
csongor's avatar
csongor committed
537

Theo Steininger's avatar
Theo Steininger committed
538
539
    @val.setter
    def val(self, new_val):
540
        self.set_val(new_val=new_val, copy=False)
csongor's avatar
csongor committed
541

Martin Reinecke's avatar
Martin Reinecke committed
542
543
544
545
    @property
    def dtype(self):
        return self._val.dtype

546
547
    @property
    def shape(self):
Theo Steininger's avatar
Theo Steininger committed
548
        """ Returns the total shape of the Field's data array.
Theo Steininger's avatar
Theo Steininger committed
549

550
551
552
        Returns
        -------
        out : tuple
Martin Reinecke's avatar
Martin Reinecke committed
553
            The output object. The tuple contains the dimensions of the spaces
554
555
556
557
558
559
560
            in domain.

        See Also
        --------
        dim

        """
Martin Reinecke's avatar
Martin Reinecke committed
561
        return self._val.shape
csongor's avatar
csongor committed
562

563
564
    @property
    def dim(self):
Theo Steininger's avatar
Theo Steininger committed
565
        """ Returns the total number of pixel-dimensions the field has.
Theo Steininger's avatar
Theo Steininger committed
566

Theo Steininger's avatar
Theo Steininger committed
567
        Effectively, all values from shape are multiplied.
Theo Steininger's avatar
Theo Steininger committed
568

569
570
571
572
573
574
575
576
577
578
        Returns
        -------
        out : int
            The dimension of the Field.

        See Also
        --------
        shape

        """
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
579
        return self._val.size
csongor's avatar
csongor committed
580

581
582
    @property
    def dof(self):
Theo Steininger's avatar
Theo Steininger committed
583
584
585
586
587
588
        """ 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
589
590
591
592
593
594
595
        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
596
597
598
        """ Returns the total volume of all spaces in the domain.
        """

Theo Steininger's avatar
Theo Steininger committed
599
        volume_tuple = tuple(sp.total_volume for sp in self.domain)
600
        try:
Theo Steininger's avatar
Theo Steininger committed
601
            return reduce(lambda x, y: x * y, volume_tuple)
602
        except TypeError:
Theo Steininger's avatar
Theo Steininger committed
603
            return 0.
604

Theo Steininger's avatar
Theo Steininger committed
605
606
607
608
    @property
    def real(self):
        """ The real part of the field (data is not copied).
        """
609
        return Field(self.domain,self.val.real)
Theo Steininger's avatar
Theo Steininger committed
610
611
612
613
614

    @property
    def imag(self):
        """ The imaginary part of the field (data is not copied).
        """
615
        return Field(self.domain,self.val.imag)
Theo Steininger's avatar
Theo Steininger committed
616

Theo Steininger's avatar
Theo Steininger committed
617
    # ---Special unary/binary operations---
618

csongor's avatar
csongor committed
619

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

623
624
        If no keyword arguments are given, the returned object will be an
        identical copy of the original Field. By explicit specification one is
Martin Reinecke's avatar
stage1    
Martin Reinecke committed
625
        able to define the domain and the dtype of the returned Field.
626
627
628
629
630

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

632
633
        dtype : type
            The new dtype the Field shall have.
Theo Steininger's avatar
Theo Steininger committed
634

635
636
637
638
639
640
641
642
643
644
        Returns
        -------
        out : Field
            The output object. An identical copy of 'self'.

        See Also
        --------
        copy_empty

        """
Theo Steininger's avatar
Theo Steininger committed
645

646
647
648
        if domain is None:
            domain = self.domain
        return Field(domain=domain,val=self._val,dtype=dtype,copy=True)
csongor's avatar
csongor committed
649

Martin Reinecke's avatar
stage1    
Martin Reinecke committed
650
    def copy_empty(self, domain=None, dtype=None):
651
652
653
        """ 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
654
655
656
        identical copy of the original Field. The memory for the data array
        is only allocated but not actively set to any value
        (c.f. numpy.ndarray.copy_empty). By explicit specification one is able
Martin Reinecke's avatar
stage1    
Martin Reinecke committed
657
        to change the domain and the dtype of the returned Field.
Theo Steininger's avatar
Theo Steininger committed
658

659
660
661
662
        Parameters
        ----------
        domain : DomainObject
            The new domain the Field shall have.
Theo Steininger's avatar
Theo Steininger committed
663

664
665
        dtype : type
            The new dtype the Field shall have.
Theo Steininger's avatar
Theo Steininger committed
666

667
668
669
        Returns
        -------
        out : Field
Theo Steininger's avatar
Theo Steininger committed
670
            The output object.
671
672
673
674
675
676

        See Also
        --------
        copy

        """
Theo Steininger's avatar
Theo Steininger committed
677

Theo Steininger's avatar
Theo Steininger committed
678
679
680
681
        if domain is None:
            domain = self.domain
        if dtype is None:
            dtype = self.dtype
682
        return Field(domain=domain, dtype=dtype)
Theo Steininger's avatar
Theo Steininger committed
683
684

    def weight(self, power=1, inplace=False, spaces=None):
Theo Steininger's avatar
Theo Steininger committed
685
        """ Weights the pixels of `self` with their invidual pixel-volume.
686
687
688
689

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

692
        inplace : boolean
Theo Steininger's avatar
Theo Steininger committed
693
694
            If True, `self` will be weighted and returned. Otherwise, a copy
            is made.
Theo Steininger's avatar
Theo Steininger committed
695

Theo Steininger's avatar
Theo Steininger committed
696
697
        spaces : tuple of ints
            Determines on which subspace the operation takes place.
Theo Steininger's avatar
Theo Steininger committed
698

699
700
701
        Returns
        -------
        out : Field
Theo Steininger's avatar
Theo Steininger committed
702
            The weighted field.
703
704

        """
705
        new_val = self.get_val(copy=False)
csongor's avatar
csongor committed
706

707
        spaces = utilities.cast_axis_to_tuple(spaces, len(self.domain))
csongor's avatar
csongor committed
708
        if spaces is None:
Martin Reinecke's avatar
Martin Reinecke committed
709
            spaces = list(range(len(self.domain)))
csongor's avatar
csongor committed
710

711
        for ind, sp in enumerate(self.domain):
Theo Steininger's avatar
Theo Steininger committed
712
713
714
715
716
            if ind in spaces:
                new_val = sp.weight(new_val,
                                    power=power,
                                    axes=self.domain_axes[ind],
                                    inplace=inplace)
Martin Reinecke's avatar
updates    
Martin Reinecke committed
717
718
                # we need at most one copy, the rest can happen in place
                inplace = True
719

Martin Reinecke's avatar
updates    
Martin Reinecke committed
720
        return Field(self.domain, new_val, self.dtype)
csongor's avatar
csongor committed
721

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

725
726
727
        Parameters
        ----------
        x : Field
Theo Steininger's avatar
Theo Steininger committed
728
            The domain of x must contain `self.domain`
Theo Steininger's avatar
Theo Steininger committed
729

Theo Steininger's avatar
Theo Steininger committed
730
731
732
        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
733

734
        bare : boolean
Theo Steininger's avatar
Theo Steininger committed
735
            If true, no volume factors will be included in the computation.
Theo Steininger's avatar
Theo Steininger committed
736

737
738
739
        Returns
        -------
        out : float, complex
Theo Steininger's avatar
Theo Steininger committed
740

741
        """
742
743
744
        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
745

Martin Reinecke's avatar
Martin Reinecke committed
746
        # Compute the dot respecting the fact of discrete/continuous spaces
747
        y = self if bare else self.weight(power=1)
Theo Steininger's avatar
Theo Steininger committed
748

749
        if spaces is None:
750
            return np.vdot(y.val.flatten(),x.val.flatten())
751
752
753
        else:
            # create a diagonal operator which is capable of taking care of the
            # axes-matching
754
            from .operators.diagonal_operator import DiagonalOperator
755
756
757
758
759
760
            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
761

Theo Steininger's avatar
Theo Steininger committed
762
    def norm(self):
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
763
        """ Computes the L2-norm of the field values.
csongor's avatar
csongor committed
764

Theo Steininger's avatar
Theo Steininger committed
765
766
767
        Returns
        -------
        norm : scalar
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
768
            The L2-norm of the field values.
csongor's avatar
csongor committed
769
770

        """
Martin Reinecke's avatar
fixes    
Martin Reinecke committed
771
        return np.sqrt(np.abs(self.vdot(x=self)))
csongor's avatar
csongor committed
772
773

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

776
777
778
        Parameters
        ----------
        inplace : boolean
Theo Steininger's avatar
Theo Steininger committed
779
            Decides whether the conjugation should be performed inplace.
Theo Steininger's avatar
Theo Steininger committed
780

781
782
783
784
        Returns
        -------
        cc : field
            The complex conjugated field.
csongor's avatar
csongor committed
785
786
787

        """
        if inplace:
788
789
            self.imag*=-1
            return self
csongor's avatar
csongor committed
790
        else:
791
            return Field(self.domain,np.conj(self.val),self.dtype)
csongor's avatar
csongor committed
792

Theo Steininger's avatar
Theo Steininger committed
793
    # ---General unary/contraction methods---
794

Theo Steininger's avatar
Theo Steininger committed
795
796
    def __pos__(self):
        return self.copy()
797

Theo Steininger's avatar
Theo Steininger committed
798
    def __neg__(self):
799
        return Field(self.domain,-self.val,self.dtype)
csongor's avatar
csongor committed
800

Theo Steininger's avatar
Theo Steininger committed
801
    def __abs__(self):
802
        return Field(self.domain,np.abs(self.val),self.dtype)
csongor's avatar
csongor committed
803

804
    def _contraction_helper(self, op, spaces):
Theo Steininger's avatar
Theo Steininger committed
805
        if spaces is None:
806
807
808
            return getattr(self.val, op)()
        # build a list of all axes
        spaces = utilities.cast_axis_to_tuple(spaces, len(self.domain))
csongor's avatar
csongor committed
809

810
        axes_list = tuple(self.domain_axes[sp_index] for sp_index in spaces)
811
812

        try:
Theo Steininger's avatar
Theo Steininger committed
813
            axes_list = reduce(lambda x, y: x+y, axes_list)
814
        except TypeError:
Theo Steininger's avatar
Theo Steininger committed
815
            axes_list = ()
csongor's avatar
csongor committed
816

Martin Reinecke's avatar
stage1    
Martin Reinecke committed
817
        # perform the contraction on the data
Theo Steininger's avatar
Theo Steininger committed
818
819
        data = self.get_val(copy=False)
        data = getattr(data, op)(axis=axes_list)
csongor's avatar
csongor committed
820

Theo Steininger's avatar
Theo Steininger committed
821
822
823
        # check if the result is scalar or if a result_field must be constr.
        if np.isscalar(data):
            return data
csongor's avatar
csongor committed
824
        else:
Theo Steininger's avatar
Theo Steininger committed
825
            return_domain = tuple(self.domain[i]
Martin Reinecke's avatar
Martin Reinecke committed
826
                                  for i in range(len(self.domain))
Theo Steininger's avatar
Theo Steininger committed
827
                                  if i not in spaces)
828

Martin Reinecke's avatar
updates    
Martin Reinecke committed
829
            return Field(domain=return_domain, val=data, copy=False)
csongor's avatar
csongor committed
830

831
832
    def sum(self, spaces=None):
        return self._contraction_helper('sum', spaces)
csongor's avatar
csongor committed
833

834
835
    def prod(self, spaces=None):
        return self._contraction_helper('prod', spaces)
csongor's avatar
csongor committed
836

837
838
    def all(self, spaces=None):
        return self._contraction_helper('all', spaces)
csongor's avatar
csongor committed
839

840
841
    def any(self, spaces=None):
        return self._contraction_helper('any', spaces)
csongor's avatar
csongor committed
842

843
844
    def min(self, spaces=None):
        return self._contraction_helper('min', spaces)
csongor's avatar
csongor committed
845

846
847
    def nanmin(self, spaces=None):
        return self._contraction_helper('nanmin', spaces)
csongor's avatar
csongor committed
848

849
850
    def max(self, spaces=None):
        return self._contraction_helper('max', spaces)
csongor's avatar
csongor committed
851

852
853
    def nanmax(self, spaces=None):
        return self._contraction_helper('nanmax', spaces)
csongor's avatar
csongor committed
854

855
856
    def mean(self, spaces=None):
        return self._contraction_helper('mean', spaces)
csongor's avatar
csongor committed
857

858
859
    def var(self, spaces=None):
        return self._contraction_helper('var', spaces)
csongor's avatar
csongor committed
860

861
862
    def std(self, spaces=None):
        return self._contraction_helper('std', spaces)
csongor's avatar
csongor committed
863

Theo Steininger's avatar
Theo Steininger committed
864
    # ---General binary methods---
csongor's avatar
csongor committed
865

866
    def _binary_helper(self, other, op):
csongor's avatar
csongor committed
867
        # if other is a field, make sure that the domains match
868
        if isinstance(other, Field):
869
870
871
            if other.domain != self.domain:
                raise ValueError("domains are incompatible.")
            return Field(self.domain,getattr(self.val,op)(other.val))
csongor's avatar
csongor committed
872

873
        return Field(self.domain,getattr(self.val,op)(other))
csongor's avatar
csongor committed
874
875

    def __add__(self, other):
Theo Steininger's avatar
Theo Steininger committed
876
        return self._binary_helper(other, op='__add__')