field.py 22.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-2020 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
Philipp Arras's avatar
Philipp Arras committed
19

csongor's avatar
csongor committed
20
import numpy as np
21

Martin Reinecke's avatar
stage 1  
Martin Reinecke committed
22
from . import utilities
Martin Reinecke's avatar
Martin Reinecke committed
23
from .domain_tuple import DomainTuple
Martin Reinecke's avatar
misc  
Martin Reinecke committed
24
from .operators.operator import Operator
25

26

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

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

33
34
    Parameters
    ----------
35
    domain : DomainTuple
Philipp Arras's avatar
Docs  
Philipp Arras committed
36
        The domain of the new Field.
Martin Reinecke's avatar
Martin Reinecke committed
37
38
    val : numpy.ndarray
        This object's shape must match the domain shape
39
        After construction, the object will no longer be writeable!
Martin Reinecke's avatar
Martin Reinecke committed
40

Martin Reinecke's avatar
Martin Reinecke committed
41
42
    Notes
    -----
Martin Reinecke's avatar
Martin Reinecke committed
43
    If possible, do not invoke the constructor directly, but use one of the
44
    many convenience functions for instantiation!
45
    """
46

47
48
    _scalar_dom = DomainTuple.scalar_domain()

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
stage 1  
Martin Reinecke committed
52
        if not isinstance(val, np.ndarray):
Martin Reinecke's avatar
Martin Reinecke committed
53
            if np.isscalar(val):
54
                val = np.broadcast_to(val, domain.shape)
Martin Reinecke's avatar
Martin Reinecke committed
55
            else:
Martin Reinecke's avatar
stage 1  
Martin Reinecke committed
56
                raise TypeError("val must be of type numpy.ndarray")
57
        if domain.shape != val.shape:
Martin Reinecke's avatar
Martin Reinecke committed
58
            raise ValueError("shape mismatch between val and domain")
59
60
        self._domain = domain
        self._val = val
Martin Reinecke's avatar
stage 1  
Martin Reinecke committed
61
        self._val.flags.writeable = False
Martin Reinecke's avatar
Martin Reinecke committed
62

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

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

74
    @staticmethod
75
    def full(domain, val):
Martin Reinecke's avatar
Martin Reinecke committed
76
77
78
79
80
        """Creates a Field with a given domain, filled with a constant value.

        Parameters
        ----------
        domain : Domain, tuple of Domain, or DomainTuple
Philipp Arras's avatar
Docs  
Philipp Arras committed
81
            Domain of the new Field.
Martin Reinecke's avatar
Martin Reinecke committed
82
        val : float/complex/int scalar
Philipp Arras's avatar
Docs  
Philipp Arras committed
83
            Fill value. Data type of the field is inferred from val.
Martin Reinecke's avatar
Martin Reinecke committed
84
85
86
87

        Returns
        -------
        Field
Philipp Arras's avatar
Docs  
Philipp Arras committed
88
            The newly created Field.
Martin Reinecke's avatar
Martin Reinecke committed
89
        """
90
91
        if not np.isscalar(val):
            raise TypeError("val must be a scalar")
92
93
94
        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
95
        return Field(domain, val)
96

97
    @staticmethod
Martin Reinecke's avatar
Martin Reinecke committed
98
    def from_raw(domain, arr):
Martin Reinecke's avatar
Martin Reinecke committed
99
100
101
102
103
        """Returns a Field constructed from `domain` and `arr`.

        Parameters
        ----------
        domain : DomainTuple, tuple of Domain, or Domain
Philipp Arras's avatar
Docs  
Philipp Arras committed
104
            The domain of the new Field.
Martin Reinecke's avatar
Martin Reinecke committed
105
106
107
108
        arr : numpy.ndarray
            The data content to be used for the new Field.
            Its shape must match the shape of `domain`.
        """
Martin Reinecke's avatar
stage 1  
Martin Reinecke committed
109
        return Field(DomainTuple.make(domain), arr)
Martin Reinecke's avatar
Martin Reinecke committed
110

Martin Reinecke's avatar
Martin Reinecke committed
111
    def cast_domain(self, new_domain):
Martin Reinecke's avatar
Martin Reinecke committed
112
113
114
115
116
117
118
119
120
121
122
        """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
123
            Field defined on `new_domain`, but with the same data as `self`.
