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

Martin Reinecke's avatar
Martin Reinecke committed
18
from functools import reduce
csongor's avatar
csongor committed
19
import numpy as np
20
21

from . import dobj, utilities
Martin Reinecke's avatar
Martin Reinecke committed
22
from .domain_tuple import DomainTuple
23

24

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

28
    Stores data arrays and carries all the needed meta-information (i.e. the
29
    domain) for operators to be able to operate on them.
Theo Steininger's avatar
Theo Steininger committed
30

31
32
    Parameters
    ----------
33
34
35
36
37
    domain : DomainTuple
        the domain of the new Field
    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
38
39
40
41

    Notes
    -----
    If possible, do not invoke the constructor directly, but use one of the
42
    many convenience functions for instantiation!
43
    """
44

45
46
    _scalar_dom = DomainTuple.scalar_domain()

47
48
49
    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
50
        if type(val) is not dobj.data_object:
Martin Reinecke's avatar
Martin Reinecke committed
51
            if np.isscalar(val):
Martin Reinecke's avatar
Martin Reinecke committed
52
                val = dobj.full(domain.shape, val)
Martin Reinecke's avatar
Martin Reinecke committed
53
54
            else:
                raise TypeError("val must be of type dobj.data_object")
55
        if domain.shape != val.shape:
Martin Reinecke's avatar
Martin Reinecke committed
56
            raise ValueError("shape mismatch between val and domain")
57
58
        self._domain = domain
        self._val = val
59
        dobj.lock(self._val)
Martin Reinecke's avatar
Martin Reinecke committed
60

Martin Reinecke's avatar
Martin Reinecke committed
61
62
63
64
    @staticmethod
    def scalar(val):
        return Field(Field._scalar_dom, val)

65
66
67
68
69
70
71
    # 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")

72
    @staticmethod
73
    def full(domain, val):
Martin Reinecke's avatar
Martin Reinecke committed
74
75
76
77
78
79
80
81
82
83
84
85
86
87
        """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
        """
88
89
        if not np.isscalar(val):
            raise TypeError("val must be a scalar")
90
91
92
        if not (np.isreal(val) or np.iscomplex(val)):
            raise TypeError("need arithmetic scalar")
        domain = DomainTuple.make(domain)
Martin Reinecke's avatar
Martin Reinecke committed
93
        return Field(domain, val)
94

95
    @staticmethod
96
    def from_global_data(domain, arr, sum_up=False):
Martin Reinecke's avatar
Martin Reinecke committed
97
98
99
100
101
102
103
104
105
        """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`.
106
107
108
109
110
        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
111
        """
112
113
        return Field(DomainTuple.make(domain),
                     dobj.from_global_data(arr, sum_up))
114

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

120
    def to_global_data(self):
Martin Reinecke's avatar
Martin Reinecke committed
121
122
123
124
125
126
127
        """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`.
        """
128
129
        return dobj.to_global_data(self._val)

130
131
132
133
134
135
136
137
138
139
    def to_global_data_rw(self):
        """Returns a modifiable array containing the full data of the field.

        Returns
        -------
        numpy.ndarray : array containing all field entries, which can be
            modified. Its shape is identical to `self.shape`.
        """
        return dobj.to_global_data_rw(self._val)

Martin Reinecke's avatar
Martin Reinecke committed
140
141
    @property
    def local_data(self):
Martin Reinecke's avatar
Martin Reinecke committed
142
143
144
145
146
        """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
147
148
        return dobj.local_data(self._val)

Martin Reinecke's avatar
Martin Reinecke committed
149
    def cast_domain(self, new_domain):
Martin Reinecke's avatar
Martin Reinecke committed
150
151
152
153
154
155
156
157
158
159
160
        """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
Philipp Arras's avatar
Philipp Arras committed
161
            Field defined on `new_domain`, but with the same data as `self`.
Martin Reinecke's avatar
Martin Reinecke committed
162
        """
