field.py 21.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
#
Martin Reinecke's avatar
Martin Reinecke committed
14
# Copyright(C) 2013-2018 Max-Planck-Society
Theo Steininger's avatar
Theo Steininger committed
15
16
17
#
# NIFTy is being developed at the Max-Planck-Institut fuer Astrophysik
# and financially supported by the Studienstiftung des deutschen Volkes.
18

19
from __future__ import absolute_import, division, print_function
20

csongor's avatar
csongor committed
21
import numpy as np
22
23
24

from . import dobj, utilities
from .compat import *
Martin Reinecke's avatar
Martin Reinecke committed
25
from .domain_tuple import DomainTuple
26

27

Martin Reinecke's avatar
Martin Reinecke committed
28
class Field(object):
Theo Steininger's avatar
Theo Steininger committed
29
30
    """ The discrete representation of a continuous field over multiple spaces.

Martin Reinecke's avatar
Martin Reinecke committed
31
    In NIFTy, Fields are used to store data arrays and carry all the needed
32
    metainformation (i.e. the domain) for operators to be able to work on them.
Theo Steininger's avatar
Theo Steininger committed
33

34
35
    Parameters
    ----------
36
37
    domain : DomainTuple
        the domain of the new Field
Theo Steininger's avatar
Theo Steininger committed
38

39
40
41
    val : data_object
        This object's global shape must match the domain shape
        After construction, the object will no longer be writeable!
Martin Reinecke's avatar
Martin Reinecke committed
42
43
44
45

    Notes
    -----
    If possible, do not invoke the constructor directly, but use one of the
46
    many convenience functions for Field construction!
47
    """
48

49
50
51
    def __init__(self, domain, val):
        if not isinstance(domain, DomainTuple):
            raise TypeError("domain must be of type DomainTuple")
Martin Reinecke's avatar
Martin Reinecke committed
52
53
        if np.isscalar(val):
            val = np.full((), val)
54
55
56
57
58
59
        if not isinstance(val, dobj.data_object):
            raise TypeError("val must be of type dobj.data_object")
        if domain.shape != val.shape:
            raise ValueError("mismatch between the shapes of val and domain")
        self._domain = domain
        self._val = val
60
        dobj.lock(self._val)
Martin Reinecke's avatar
Martin Reinecke committed
61

62
63
64
65
66
67
68
    # prevent implicit conversion to bool
    def __nonzero__(self):
        raise TypeError("Field does not support implicit conversion to bool")

    def __bool__(self):
        raise TypeError("Field does not support implicit conversion to bool")

69
    @staticmethod
70
    def full(domain, val):
Martin Reinecke's avatar
Martin Reinecke committed
71
72
73
74
75
76
77
78
79
80
81
82
83
84
        """Creates a Field with a given domain, filled with a constant value.

        Parameters
        ----------
        domain : Domain, tuple of Domain, or DomainTuple
            domain of the new Field
        val : float/complex/int scalar
            fill value. Data type of the field is inferred from val.

        Returns
        -------
        Field
            the newly created field
        """
85
86
        if not np.isscalar(val):
            raise TypeError("val must be a scalar")
87
88
89
90
        if not (np.isreal(val) or np.iscomplex(val)):
            raise TypeError("need arithmetic scalar")
        domain = DomainTuple.make(domain)
        return Field(domain, dobj.full(domain.shape, fill_value=val))
91

92
    @staticmethod
93
    def from_global_data(domain, arr, sum_up=False):
Martin Reinecke's avatar
Martin Reinecke committed
94
95
96
97
98
99
100
101
102
        """Returns a Field constructed from `domain` and `arr`.

        Parameters
        ----------
        domain : DomainTuple, tuple of Domain, or Domain
            the domain of the new Field
        arr : numpy.ndarray
            The data content to be used for the new Field.
            Its shape must match the shape of `domain`.
103
104
105
106
107
        sum_up : bool, optional
            If True, the contents of `arr` are summed up over all MPI tasks
            (if any), and the sum is used as data content.
            If False, the contens of `arr` are used directly, and must be
            identical on all MPI tasks.
Martin Reinecke's avatar
Martin Reinecke committed
108
        """