Martin Reinecke's avatar
Martin Reinecke committed
124
        """
125
        return Field(DomainTuple.make(new_domain), self._val)
126

Martin Reinecke's avatar
Martin Reinecke committed
127
    @staticmethod
128
    def from_random(domain, random_type='normal', dtype=np.float64, **kwargs):
129
        """Draws a random field with the given parameters.
130
131
132

        Parameters
        ----------
Martin Reinecke's avatar
Martin Reinecke committed
133
134
        random_type : 'pm1', 'normal', or 'uniform'
            The random distribution to use.
Martin Reinecke's avatar
Martin Reinecke committed
135
        domain : DomainTuple
Philipp Arras's avatar
Docs  
Philipp Arras committed
136
            The domain of the output random Field.
137
        dtype : type
Philipp Arras's avatar
Docs  
Philipp Arras committed
138
            The datatype of the output random Field.
Theo Steininger's avatar
Theo Steininger committed
139

140
141
        Returns
        -------
Martin Reinecke's avatar
Martin Reinecke committed
142
        Field
Martin Reinecke's avatar
Martin Reinecke committed
143
            The newly created Field.
144
        """
Martin Reinecke's avatar
cleanup  
Martin Reinecke committed
145
        from .random import Random
Martin Reinecke's avatar
Martin Reinecke committed
146
        domain = DomainTuple.make(domain)
Martin Reinecke's avatar
cleanup  
Martin Reinecke committed
147
148
149
        generator_function = getattr(Random, random_type)
        arr = generator_function(dtype=dtype, shape=domain.shape, **kwargs)
        return Field(domain, arr)
150

Theo Steininger's avatar
Theo Steininger committed
151
152
    @property
    def val(self):
Martin Reinecke's avatar
Martin Reinecke committed
153
        """numpy.ndarray : the array storing the field's entries.
Martin Reinecke's avatar
Martin Reinecke committed
154

Martin Reinecke's avatar
Martin Reinecke committed
155
156
        Notes
        -----
Martin Reinecke's avatar
Martin Reinecke committed
157
        The returned array is read-only.
158
        """
Martin Reinecke's avatar
Martin Reinecke committed
159
        return self._val
csongor's avatar
csongor committed
160

Martin Reinecke's avatar
Martin Reinecke committed
161
162
163
164
165
    def val_rw(self):
        """numpy.ndarray : a copy of the array storing the field's entries.
        """
        return self._val.copy()

Martin Reinecke's avatar
Martin Reinecke committed
166
167
    @property
    def dtype(self):
Martin Reinecke's avatar
Martin Reinecke committed
168
        """type : the data type of the field's entries"""
Martin Reinecke's avatar
Martin Reinecke committed
169
170
        return self._val.dtype

Martin Reinecke's avatar
Martin Reinecke committed
171
172
    @property
    def domain(self):
Martin Reinecke's avatar
Martin Reinecke committed
173
        """DomainTuple : the field's domain"""
Martin Reinecke's avatar
Martin Reinecke committed
174
175
        return self._domain

176
177
    @property
    def shape(self):
Martin Reinecke's avatar
Martin Reinecke committed
178
        """tuple of int : the concatenated shapes of all sub-domains"""
Martin Reinecke's avatar
Martin Reinecke committed
179
        return self._domain.shape
csongor's avatar
csongor committed
180

181
    @property
Martin Reinecke's avatar
Martin Reinecke committed
182
    def size(self):
Martin Reinecke's avatar
Martin Reinecke committed
183
        """int : total number of pixels in the field"""
Martin Reinecke's avatar
Martin Reinecke committed
184
        return self._domain.size
csongor's avatar
csongor committed
185

Theo Steininger's avatar
Theo Steininger committed
186
187
    @property
    def real(self):
Martin Reinecke's avatar
Martin Reinecke committed
188
        """Field : The real part of the field"""
Martin Reinecke's avatar
Martin Reinecke committed
189
190
191
        if utilities.iscomplextype(self.dtype):
            return Field(self._domain, self._val.real)
        return self
Theo Steininger's avatar
Theo Steininger committed
192
193
194

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

200
    def scalar_weight(self, spaces=None):