163
        return Field(DomainTuple.make(new_domain), self._val)
164

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

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

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

Theo Steininger's avatar
Theo Steininger committed
188
189
    @property
    def val(self):
Martin Reinecke's avatar
Martin Reinecke committed
190
191
192
193
194
195
        """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.
196
        """
Martin Reinecke's avatar
Martin Reinecke committed
197
        return self._val
csongor's avatar
csongor committed
198

Martin Reinecke's avatar
Martin Reinecke committed
199
200
    @property
    def dtype(self):
Martin Reinecke's avatar
Martin Reinecke committed
201
        """type : the data type of the field's entries"""
Martin Reinecke's avatar
Martin Reinecke committed
202
203
        return self._val.dtype

Martin Reinecke's avatar
Martin Reinecke committed
204
205
    @property
    def domain(self):
Martin Reinecke's avatar
Martin Reinecke committed
206
        """DomainTuple : the field's domain"""
Martin Reinecke's avatar
Martin Reinecke committed
207
208
        return self._domain

209
210
    @property
    def shape(self):
Martin Reinecke's avatar
Martin Reinecke committed
211
        """tuple of int : the concatenated shapes of all sub-domains"""
Martin Reinecke's avatar
Martin Reinecke committed
212
        return self._domain.shape
csongor's avatar
csongor committed
213

214
    @property
Martin Reinecke's avatar
Martin Reinecke committed
215
    def size(self):
Martin Reinecke's avatar
Martin Reinecke committed
216
        """int : total number of pixels in the field"""
Martin Reinecke's avatar
Martin Reinecke committed
217
        return self._domain.size
csongor's avatar
csongor committed
218

Theo Steininger's avatar
Theo Steininger committed
219
220
    @property
    def real(self):
Martin Reinecke's avatar
Martin Reinecke committed
221
        """Field : The real part of the field"""
Martin Reinecke's avatar
Martin Reinecke committed
222
223
224
        if utilities.iscomplextype(self.dtype):
            return Field(self._domain, self._val.real)
        return self
Theo Steininger's avatar
Theo Steininger committed
225
226
227

    @property
    def imag(self):
Martin Reinecke's avatar
Martin Reinecke committed
228
        """Field : The imaginary part of the field"""
Martin Reinecke's avatar
Martin Reinecke committed
229
        if not utilities.iscomplextype(self.dtype):
230
            raise ValueError(".imag called on a non-complex Field")
Martin Reinecke's avatar
Martin Reinecke committed
231
        return Field(self._domain, self._val.imag)
Theo Steininger's avatar
Theo Steininger committed
232

233
    def scalar_weight(self, spaces=None):
Martin Reinecke's avatar
Martin Reinecke committed
234
235
236
237
238
239
240
241
242
243
244
245
246
247
        """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.
        """
248
        if np.isscalar(spaces):
Martin Reinecke's avatar
Martin Reinecke committed
249
            return self._domain[spaces].scalar_dvol
250
251

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

Martin Reinecke's avatar
Martin Reinecke committed
261
    def total_volume(self, spaces=None):
Martin Reinecke's avatar
Martin Reinecke committed
262
263
264
265
266
267
268
269
270
271
272
273
274
        """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
275
        if np.isscalar(spaces):
Martin Reinecke's avatar
Martin Reinecke committed
276
            return self._domain[spaces].total_volume
Martin Reinecke's avatar
Martin Reinecke committed
277
278
279
280
281

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

285
    def weight(self, power=1, spaces=None):
286
        """Weights the pixels of `self` with their invidual pixel-volume.
287
288
289
290

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

Martin Reinecke's avatar
Martin Reinecke committed
293
294
295
        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
296

297
298
        Returns
        -------
Martin Reinecke's avatar
Martin Reinecke committed
299
        Field
Theo Steininger's avatar
Theo Steininger committed
300
            The weighted field.