109
110
        return Field(DomainTuple.make(domain),
                     dobj.from_global_data(arr, sum_up))
111

Martin Reinecke's avatar
Martin Reinecke committed
112
113
    @staticmethod
    def from_local_data(domain, arr):
114
        return Field(DomainTuple.make(domain),
Martin Reinecke's avatar
Martin Reinecke committed
115
                     dobj.from_local_data(domain.shape, arr))
Martin Reinecke's avatar
Martin Reinecke committed
116

117
    def to_global_data(self):
Martin Reinecke's avatar
Martin Reinecke committed
118
119
120
121
122
123
124
125
126
127
128
129
        """Returns an array containing the full data of the field.

        Returns
        -------
        numpy.ndarray : array containing all field entries.
            Its shape is identical to `self.shape`.

        Notes
        -----
        Do not write to the returned array! Depending on whether MPI is
        active or not, this may or may not change the field's data content.
        """
130
131
        return dobj.to_global_data(self._val)

Martin Reinecke's avatar
Martin Reinecke committed
132
133
    @property
    def local_data(self):
Martin Reinecke's avatar
Martin Reinecke committed
134
135
136
137
138
        """numpy.ndarray : locally residing field data

        Returns a handle to the part of the array data residing on the local
        task (or to the entore array if MPI is not active).
        """
Martin Reinecke's avatar
Martin Reinecke committed
139
140
        return dobj.local_data(self._val)

Martin Reinecke's avatar
Martin Reinecke committed
141
    def cast_domain(self, new_domain):
Martin Reinecke's avatar
Martin Reinecke committed
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
        """Returns a field with the same data, but a different domain

        Parameters
        ----------
        new_domain : Domain, tuple of Domain, or DomainTuple
            The domain for the returned field. Must be shape-compatible to
            `self`.

        Returns
        -------
        Field
            Field living on `new_domain`, but with the same data as `self`.

        Notes
        -----
        No copy is made. If needed, use an additional copy() invocation.
        """
159
        return Field(DomainTuple.make(new_domain), self._val)
160

Martin Reinecke's avatar
Martin Reinecke committed
161
162
    @staticmethod
    def from_random(random_type, domain, dtype=np.float64, **kwargs):
163
164
165
166
        """ Draws a random field with the given parameters.

        Parameters
        ----------
Martin Reinecke's avatar
Martin Reinecke committed
167
168
        random_type : 'pm1', 'normal', or 'uniform'
            The random distribution to use.
Martin Reinecke's avatar
Martin Reinecke committed
169
        domain : DomainTuple
170
171
172
            The domain of the output random field
        dtype : type
            The datatype of the output random field
Theo Steininger's avatar
Theo Steininger committed
173

174
175
        Returns
        -------
Martin Reinecke's avatar
Martin Reinecke committed
176
        Field
Martin Reinecke's avatar
Martin Reinecke committed
177
            The newly created Field.
178
        """
Martin Reinecke's avatar
Martin Reinecke committed
179
        domain = DomainTuple.make(domain)
Martin Reinecke's avatar
Martin Reinecke committed
180
181
182
        return Field(domain=domain,
                     val=dobj.from_random(random_type, dtype=dtype,
                                          shape=domain.shape, **kwargs))
183

Theo Steininger's avatar
Theo Steininger committed
184
185
    @property
    def val(self):
Martin Reinecke's avatar
Martin Reinecke committed
186
187
188
189
190
191
        """dobj.data_object : the data object storing the field's entries

        Notes
        -----
        This property is intended for low-level, internal use only. Do not use
        from outside of NIFTy's core; there should be better alternatives.
192
        """
Martin Reinecke's avatar
Martin Reinecke committed
193
        return self._val
csongor's avatar
csongor committed
194

Martin Reinecke's avatar
Martin Reinecke committed
195
196
    @property
    def dtype(self):
Martin Reinecke's avatar
Martin Reinecke committed
197
        """type : the data type of the field's entries"""
Martin Reinecke's avatar
Martin Reinecke committed
198
199
        return self._val.dtype

Martin Reinecke's avatar
Martin Reinecke committed
200
201
    @property
    def domain(self):