Martin Reinecke's avatar
Martin Reinecke committed
201
202
203
204
205
        """Returns the uniform volume element for a sub-domain of `self`.

        Parameters
        ----------
        spaces : int, tuple of int or None
Philipp Arras's avatar
Docs  
Philipp Arras committed
206
            Indices of the sub-domains of the field's domain to be considered.
Martin Reinecke's avatar
Martin Reinecke committed
207
208
209
210
211
            If `None`, the entire domain is used.

        Returns
        -------
        float or None
Philipp Arras's avatar
Docs  
Philipp Arras committed
212
            If the requested sub-domain has a uniform volume element, it is
Martin Reinecke's avatar
Martin Reinecke committed
213
214
            returned. Otherwise, `None` is returned.
        """
215
        return self._domain.scalar_weight(spaces)
216

Martin Reinecke's avatar
Martin Reinecke committed
217
    def total_volume(self, spaces=None):
218
        """Returns the total volume of the field's domain or of a subspace of it.
Martin Reinecke's avatar
Martin Reinecke committed
219
220
221
222

        Parameters
        ----------
        spaces : int, tuple of int or None
Philipp Arras's avatar
Docs  
Philipp Arras committed
223
            Indices of the sub-domains of the field's domain to be considered.
224
            If `None`, the total volume of the whole domain is returned.
Martin Reinecke's avatar
Martin Reinecke committed
225
226
227
228

        Returns
        -------
        float
229
            the total volume of the requested (sub-)domain.
Martin Reinecke's avatar
Martin Reinecke committed
230
        """
231
        return self._domain.total_volume(spaces)
Martin Reinecke's avatar
Martin Reinecke committed
232

233
    def weight(self, power=1, spaces=None):
234
        """Weights the pixels of `self` with their invidual pixel volumes.
235
236
237
238

        Parameters
        ----------
        power : number
239
            The pixel values get multiplied with their volume-factor**power.
Theo Steininger's avatar
Theo Steininger committed
240

Martin Reinecke's avatar
Martin Reinecke committed
241
242
243
        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
244

245
246
        Returns
        -------
Martin Reinecke's avatar
Martin Reinecke committed
247
        Field
Theo Steininger's avatar
Theo Steininger committed
248
            The weighted field.
249
        """
Martin Reinecke's avatar
Martin Reinecke committed
250
        aout = self.val_rw()
csongor's avatar
csongor committed
251

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

254
255
        fct = 1.
        for ind in spaces:
Martin Reinecke's avatar
Martin Reinecke committed
256
            wgt = self._domain[ind].dvol
257
258
259
            if np.isscalar(wgt):
                fct *= wgt
            else:
Martin Reinecke's avatar
Martin Reinecke committed
260
                new_shape = np.ones(len(self.shape), dtype=np.int)
Martin Reinecke's avatar
Martin Reinecke committed
261
262
                new_shape[self._domain.axes[ind][0]:
                          self._domain.axes[ind][-1]+1] = wgt.shape
263
                wgt = wgt.reshape(new_shape)
264
                aout *= wgt**power
265
        fct = fct**power
Martin Reinecke's avatar
Martin Reinecke committed
266
        if fct != 1.:
267
            aout *= fct
268

Martin Reinecke's avatar
stage 1  
Martin Reinecke committed
269
        return Field(self._domain, aout)
csongor's avatar
csongor committed
270

271
    def outer(self, x):
272
        """Computes the outer product of 'self' with x.
273
274
275
276
277
278

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

        Returns
Philipp Arras's avatar
Docs  
Philipp Arras committed
279
280
281
        -------
        Field
            Defined on the product space of self.domain and x.domain.
282
283
284
        """
        if not isinstance(x, Field):
            raise TypeError("The multiplier must be an instance of " +
285
                            "the Field class")
286
        from .operators.outer_product_operator import OuterProduct
287
        return OuterProduct(x.domain, self)(x)
288

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

292
293
294
        Parameters
        ----------
        x : Field
Philipp Arras's avatar
Philipp Arras committed
295
            x must be defined on the same domain as `self`.
Theo Steininger's avatar
Theo Steininger committed
296

Philipp Arras's avatar
Philipp Arras committed
297
        spaces : None, int or tuple of int
298
299
            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
300
            Default: None.
Theo Steininger's avatar
Theo Steininger committed
301

302
303
        Returns
        -------
Philipp Arras's avatar
Philipp Arras committed
304
        float, complex, either scalar (for full dot products) or Field (for partial dot products).