301
        """
302
        aout = self.local_data.copy()
csongor's avatar
csongor committed
303

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

306
307
        fct = 1.
        for ind in spaces:
Martin Reinecke's avatar
Martin Reinecke committed
308
            wgt = self._domain[ind].dvol
309
310
311
            if np.isscalar(wgt):
                fct *= wgt
            else:
Martin Reinecke's avatar
Martin Reinecke committed
312
                new_shape = np.ones(len(self.shape), dtype=np.int)
Martin Reinecke's avatar
Martin Reinecke committed
313
314
                new_shape[self._domain.axes[ind][0]:
                          self._domain.axes[ind][-1]+1] = wgt.shape
315
                wgt = wgt.reshape(new_shape)
Martin Reinecke's avatar
Martin Reinecke committed
316
317
                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
318
                    wgt = dobj.local_data(dobj.from_global_data(wgt))
319
                aout *= wgt**power
320
        fct = fct**power
Martin Reinecke's avatar
Martin Reinecke committed
321
        if fct != 1.:
322
            aout *= fct
323

324
        return Field.from_local_data(self._domain, aout)
csongor's avatar
csongor committed
325

326
    def outer(self, x):
327
        """Computes the outer product of 'self' with x.
328
329
330
331
332
333
334

        Parameters
        ----------
        x : Field

        Returns
        ----------
Philipp Arras's avatar
Philipp Arras committed
335
        Field, defined on the product space of self.domain and x.domain
336
337
338
        """
        if not isinstance(x, Field):
            raise TypeError("The multiplier must be an instance of " +
339
                            "the Field class")
340
341
342
        from .operators.outer_product_operator import OuterProduct
        return OuterProduct(self, x.domain)(x)

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

346
347
348
        Parameters
        ----------
        x : Field
Philipp Arras's avatar
Philipp Arras committed
349
            x must be defined on the same domain as `self`.
Theo Steininger's avatar
Theo Steininger committed
350

Philipp Arras's avatar
Philipp Arras committed
351
        spaces : None, int or tuple of int
352
353
            The dot product is only carried out over the sub-domains in this
            tuple. If None, it is carried out over all sub-domains.
Philipp Arras's avatar
Philipp Arras committed
354
            Default: None.
Theo Steininger's avatar
Theo Steininger committed
355

356
357
        Returns
        -------
Philipp Arras's avatar
Philipp Arras committed
358
        float, complex, either scalar (for full dot products) or Field (for partial dot products).
359
        """
360
        if not isinstance(x, Field):
361
            raise TypeError("The dot-partner must be an instance of " +
362
                            "the Field class")
Theo Steininger's avatar
Theo Steininger committed
363

Martin Reinecke's avatar
Martin Reinecke committed
364
        if x._domain != self._domain:
365
            raise ValueError("Domain mismatch")
Theo Steininger's avatar
Theo Steininger committed
366

Martin Reinecke's avatar
Martin Reinecke committed
367
        ndom = len(self._domain)
368
369
370
        spaces = utilities.parse_spaces(spaces, ndom)

        if len(spaces) == ndom:
Martin Reinecke's avatar
Martin Reinecke committed
371
            return dobj.vdot(self._val, x._val)
372
373
        # 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
374
        return (self.conjugate()*x).sum(spaces=spaces)
Theo Steininger's avatar
Theo Steininger committed
375

Martin Reinecke's avatar
Martin Reinecke committed
376
    def norm(self, ord=2):
377
        """Computes the L2-norm of the field values.
csongor's avatar
csongor committed
378

Martin Reinecke's avatar
Martin Reinecke committed
379
380
        Parameters
        ----------
Philipp Arras's avatar
Philipp Arras committed
381
382
        ord : int
            Accepted values: 1, 2, ..., np.inf. Default: 2.
383
384
385
386

        Returns
        -------
        float
Martin Reinecke's avatar
Martin Reinecke committed
387
            The L2-norm of the field values.
388
        """