Martin Reinecke's avatar
Martin Reinecke committed
202
        """DomainTuple : the field's domain"""
Martin Reinecke's avatar
Martin Reinecke committed
203
204
        return self._domain

205
206
    @property
    def shape(self):
Martin Reinecke's avatar
Martin Reinecke committed
207
        """tuple of int : the concatenated shapes of all sub-domains"""
Martin Reinecke's avatar
Martin Reinecke committed
208
        return self._domain.shape
csongor's avatar
csongor committed
209

210
    @property
Martin Reinecke's avatar
Martin Reinecke committed
211
    def size(self):
Martin Reinecke's avatar
Martin Reinecke committed
212
        """int : total number of pixels in the field"""
Martin Reinecke's avatar
Martin Reinecke committed
213
        return self._domain.size
csongor's avatar
csongor committed
214

Theo Steininger's avatar
Theo Steininger committed
215
216
    @property
    def real(self):
Martin Reinecke's avatar
Martin Reinecke committed
217
        """Field : The real part of the field"""
218
        if not np.issubdtype(self.dtype, np.complexfloating):
219
            return self
Martin Reinecke's avatar
Martin Reinecke committed
220
        return Field(self._domain, self._val.real)
Theo Steininger's avatar
Theo Steininger committed
221
222
223

    @property
    def imag(self):
Martin Reinecke's avatar
Martin Reinecke committed
224
        """Field : The imaginary part of the field"""
225
226
        if not np.issubdtype(self.dtype, np.complexfloating):
            raise ValueError(".imag called on a non-complex Field")
Martin Reinecke's avatar
Martin Reinecke committed
227
        return Field(self._domain, self._val.imag)
Theo Steininger's avatar
Theo Steininger committed
228

229
    def scalar_weight(self, spaces=None):
Martin Reinecke's avatar
Martin Reinecke committed
230
231
232
233
234
235
236
237
238
239
240
241
242
243
        """Returns the uniform volume element for a sub-domain of `self`.

        Parameters
        ----------
        spaces : int, tuple of int or None
            indices of the sub-domains of the field's domain to be considered.
            If `None`, the entire domain is used.

        Returns
        -------
        float or None
            if the requested sub-domain has a uniform volume element, it is
            returned. Otherwise, `None` is returned.
        """
244
        if np.isscalar(spaces):
Martin Reinecke's avatar
Martin Reinecke committed
245
            return self._domain[spaces].scalar_dvol
246
247

        if spaces is None:
Martin Reinecke's avatar
Martin Reinecke committed
248
            spaces = range(len(self._domain))
Martin Reinecke's avatar
Martin Reinecke committed
249
        res = 1.
250
        for i in spaces:
Martin Reinecke's avatar
Martin Reinecke committed
251
            tmp = self._domain[i].scalar_dvol
252
253
254
255
256
            if tmp is None:
                return None
            res *= tmp
        return res

Martin Reinecke's avatar
Martin Reinecke committed
257
    def total_volume(self, spaces=None):
Martin Reinecke's avatar
Martin Reinecke committed
258
259
260
261
262
263
264
265
266
267
268
269
270
        """Returns the total volume of a sub-domain of `self`.

        Parameters
        ----------
        spaces : int, tuple of int or None
            indices of the sub-domains of the field's domain to be considered.
            If `None`, the entire domain is used.

        Returns
        -------
        float
            the total volume of the requested sub-domain.
        """
Martin Reinecke's avatar
Martin Reinecke committed
271
        if np.isscalar(spaces):
Martin Reinecke's avatar
Martin Reinecke committed
272
            return self._domain[spaces].total_volume
Martin Reinecke's avatar
Martin Reinecke committed
273
274
275
276
277

        if spaces is None:
            spaces = range(len(self._domain))
        res = 1.
        for i in spaces:
Martin Reinecke's avatar
Martin Reinecke committed
278
            res *= self._domain[i].total_volume
Martin Reinecke's avatar
Martin Reinecke committed
279
280
        return res

281
    def weight(self, power=1, spaces=None):