305
        """
306
        if not isinstance(x, Field):
307
            raise TypeError("The dot-partner must be an instance of " +
308
                            "the Field class")
Theo Steininger's avatar
Theo Steininger committed
309

Martin Reinecke's avatar
Martin Reinecke committed
310
        if x._domain != self._domain:
311
            raise ValueError("Domain mismatch")
Theo Steininger's avatar
Theo Steininger committed
312

Martin Reinecke's avatar
Martin Reinecke committed
313
        ndom = len(self._domain)
314
315
316
        spaces = utilities.parse_spaces(spaces, ndom)

        if len(spaces) == ndom:
Martin Reinecke's avatar
Martin Reinecke committed
317
            return Field.scalar(np.array(np.vdot(self._val, x._val)))
318
319
        # 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
320
        return (self.conjugate()*x).sum(spaces=spaces)
Theo Steininger's avatar
Theo Steininger committed
321

Martin Reinecke's avatar
Martin Reinecke committed
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
    def s_vdot(self, x):
        """Computes the dot product of 'self' with x.

        Parameters
        ----------
        x : Field
            x must be defined on the same domain as `self`.

        Returns
        -------
        float or complex
            The dot product
        """
        if not isinstance(x, Field):
            raise TypeError("The dot-partner must be an instance of " +
                            "the Field class")

        if x._domain != self._domain:
            raise ValueError("Domain mismatch")

        return np.vdot(self._val, x._val)

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

Martin Reinecke's avatar
Martin Reinecke committed
347
348
        Parameters
        ----------
Philipp Arras's avatar
Philipp Arras committed
349
350
        ord : int
            Accepted values: 1, 2, ..., np.inf. Default: 2.
351
352
353
354

        Returns
        -------
        float
Martin Reinecke's avatar
Martin Reinecke committed
355
            The L2-norm of the field values.
356
        """
Martin Reinecke's avatar
stage 1  
Martin Reinecke committed
357
        return np.linalg.norm(self._val.reshape(-1), ord=ord)
358

Martin Reinecke's avatar
tweaks  
Martin Reinecke committed
359
    def conjugate(self):
360
        """Returns the complex conjugate of the field.
Theo Steininger's avatar
Theo Steininger committed
361

362
363
        Returns
        -------
Martin Reinecke's avatar
Martin Reinecke committed
364
365
        Field
            The complex conjugated field.
csongor's avatar
csongor committed
366
        """
Martin Reinecke's avatar
Martin Reinecke committed
367
        if utilities.iscomplextype(self._val.dtype):
Martin Reinecke's avatar
Martin Reinecke committed
368
369
            return Field(self._domain, self._val.conjugate())
        return self
csongor's avatar
csongor committed
370

Theo Steininger's avatar
Theo Steininger committed
371
    # ---General unary/contraction methods---
372

Theo Steininger's avatar
Theo Steininger committed
373
    def __pos__(self):
374
        return self
375

Theo Steininger's avatar
Theo Steininger committed
376
    def __neg__(self):
Martin Reinecke's avatar
Martin Reinecke committed
377
        return Field(self._domain, -self._val)
csongor's avatar
csongor committed
378

Theo Steininger's avatar
Theo Steininger committed
379
    def __abs__(self):
Martin Reinecke's avatar
Martin Reinecke committed
380
        return Field(self._domain, abs(self._val))
csongor's avatar
csongor committed
381

382
    def _contraction_helper(self, op, spaces):
Theo Steininger's avatar
Theo Steininger committed
383
        if spaces is None:
Martin Reinecke's avatar
Martin Reinecke committed
384
            return Field.scalar(getattr(self._val, op)())
385

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

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

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

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

Theo Steininger's avatar
Theo Steininger committed
396
397
        # check if the result is scalar or if a result_field must be constr.
        if np.isscalar(data):
Martin Reinecke's avatar
Martin Reinecke committed
398
            return Field.scalar(data)
csongor's avatar
csongor committed
399
        else:
Martin Reinecke's avatar
Martin Reinecke committed
400
            return_domain = tuple(dom
Martin Reinecke's avatar
Martin Reinecke committed
401
                                  for i, dom in enumerate(self._domain)
Theo Steininger's avatar
Theo Steininger committed
402
                                  if i not in spaces)
403

404
            return Field(DomainTuple.make(return_domain), data)
csongor's avatar
csongor committed
405

406
    def sum(self, spaces=None):