Martin Reinecke's avatar
Martin Reinecke committed
389
        return dobj.norm(self._val, ord)
390

Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
391
    def conjugate(self):
392
        """Returns the complex conjugate of the field.
Theo Steininger's avatar
Theo Steininger committed
393

394
395
        Returns
        -------
Martin Reinecke's avatar
Martin Reinecke committed
396
397
        Field
            The complex conjugated field.
csongor's avatar
csongor committed
398
        """
Martin Reinecke's avatar
Martin Reinecke committed
399
        if utilities.iscomplextype(self._val.dtype):
Martin Reinecke's avatar
Martin Reinecke committed
400
401
            return Field(self._domain, self._val.conjugate())
        return self
csongor's avatar
csongor committed
402

Theo Steininger's avatar
Theo Steininger committed
403
    # ---General unary/contraction methods---
404

Theo Steininger's avatar
Theo Steininger committed
405
    def __pos__(self):
406
        return self
407

Theo Steininger's avatar
Theo Steininger committed
408
    def __neg__(self):
Martin Reinecke's avatar
Martin Reinecke committed
409
        return Field(self._domain, -self._val)
csongor's avatar
csongor committed
410

Theo Steininger's avatar
Theo Steininger committed
411
    def __abs__(self):
Martin Reinecke's avatar
Martin Reinecke committed
412
        return Field(self._domain, abs(self._val))
csongor's avatar
csongor committed
413

414
    def _contraction_helper(self, op, spaces):
Theo Steininger's avatar
Theo Steininger committed
415
        if spaces is None:
Martin Reinecke's avatar
Martin Reinecke committed
416
            return getattr(self._val, op)()
417

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

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

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

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

Theo Steininger's avatar
Theo Steininger committed
428
429
430
        # 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
431
        else:
Martin Reinecke's avatar
Martin Reinecke committed
432
            return_domain = tuple(dom
Martin Reinecke's avatar
Martin Reinecke committed
433
                                  for i, dom in enumerate(self._domain)
Theo Steininger's avatar
Theo Steininger committed
434
                                  if i not in spaces)
435

436
            return Field(DomainTuple.make(return_domain), data)
csongor's avatar
csongor committed
437

438
    def sum(self, spaces=None):
Martin Reinecke's avatar
Martin Reinecke committed
439
440
441
442
        """Sums up over the sub-domains given by `spaces`.

        Parameters
        ----------
Philipp Arras's avatar
Philipp Arras committed
443
        spaces : None, int or tuple of int
Martin Reinecke's avatar
Martin Reinecke committed
444
            The summation is only carried out over the sub-domains in this
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
445
            tuple. If None, it is carried out over all sub-domains.
Martin Reinecke's avatar
Martin Reinecke committed
446
447
448
449
450
451
452

        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.
        """
453
        return self._contraction_helper('sum', spaces)
csongor's avatar
csongor committed
454

455
    def integrate(self, spaces=None):
Martin Reinecke's avatar
Martin Reinecke committed
456
457
458
459
460
461
462
        """Integrates over the sub-domains given by `spaces`.

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

        Parameters
        ----------
Philipp Arras's avatar
Philipp Arras committed
463
        spaces : None, int or tuple of int
Martin Reinecke's avatar
Martin Reinecke committed
464
465
466
467
468
469
470
471
472
            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
473
474
475
        swgt = self.scalar_weight(spaces)
        if swgt is not None:
            res = self.sum(spaces)
Martin Reinecke's avatar
fixes    
Martin Reinecke committed
476
            res = res*swgt
Martin Reinecke's avatar
Martin Reinecke committed
477
            return res
478
479
480
        tmp = self.weight(1, spaces=spaces)
        return tmp.sum(spaces)

481
    def prod(self, spaces=None):
Martin Reinecke's avatar
Martin Reinecke committed
482
483
484
485
        """Computes the product over the sub-domains given by `spaces`.

        Parameters
        ----------