Theo Steininger's avatar
Theo Steininger committed
282
        """ Weights the pixels of `self` with their invidual pixel-volume.
283
284
285
286

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

Martin Reinecke's avatar
Martin Reinecke committed
289
290
291
        spaces : None, int or tuple of int
            Determines on which sub-domain the operation takes place.
            If None, the entire domain is used.
Theo Steininger's avatar
Theo Steininger committed
292

293
294
        Returns
        -------
Martin Reinecke's avatar
Martin Reinecke committed
295
        Field
Theo Steininger's avatar
Theo Steininger committed
296
            The weighted field.
297
        """
298
        aout = self.local_data.copy()
csongor's avatar
csongor committed
299

Martin Reinecke's avatar
Martin Reinecke committed
300
        spaces = utilities.parse_spaces(spaces, len(self._domain))
csongor's avatar
csongor committed
301

302
303
        fct = 1.
        for ind in spaces:
Martin Reinecke's avatar
Martin Reinecke committed
304
            wgt = self._domain[ind].dvol
305
306
307
            if np.isscalar(wgt):
                fct *= wgt
            else:
Martin Reinecke's avatar
Martin Reinecke committed
308
                new_shape = np.ones(len(self.shape), dtype=np.int)
Martin Reinecke's avatar
Martin Reinecke committed
309
310
                new_shape[self._domain.axes[ind][0]:
                          self._domain.axes[ind][-1]+1] = wgt.shape
311
                wgt = wgt.reshape(new_shape)
Martin Reinecke's avatar
Martin Reinecke committed
312
313
                if dobj.distaxis(self._val) >= 0 and ind == 0:
                    # we need to distribute the weights along axis 0
Martin Reinecke's avatar
fixes    
Martin Reinecke committed
314
                    wgt = dobj.local_data(dobj.from_global_data(wgt))
315
                aout *= wgt**power
316
        fct = fct**power
Martin Reinecke's avatar
Martin Reinecke committed
317
        if fct != 1.:
318
            aout *= fct
319

320
        return Field.from_local_data(self._domain, aout)
csongor's avatar
csongor committed
321

Martin Reinecke's avatar
Martin Reinecke committed
322
    def vdot(self, x=None, spaces=None):
Martin Reinecke's avatar
Martin Reinecke committed
323
        """ Computes the dot product of 'self' with x.
Theo Steininger's avatar
Theo Steininger committed
324

325
326
327
        Parameters
        ----------
        x : Field
328
            x must live on the same domain as `self`.
Theo Steininger's avatar
Theo Steininger committed
329

Martin Reinecke's avatar
Martin Reinecke committed
330
        spaces : None, int or tuple of int (default: None)
331
332
            The dot product is only carried out over the sub-domains in this
            tuple. If None, it is carried out over all sub-domains.
Theo Steininger's avatar
Theo Steininger committed
333

334
335
        Returns
        -------
Martin Reinecke's avatar
Martin Reinecke committed
336
        float, complex, either scalar (for full dot products)
337
                              or Field (for partial dot products)
338
        """
339
        if not isinstance(x, Field):
340
341
            raise TypeError("The dot-partner must be an instance of " +
                            "the NIFTy field class")
Theo Steininger's avatar
Theo Steininger committed
342

343
        if x._domain is not self._domain:
344
            raise ValueError("Domain mismatch")
Theo Steininger's avatar
Theo Steininger committed
345

Martin Reinecke's avatar
Martin Reinecke committed
346
        ndom = len(self._domain)
347
348
349
        spaces = utilities.parse_spaces(spaces, ndom)

        if len(spaces) == ndom:
Martin Reinecke's avatar
Martin Reinecke committed
350
            return dobj.vdot(self._val, x._val)
351
352
        # If we arrive here, we have to do a partial dot product.
        # For the moment, do this the explicit, non-optimized way
Martin Reinecke's avatar
Martin Reinecke committed
353
        return (self.conjugate()*x).sum(spaces=spaces)
Theo Steininger's avatar
Theo Steininger committed
354

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

Theo Steininger's avatar
Theo Steininger committed
358
359
        Returns
        -------
Martin Reinecke's avatar
Martin Reinecke committed
360
        float
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
361
            The L2-norm of the field values.