Martin Reinecke's avatar
Martin Reinecke committed
407
408
409
410
        """Sums up over the sub-domains given by `spaces`.

        Parameters
        ----------
Philipp Arras's avatar
Philipp Arras committed
411
        spaces : None, int or tuple of int
Martin Reinecke's avatar
Martin Reinecke committed
412
            The summation is only carried out over the sub-domains in this
Martin Reinecke's avatar
cleanup  
Martin Reinecke committed
413
            tuple. If None, it is carried out over all sub-domains.
Martin Reinecke's avatar
Martin Reinecke committed
414
415
416

        Returns
        -------
Martin Reinecke's avatar
Martin Reinecke committed
417
418
        Field
            The result of the summation.
Martin Reinecke's avatar
Martin Reinecke committed
419
        """
420
        return self._contraction_helper('sum', spaces)
csongor's avatar
csongor committed
421

Martin Reinecke's avatar
Martin Reinecke committed
422
423
424
425
426
427
428
429
430
431
    def s_sum(self):
        """Returns the sum over all entries

        Returns
        -------
        scalar
            The result of the summation.
        """
        return self._val.sum()

432
    def integrate(self, spaces=None):
Martin Reinecke's avatar
Martin Reinecke committed
433
434
435
436
437
438
439
        """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
440
        spaces : None, int or tuple of int
Martin Reinecke's avatar
Martin Reinecke committed
441
442
443
444
445
            The summation is only carried out over the sub-domains in this
            tuple. If None, it is carried out over all sub-domains.

        Returns
        -------
Martin Reinecke's avatar
Martin Reinecke committed
446
447
        Field
            The result of the integration.
Martin Reinecke's avatar
Martin Reinecke committed
448
        """
Martin Reinecke's avatar
Martin Reinecke committed
449
450
451
        swgt = self.scalar_weight(spaces)
        if swgt is not None:
            res = self.sum(spaces)
Martin Reinecke's avatar
fixes  
Martin Reinecke committed
452
            res = res*swgt
Martin Reinecke's avatar
Martin Reinecke committed
453
            return res
454
455
456
        tmp = self.weight(1, spaces=spaces)
        return tmp.sum(spaces)

Martin Reinecke's avatar
Martin Reinecke committed
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
    def s_integrate(self):
        """Integrates over the Field.

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

        Returns
        -------
        Scalar
            The result of the integration.
        """
        swgt = self.scalar_weight()
        if swgt is not None:
            return self.s_sum()*swgt
        tmp = self.weight(1)
        return tmp.s_sum()

474
    def prod(self, spaces=None):
Martin Reinecke's avatar
Martin Reinecke committed
475
476
477
478
        """Computes the product over the sub-domains given by `spaces`.

        Parameters
        ----------
Philipp Arras's avatar
Philipp Arras committed
479
        spaces : None, int or tuple of int
Martin Reinecke's avatar
Martin Reinecke committed
480
481
            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
482
            Default: None.
Martin Reinecke's avatar
Martin Reinecke committed
483
484
485

        Returns
        -------
Martin Reinecke's avatar
Martin Reinecke committed
486
        Field
Philipp Arras's avatar
Philipp Arras committed
487
            The result of the product.
Martin Reinecke's avatar
Martin Reinecke committed
488
        """
489
        return self._contraction_helper('prod', spaces)
csongor's avatar
csongor committed
490

Martin Reinecke's avatar
Martin Reinecke committed
491
492
493
    def s_prod(self):
        return self._val.prod()

494
495
    def all(self, spaces=None):
        return self._contraction_helper('all', spaces)
csongor's avatar
csongor committed
496

Martin Reinecke's avatar
Martin Reinecke committed
497
498
499
    def s_all(self):
        return self._val.all()

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

Martin Reinecke's avatar
Martin Reinecke committed
503
504
505
    def s_any(self):
        return self._val.any()

506
507
508
509
510
511
512
513
514
515
516
#     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
#         -------
Martin Reinecke's avatar
Martin Reinecke committed
517
518
#         Field
#             The result of the operation.
519
520
521
522
523
524
525
526
527
528
529
530
531
532
#         """
#         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
#         -------
Martin Reinecke's avatar
Martin Reinecke committed
533
534
#         Field
#             The result of the operation.
535
536
#         """
#         return self._contraction_helper('max', spaces)
csongor's avatar
csongor committed
537

538
    def mean(self, spaces=None):
