field.py 22.5 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.
139
140
            If the datatype is complex, each real and imaginary part
            have variance 1
Theo Steininger's avatar
Theo Steininger committed
141

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

theos's avatar
theos committed
153
154
    @property
    def val(self):
Martin Reinecke's avatar
Martin Reinecke committed
155
        """numpy.ndarray : the array storing the field's entries.
Martin Reinecke's avatar
Martin Reinecke committed
156

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

Martin Reinecke's avatar
Martin Reinecke committed
163
164
165
166
167
    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
168
169
    @property
    def dtype(self):
Martin Reinecke's avatar
Martin Reinecke committed
170
        """type : the data type of the field's entries"""
Martin Reinecke's avatar
Martin Reinecke committed
171
172
        return self._val.dtype

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

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

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

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

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

202
    def scalar_weight(self, spaces=None):
Martin Reinecke's avatar
Martin Reinecke committed
203
204
205
206
207
        """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
208
            Indices of the sub-domains of the field's domain to be considered.
Martin Reinecke's avatar
Martin Reinecke committed
209
210
211
212
213
            If `None`, the entire domain is used.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Martin Reinecke's avatar
Martin Reinecke committed
312
        if x._domain != self._domain:
313
            raise ValueError("Domain mismatch")
theos's avatar
theos committed
314

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

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

Martin Reinecke's avatar
Martin Reinecke committed
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
    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
346
    def norm(self, ord=2):
347
        """Computes the L2-norm of the field values.
csongor's avatar
csongor committed
348

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

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

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

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

theos's avatar
theos committed
373
    # ---General unary/contraction methods---
374

theos's avatar
theos committed
375
    def __pos__(self):
376
        return self
377

theos's avatar
theos committed
378
    def __neg__(self):
Martin Reinecke's avatar
Martin Reinecke committed
379
        return Field(self._domain, -self._val)
csongor's avatar
csongor committed
380

theos's avatar
theos committed
381
    def __abs__(self):
Martin Reinecke's avatar
Martin Reinecke committed
382
        return Field(self._domain, abs(self._val))
csongor's avatar
csongor committed
383

384
    def _contraction_helper(self, op, spaces):
theos's avatar
theos committed
385
        if spaces is None:
Martin Reinecke's avatar
Martin Reinecke committed
386
            return Field.scalar(getattr(self._val, op)())
387

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

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

Martin Reinecke's avatar
Martin Reinecke committed
392
        if len(axes_list) > 0:
theos's avatar
theos committed
393
            axes_list = reduce(lambda x, y: x+y, axes_list)
csongor's avatar
csongor committed
394

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

theos's avatar
theos committed
398
399
        # 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
400
            return Field.scalar(data)
csongor's avatar
csongor committed
401
        else:
Martin Reinecke's avatar
Martin Reinecke committed
402
            return_domain = tuple(dom
Martin Reinecke's avatar
Martin Reinecke committed
403
                                  for i, dom in enumerate(self._domain)
theos's avatar
theos committed
404
                                  if i not in spaces)
405

406
            return Field(DomainTuple.make(return_domain), data)
csongor's avatar
csongor committed
407

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

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

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

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

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

434
    def integrate(self, spaces=None):
Martin Reinecke's avatar
Martin Reinecke committed
435
436
437
438
439
440
441
        """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
442
        spaces : None, int or tuple of int
Martin Reinecke's avatar
Martin Reinecke committed
443
444
445
446
447
            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
448
449
        Field
            The result of the integration.
Martin Reinecke's avatar
Martin Reinecke committed
450
        """
Martin Reinecke's avatar
Martin Reinecke committed
451
452
453
        swgt = self.scalar_weight(spaces)
        if swgt is not None:
            res = self.sum(spaces)
Martin Reinecke's avatar
fixes    
Martin Reinecke committed
454
            res = res*swgt
Martin Reinecke's avatar
Martin Reinecke committed
455
            return res
456
457
458
        tmp = self.weight(1, spaces=spaces)
        return tmp.sum(spaces)

Martin Reinecke's avatar
Martin Reinecke committed
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
    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()

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

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

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

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

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

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

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

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

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
#         -------
Martin Reinecke's avatar
Martin Reinecke committed
519
520
#         Field
#             The result of the operation.
521
522
523
524
525
526
527
528
529
530
531
532
533
534
#         """
#         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
535
536
#         Field
#             The result of the operation.
537
538
#         """
#         return self._contraction_helper('max', spaces)
csongor's avatar
csongor committed
539

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

        Returns
        -------
Martin Reinecke's avatar
Martin Reinecke committed
554
555
        Field
            The result of the operation.
Martin Reinecke's avatar
Martin Reinecke committed
556
        """
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

Martin Reinecke's avatar
Martin Reinecke committed
564
565
566
567
568
569
570
571
572
573
574
575
576
    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()

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

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

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

Martin Reinecke's avatar
Martin Reinecke committed
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
    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()

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

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

Martin Reinecke's avatar
Martin Reinecke committed
645
646
647
648
649
650
651
652
653
654
655
656
657
658
    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())

theos's avatar
theos committed
659
    def __repr__(self):
Martin Reinecke's avatar
Martin Reinecke committed
660
        return "<nifty7.Field>"
theos's avatar
theos committed
661
662

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

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

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

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

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

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

Martin Reinecke's avatar
Martin Reinecke committed
694
695
696
697
    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
698
699
700
701
        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
702
703
704
705
706
        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
707
708
709
710
        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
711
        argstmp, kwargstmp = self._prep_args(args, kwargs)
Martin Reinecke's avatar
misc    
Martin Reinecke committed
712
713
        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
714

Philipp Arras's avatar
Cleanup    
Philipp Arras committed
715

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

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