csongor's avatar
csongor committed
362
        """
363
        return np.sqrt(abs(self.vdot(x=self)))
csongor's avatar
csongor committed
364

365
366
367
368
369
370
371
372
373
374
    def squared_norm(self):
        """ Computes the square of the L2-norm of the field values.

        Returns
        -------
        float
            The square of the L2-norm of the field values.
        """
        return abs(self.vdot(x=self))

Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
375
    def conjugate(self):
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
376
        """ Returns the complex conjugate of the field.
Theo Steininger's avatar
Theo Steininger committed
377

378
379
        Returns
        -------
Martin Reinecke's avatar
Martin Reinecke committed
380
381
        Field
            The complex conjugated field.
csongor's avatar
csongor committed
382
        """
Martin Reinecke's avatar
Martin Reinecke committed
383
        return Field(self._domain, self._val.conjugate())
csongor's avatar
csongor committed
384

Theo Steininger's avatar
Theo Steininger committed
385
    # ---General unary/contraction methods---
386

Theo Steininger's avatar
Theo Steininger committed
387
    def __pos__(self):
388
        return self
389

Theo Steininger's avatar
Theo Steininger committed
390
    def __neg__(self):
Martin Reinecke's avatar
Martin Reinecke committed
391
        return Field(self._domain, -self._val)
csongor's avatar
csongor committed
392

Theo Steininger's avatar
Theo Steininger committed
393
    def __abs__(self):
Martin Reinecke's avatar
Martin Reinecke committed
394
        return Field(self._domain, abs(self._val))
csongor's avatar
csongor committed
395

396
    def _contraction_helper(self, op, spaces):
Theo Steininger's avatar
Theo Steininger committed
397
        if spaces is None:
Martin Reinecke's avatar
Martin Reinecke committed
398
            return getattr(self._val, op)()
399

Martin Reinecke's avatar
Martin Reinecke committed
400
        spaces = utilities.parse_spaces(spaces, len(self._domain))
csongor's avatar
csongor committed
401

Martin Reinecke's avatar
Martin Reinecke committed
402
        axes_list = tuple(self._domain.axes[sp_index] for sp_index in spaces)
403

Martin Reinecke's avatar
Martin Reinecke committed
404
        if len(axes_list) > 0:
Theo Steininger's avatar
Theo Steininger committed
405
            axes_list = reduce(lambda x, y: x+y, axes_list)
csongor's avatar
csongor committed
406

Martin Reinecke's avatar
stage1    
Martin Reinecke committed
407
        # perform the contraction on the data
Martin Reinecke's avatar
Martin Reinecke committed
408
        data = getattr(self._val, op)(axis=axes_list)
csongor's avatar
csongor committed
409

Theo Steininger's avatar
Theo Steininger committed
410
411
412
        # 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
413
        else:
Martin Reinecke's avatar
Martin Reinecke committed
414
            return_domain = tuple(dom
Martin Reinecke's avatar
Martin Reinecke committed
415
                                  for i, dom in enumerate(self._domain)
Theo Steininger's avatar
Theo Steininger committed
416
                                  if i not in spaces)
417

418
            return Field(DomainTuple.make(return_domain), data)
csongor's avatar
csongor committed
419

420
    def sum(self, spaces=None):
Martin Reinecke's avatar
Martin Reinecke committed
421
422
423
424
425
426
427
428
429
430
431
432
433
434
        """Sums up over the sub-domains given by `spaces`.

        Parameters
        ----------
        spaces : None, int or tuple of int (default: None)
            The summation is only carried out over the sub-domains in this
            tuple. If None, it is carried out over all sub-domains.

        Returns
        -------
        Field or scalar
            The result of the summation. If it is carried out over the entire
            domain, this is a scalar, otherwise a Field.
        """
435
        return self._contraction_helper('sum', spaces)
csongor's avatar
csongor committed
436

437
    def integrate(self, spaces=None):
Martin Reinecke's avatar
Martin Reinecke committed
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
        """Integrates over the sub-domains given by `spaces`.

        Integration is performed by summing over `self` multiplied by its
        volume factors.

        Parameters
        ----------
        spaces : None, int or tuple of int (default: None)
            The summation is only carried out over the sub-domains in this
            tuple. If None, it is carried out over all sub-domains.

        Returns
        -------
        Field or scalar
            The result of the integration. If it is carried out over the
            entire domain, this is a scalar, otherwise a Field.
        """
Martin Reinecke's avatar
Martin Reinecke committed
455
456
457
458
459
        swgt = self.scalar_weight(spaces)
        if swgt is not None:
            res = self.sum(spaces)
            res *= swgt
            return res
460
461
462
        tmp = self.weight(1, spaces=spaces)
        return tmp.sum(spaces)

463
    def prod(self, spaces=None):
Martin Reinecke's avatar
Martin Reinecke committed
464
465
466
467
468
469
470
471
472
473
474
475
476
477
        """Computes the product over the sub-domains given by `spaces`.

        Parameters
        ----------
        spaces : None, int or tuple of int (default: None)
            The operation is only carried out over the sub-domains in this
            tuple. If None, it is carried out over all sub-domains.

        Returns
        -------
        Field or scalar
            The result of the product. If it is carried out over the entire
            domain, this is a scalar, otherwise a Field.
        """
478
        return self._contraction_helper('prod', spaces)
csongor's avatar
csongor committed
479

480
481
    def all(self, spaces=None):
        return self._contraction_helper('all', spaces)
csongor's avatar
csongor committed
482

483
484
    def any(self, spaces=None):
        return self._contraction_helper('any', spaces)
csongor's avatar
csongor committed
485

486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
#     def min(self, spaces=None):
#         """Determines the minimum over the sub-domains given by `spaces`.
#
#         Parameters
#         ----------
#         spaces : None, int or tuple of int (default: None)
#             The operation is only carried out over the sub-domains in this
#             tuple. If None, it is carried out over all sub-domains.
#
#         Returns
#         -------
#         Field or scalar
#             The result of the operation. If it is carried out over the entire
#             domain, this is a scalar, otherwise a Field.
#         """
#         return self._contraction_helper('min', spaces)
#
#     def max(self, spaces=None):
#         """Determines the maximum over the sub-domains given by `spaces`.
#
#         Parameters
#         ----------
#         spaces : None, int or tuple of int (default: None)
#             The operation is only carried out over the sub-domains in this
#             tuple. If None, it is carried out over all sub-domains.
#
#         Returns
#         -------
#         Field or scalar
#             The result of the operation. If it is carried out over the entire
#             domain, this is a scalar, otherwise a Field.
#         """
#         return self._contraction_helper('max', spaces)
csongor's avatar
csongor committed
519