Martin Reinecke's avatar
Martin Reinecke committed
539
540
541
542
543
544
545
        """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
546
        spaces : None, int or tuple of int
Martin Reinecke's avatar
Martin Reinecke committed
547
            The operation is only carried out over the sub-domains in this
Martin Reinecke's avatar
cleanup  
Martin Reinecke committed
548
            tuple. If None, it is carried out over all sub-domains.
Martin Reinecke's avatar
Martin Reinecke committed
549
550
551

        Returns
        -------
Martin Reinecke's avatar
Martin Reinecke committed
552
553
        Field
            The result of the operation.
Martin Reinecke's avatar
Martin Reinecke committed
554
        """
555
556
        if self.scalar_weight(spaces) is not None:
            return self._contraction_helper('mean', spaces)
Martin Reinecke's avatar
Martin Reinecke committed
557
        # MR FIXME: not very efficient
558
559
        # MR FIXME: do we need "spaces" here?
        tmp = self.weight(1, spaces)
Martin Reinecke's avatar
Martin Reinecke committed
560
        return tmp.sum(spaces)*(1./tmp.total_volume(spaces))
csongor's avatar
csongor committed
561

Martin Reinecke's avatar
Martin Reinecke committed
562
563
564
565
566
567
568
569
570
571
572
573
574
    def s_mean(self):
        """Determines the field mean

        ``x.s_mean()`` is equivalent to
        ``x.s_integrate()/x.total_volume()``.

        Returns
        -------
        scalar
            The result of the operation.
        """
        return self.s_integrate()/self.total_volume()

575
    def var(self, spaces=None):
Martin Reinecke's avatar
Martin Reinecke committed
576
577
578
579
        """Determines the variance over the sub-domains given by `spaces`.

        Parameters
        ----------
Philipp Arras's avatar
Philipp Arras committed
580
        spaces : None, int or tuple of int
Martin Reinecke's avatar
Martin Reinecke committed
581
582
            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
583
            Default: None.
Martin Reinecke's avatar
Martin Reinecke committed
584
585
586

        Returns
        -------
Martin Reinecke's avatar
Martin Reinecke committed
587
588
        Field
            The result of the operation.
Martin Reinecke's avatar
Martin Reinecke committed
589
        """
590
591
        if self.scalar_weight(spaces) is not None:
            return self._contraction_helper('var', spaces)
Martin Reinecke's avatar
Martin Reinecke committed
592
593
        # MR FIXME: not very efficient or accurate
        m1 = self.mean(spaces)
Martin Reinecke's avatar
fixes  
Martin Reinecke committed
594
595
596
        from .operators.contraction_operator import ContractionOperator
        op = ContractionOperator(self._domain, spaces)
        m1 = op.adjoint_times(m1)
Martin Reinecke's avatar
Martin Reinecke committed
597
        if utilities.iscomplextype(self.dtype):
598
            sq = abs(self-m1)**2
Martin Reinecke's avatar
Martin Reinecke committed
599
        else:
600
601
            sq = (self-m1)**2
        return sq.mean(spaces)
csongor's avatar
csongor committed
602

Martin Reinecke's avatar
Martin Reinecke committed
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
    def s_var(self):
        """Determines the field variance

        Returns
        -------
        scalar
            The result of the operation.
        """
        if self.scalar_weight() is not None:
            return self._val.var()
        # MR FIXME: not very efficient or accurate
        m1 = self.s_mean()
        if utilities.iscomplextype(self.dtype):
            sq = abs(self-m1)**2
        else:
            sq = (self-m1)**2
        return sq.s_mean()

621
    def std(self, spaces=None):
Martin Reinecke's avatar
Martin Reinecke committed
622
623
624
625
626
627
628
        """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
629
        spaces : None, int or tuple of int
Martin Reinecke's avatar
Martin Reinecke committed
630
631
            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
632
            Default: None.
Martin Reinecke's avatar
Martin Reinecke committed
633
634
635

        Returns
        -------
Martin Reinecke's avatar
Martin Reinecke committed
636
637
        Field
            The result of the operation.
Martin Reinecke's avatar
Martin Reinecke committed
638
        """
639
640
        if self.scalar_weight(spaces) is not None:
            return self._contraction_helper('std', spaces)
Martin Reinecke's avatar
Martin Reinecke committed
641
        return self.var(spaces).ptw("sqrt")
csongor's avatar
csongor committed
642