Philipp Arras's avatar
Philipp Arras committed
486
        spaces : None, int or tuple of int
Martin Reinecke's avatar
Martin Reinecke committed
487
488
            The operation is only carried out over the sub-domains in this
            tuple. If None, it is carried out over all sub-domains.
Philipp Arras's avatar
Philipp Arras committed
489
            Default: None.
Martin Reinecke's avatar
Martin Reinecke committed
490
491
492
493
494
495
496

        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.
        """
497
        return self._contraction_helper('prod', spaces)
csongor's avatar
csongor committed
498

499
500
    def all(self, spaces=None):
        return self._contraction_helper('all', spaces)
csongor's avatar
csongor committed
501

502
503
    def any(self, spaces=None):
        return self._contraction_helper('any', spaces)
csongor's avatar
csongor committed
504

505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
#     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
538

539
    def mean(self, spaces=None):
Martin Reinecke's avatar
Martin Reinecke committed
540
541
542
543
544
545
546
        """Determines the mean over the sub-domains given by `spaces`.

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

        Parameters
        ----------
Philipp Arras's avatar
Philipp Arras committed
547
        spaces : None, int or tuple of int
Martin Reinecke's avatar
Martin Reinecke committed
548
            The operation is only carried out over the sub-domains in this
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
549
            tuple. If None, it is carried out over all sub-domains.
Martin Reinecke's avatar
Martin Reinecke committed
550
551
552
553
554
555
556

        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.
        """
557
558
        if self.scalar_weight(spaces) is not None:
            return self._contraction_helper('mean', spaces)
Martin Reinecke's avatar
Martin Reinecke committed
559
        # MR FIXME: not very efficient
560
561
        # MR FIXME: do we need "spaces" here?
        tmp = self.weight(1, spaces)
Martin Reinecke's avatar
Martin Reinecke committed
562
        return tmp.sum(spaces)*(1./tmp.total_volume(spaces))
csongor's avatar
csongor committed
563

564
    def var(self, spaces=None):
Martin Reinecke's avatar
Martin Reinecke committed
565
566
567
568
        """Determines the variance over the sub-domains given by `spaces`.

        Parameters
        ----------
Philipp Arras's avatar
Philipp Arras committed
569
        spaces : None, int or tuple of int
Martin Reinecke's avatar
Martin Reinecke committed
570
571
            The operation is only carried out over the sub-domains in this
            tuple. If None, it is carried out over all sub-domains.
Philipp Arras's avatar
Philipp Arras committed
572
            Default: None.
Martin Reinecke's avatar
Martin Reinecke committed
573
574
575
576
577
578
579

        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.
        """
580
581
        if self.scalar_weight(spaces) is not None:
            return self._contraction_helper('var', spaces)
Martin Reinecke's avatar
Martin Reinecke committed
582
583
        # MR FIXME: not very efficient or accurate
        m1 = self.mean(spaces)
Martin Reinecke's avatar
Martin Reinecke committed
584
        if utilities.iscomplextype(self.dtype):
585
            sq = abs(self-m1)**2
Martin Reinecke's avatar
Martin Reinecke committed
586
        else:
587
588
            sq = (self-m1)**2
        return sq.mean(spaces)
csongor's avatar
csongor committed
589

590
    def std(self, spaces=None):
Martin Reinecke's avatar
Martin Reinecke committed
591
592
593
594
595
596
597
        """Determines the standard deviation over the sub-domains given by
        `spaces`.

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

        Parameters
        ----------
Philipp Arras's avatar
Philipp Arras committed
598
        spaces : None, int or tuple of int
Martin Reinecke's avatar
Martin Reinecke committed
599
600
            The operation is only carried out over the sub-domains in this
            tuple. If None, it is carried out over all sub-domains.
Philipp Arras's avatar
Philipp Arras committed
601
            Default: None.