520
    def mean(self, spaces=None):
Martin Reinecke's avatar
Martin Reinecke committed
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
        """Determines the mean over the sub-domains given by `spaces`.

        ``x.mean(spaces)`` is equivalent to
        ``x.integrate(spaces)/x.total_volume(spaces)``.

        Parameters
        ----------
        spaces : None, int or tuple of int (default: None)
            The operation is only carried out over the sub-domains in this
            tuple. If None, it is carried out over all sub-domains.

        Returns
        -------
        Field or scalar
            The result of the operation. If it is carried out over the entire
            domain, this is a scalar, otherwise a Field.
        """
538
539
        if self.scalar_weight(spaces) is not None:
            return self._contraction_helper('mean', spaces)
Martin Reinecke's avatar
Martin Reinecke committed
540
        # MR FIXME: not very efficient
541
542
        # MR FIXME: do we need "spaces" here?
        tmp = self.weight(1, spaces)
Martin Reinecke's avatar
Martin Reinecke committed
543
        return tmp.sum(spaces)*(1./tmp.total_volume(spaces))
csongor's avatar
csongor committed
544

545
    def var(self, spaces=None):
Martin Reinecke's avatar
Martin Reinecke committed
546
547
548
549
550
551
552
553
554
555
556
557
558
559
        """Determines the variance over the sub-domains given by `spaces`.

        Parameters
        ----------
        spaces : None, int or tuple of int (default: None)
            The operation is only carried out over the sub-domains in this
            tuple. If None, it is carried out over all sub-domains.

        Returns
        -------
        Field or scalar
            The result of the operation. If it is carried out over the entire
            domain, this is a scalar, otherwise a Field.
        """