Martin Reinecke's avatar
Martin Reinecke committed
643
644
645
646
647
648
649
650
651
652
653
654
655
656
    def s_std(self):
        """Determines the standard deviation of the Field.

        ``x.s_std()`` is equivalent to ``sqrt(x.s_var())``.

        Returns
        -------
        scalar
            The result of the operation.
        """
        if self.scalar_weight() is not None:
            return self._val.std()
        return np.sqrt(self.s_var())

Theo Steininger's avatar
Theo Steininger committed
657
    def __repr__(self):
Martin Reinecke's avatar
Martin Reinecke committed
658
        return "<nifty7.Field>"
Theo Steininger's avatar
Theo Steininger committed
659
660

    def __str__(self):
Martin Reinecke's avatar
Martin Reinecke committed
661
        return "nifty7.Field instance\n- domain      = " + \
662
               self._domain.__str__() + \
Martin Reinecke's avatar
Martin Reinecke committed
663
               "\n- val         = " + repr(self._val)
Martin Reinecke's avatar
cleanup  
Martin Reinecke committed
664

Martin Reinecke's avatar
more  
Martin Reinecke committed
665
    def extract(self, dom):
Martin Reinecke's avatar
Martin Reinecke committed
666
        if dom != self._domain:
Martin Reinecke's avatar
more  
Martin Reinecke committed
667
668
669
            raise ValueError("domain mismatch")
        return self

670
671
672
    def extract_part(self, dom):
        if dom != self._domain:
            raise ValueError("domain mismatch")
Martin Reinecke's avatar
more  
Martin Reinecke committed
673
674
675
        return self

    def unite(self, other):
Martin Reinecke's avatar
Martin Reinecke committed
676
677
678
679
        return self+other

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

Martin Reinecke's avatar
Martin Reinecke committed
681
682
683
684
    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
685
            if other._domain != self._domain:
Martin Reinecke's avatar
Martin Reinecke committed
686
687
688
689
690
                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
691

Martin Reinecke's avatar
Martin Reinecke committed
692
693
694
695
    def _prep_args(self, args, kwargs):
        for arg in args + tuple(kwargs.values()):
            if not (arg is None or np.isscalar(arg) or arg.jac is None):
                raise TypeError("bad argument")
Martin Reinecke's avatar
misc  
Martin Reinecke committed
696
697
698
699
        argstmp = tuple(arg if arg is None or np.isscalar(arg) else arg._val
                        for arg in args)
        kwargstmp = {key: val if val is None or np.isscalar(val) else val._val
                     for key, val in kwargs.items()}
Martin Reinecke's avatar
Martin Reinecke committed
700
701
702
703
704
        return argstmp, kwargstmp

    def ptw(self, op, *args, **kwargs):
        from .pointwise import ptw_dict
        argstmp, kwargstmp = self._prep_args(args, kwargs)
Martin Reinecke's avatar
misc  
Martin Reinecke committed
705
706
707
708
        return Field(self._domain, ptw_dict[op][0](self._val, *argstmp, **kwargstmp))

    def ptw_with_deriv(self, op, *args, **kwargs):
        from .pointwise import ptw_dict
Martin Reinecke's avatar
Martin Reinecke committed
709
        argstmp, kwargstmp = self._prep_args(args, kwargs)
Martin Reinecke's avatar
misc  
Martin Reinecke committed
710
711
        tmp = ptw_dict[op][1](self._val, *argstmp, **kwargstmp)
        return (Field(self._domain, tmp[0]), Field(self._domain, tmp[1]))
Martin Reinecke's avatar
Martin Reinecke committed
712

Philipp Arras's avatar
Cleanup  
Philipp Arras committed
713

Martin Reinecke's avatar
Martin Reinecke committed
714
715
716
for op in ["__add__", "__radd__",
           "__sub__", "__rsub__",
           "__mul__", "__rmul__",
717
718
719
           "__truediv__", "__rtruediv__",
           "__floordiv__", "__rfloordiv__",
           "__pow__", "__rpow__",
720
721
722
           "__lt__", "__le__", "__gt__", "__ge__", "__eq__", "__ne__"]:
    def func(op):
        def func2(self, other):
Martin Reinecke's avatar
Martin Reinecke committed
723
            return self._binary_op(other, op)
724
725
        return func2
    setattr(Field, op, func(op))
726
727
728
729
730
731
732
733
734

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))