Martin Reinecke's avatar
Martin Reinecke committed
602
603
604
605
606
607
608

        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.
        """
609
        from .sugar import sqrt
610
611
612
        if self.scalar_weight(spaces) is not None:
            return self._contraction_helper('std', spaces)
        return sqrt(self.var(spaces))
csongor's avatar
csongor committed
613

Theo Steininger's avatar
Theo Steininger committed
614
    def __repr__(self):
Philipp Arras's avatar
Philipp Arras committed
615
        return "<nifty5.Field>"
Theo Steininger's avatar
Theo Steininger committed
616
617

    def __str__(self):
Philipp Arras's avatar
Philipp Arras committed
618
        return "nifty5.Field instance\n- domain      = " + \
619
               self._domain.__str__() + \
Martin Reinecke's avatar
Martin Reinecke committed
620
               "\n- val         = " + repr(self._val)
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
621

Martin Reinecke's avatar
more    
Martin Reinecke committed
622
    def extract(self, dom):
Martin Reinecke's avatar
Martin Reinecke committed
623
        if dom != self._domain:
Martin Reinecke's avatar
more    
Martin Reinecke committed
624
625
626
627
            raise ValueError("domain mismatch")
        return self

    def unite(self, other):
Martin Reinecke's avatar
Martin Reinecke committed
628
629
630
631
        return self+other

    def flexible_addsub(self, other, neg):
        return self-other if neg else self+other
632

633
    def sigmoid(self):
Martin Reinecke's avatar
Martin Reinecke committed
634
635
        return 0.5*(1.+self.tanh())

Martin Reinecke's avatar
Martin Reinecke committed
636
637
    def clip(self, min=None, max=None):
        return Field(self._domain, dobj.clip(self._val, min, max))
638
639
640
641

    def one_over(self):
        return 1/self

Martin Reinecke's avatar
Martin Reinecke committed
642
643
644
645
    def _binary_op(self, other, op):
        # if other is a field, make sure that the domains match
        f = getattr(self._val, op)
        if isinstance(other, Field):
Martin Reinecke's avatar
Martin Reinecke committed
646
            if other._domain != self._domain:
Martin Reinecke's avatar
Martin Reinecke committed
647
648
649
650
651
                raise ValueError("domains are incompatible.")
            return Field(self._domain, f(other._val))
        if np.isscalar(other):
            return Field(self._domain, f(other))
        return NotImplemented
Martin Reinecke's avatar
Martin Reinecke committed
652

Martin Reinecke's avatar
Martin Reinecke committed
653

Martin Reinecke's avatar
Martin Reinecke committed
654
655
656
for op in ["__add__", "__radd__",
           "__sub__", "__rsub__",
           "__mul__", "__rmul__",
657
658
659
660
           "__div__", "__rdiv__",
           "__truediv__", "__rtruediv__",
           "__floordiv__", "__rfloordiv__",
           "__pow__", "__rpow__",
661
662
663
           "__lt__", "__le__", "__gt__", "__ge__", "__eq__", "__ne__"]:
    def func(op):
        def func2(self, other):
Martin Reinecke's avatar
Martin Reinecke committed
664
            return self._binary_op(other, op)
665
666
        return func2
    setattr(Field, op, func(op))
667
668
669
670
671
672
673
674
675

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))
Martin Reinecke's avatar
Martin Reinecke committed
676

677
678
679
for f in ["sqrt", "exp", "log", "tanh",
          "sin", "cos", "tan", "cosh", "sinh",
          "absolute", "sinc", "sign"]:
Martin Reinecke's avatar
Martin Reinecke committed
680
681
    def func(f):
        def func2(self):
Martin Reinecke's avatar
Martin Reinecke committed
682
            return Field(self._domain, getattr(dobj, f)(self.val))
Martin Reinecke's avatar
Martin Reinecke committed
683
684
        return func2
    setattr(Field, f, func(f))