560
561
        if self.scalar_weight(spaces) is not None:
            return self._contraction_helper('var', spaces)
Martin Reinecke's avatar
Martin Reinecke committed
562
563
564
        # MR FIXME: not very efficient or accurate
        m1 = self.mean(spaces)
        if np.issubdtype(self.dtype, np.complexfloating):
565
            sq = abs(self-m1)**2
Martin Reinecke's avatar
Martin Reinecke committed
566
        else:
567
568
            sq = (self-m1)**2
        return sq.mean(spaces)
csongor's avatar
csongor committed
569

570
    def std(self, spaces=None):
Martin Reinecke's avatar
Martin Reinecke committed
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
        """Determines the standard deviation over the sub-domains given by
        `spaces`.

        ``x.std(spaces)`` is equivalent to ``sqrt(x.var(spaces))``.

        Parameters
        ----------
        spaces : None, int or tuple of int (default: None)
            The operation is only carried out over the sub-domains in this
            tuple. If None, it is carried out over all sub-domains.

        Returns
        -------
        Field or scalar
            The result of the operation. If it is carried out over the entire
            domain, this is a scalar, otherwise a Field.
        """
588
        from .sugar import sqrt
589
590
591
        if self.scalar_weight(spaces) is not None:
            return self._contraction_helper('std', spaces)
        return sqrt(self.var(spaces))
csongor's avatar
csongor committed
592

Theo Steininger's avatar
Theo Steininger committed
593
    def __repr__(self):
Philipp Arras's avatar
Philipp Arras committed
594
        return "<nifty5.Field>"
Theo Steininger's avatar
Theo Steininger committed
595
596

    def __str__(self):
Philipp Arras's avatar
Philipp Arras committed
597
        return "nifty5.Field instance\n- domain      = " + \
598
               self._domain.__str__() + \
Martin Reinecke's avatar
Martin Reinecke committed
599
               "\n- val         = " + repr(self._val)
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
600

601
602
603
    def isEquivalentTo(self, other):
        """Determines (as quickly as possible) whether `self`'s content is
        identical to `other`'s content."""
604
605
606
607
        if self is other:
            return True
        if not isinstance(other, Field):
            return False
608
        if self._domain is not other._domain:
609
610
611
            return False
        return (self._val == other._val).all()

Martin Reinecke's avatar
more    
Martin Reinecke committed
612
613
614
615
616
617
618
    def extract(self, dom):
        if dom is not self._domain:
            raise ValueError("domain mismatch")
        return self

    def unite(self, other):
        return self + other
619

620
621
622
623
624
625
626
for op in ["__add__", "__radd__",
           "__sub__", "__rsub__",
           "__mul__", "__rmul__",
           "__div__", "__rdiv__",
           "__truediv__", "__rtruediv__",
           "__floordiv__", "__rfloordiv__",
           "__pow__", "__rpow__",
627
628
629
           "__lt__", "__le__", "__gt__", "__ge__", "__eq__", "__ne__"]:
    def func(op):
        def func2(self, other):
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
630
631
            # if other is a field, make sure that the domains match
            if isinstance(other, Field):
632
                if other._domain is not self._domain:
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
633
                    raise ValueError("domains are incompatible.")
Martin Reinecke's avatar
Martin Reinecke committed
634
                tval = getattr(self._val, op)(other._val)
635
                return Field(self._domain, tval)
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
636

Martin Reinecke's avatar
fix    
Martin Reinecke committed
637
638
            if (np.isscalar(other) or
                    isinstance(other, (dobj.data_object, np.ndarray))):
Martin Reinecke's avatar
Martin Reinecke committed
639
                tval = getattr(self._val, op)(other)
640
                return Field(self._domain, tval)
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
641
642

            return NotImplemented
643
644
        return func2
    setattr(Field, op, func(op))
645
646
647
648
649
650
651
652
653

for op in ["__iadd__", "__isub__", "__imul__", "__idiv__",
           "__itruediv__", "__ifloordiv__", "__ipow__"]:
    def func(op):
        def func2(self, other):
            raise TypeError(
                "In-place operations are deliberately not supported")
        return func2
    setattr(Field, op, func(op))