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
csongor's avatar
csongor committed
19
import numpy as np
20

Martin Reinecke's avatar
stage 1    
Martin Reinecke committed
21
from . import utilities
Martin Reinecke's avatar
Martin Reinecke committed
22
from .domain_tuple import DomainTuple
23

24

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
    domain : DomainTuple
Philipp Arras's avatar
Docs    
Philipp Arras committed
34
        The domain of the new Field.
Martin Reinecke's avatar
Martin Reinecke committed
35
36
    val : numpy.ndarray
        This object's shape must match the domain shape
37
        After construction, the object will no longer be writeable!
Martin Reinecke's avatar
Martin Reinecke committed
38

Martin Reinecke's avatar
Martin Reinecke committed
39
40
    Notes
    -----
Martin Reinecke's avatar
Martin Reinecke committed
41
    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
stage 1    
Martin Reinecke committed
50
        if not isinstance(val, np.ndarray):
Martin Reinecke's avatar
Martin Reinecke committed
51
            if np.isscalar(val):
Martin Reinecke's avatar
stage 1    
Martin Reinecke committed
52
                val = np.full(domain.shape, val)
Martin Reinecke's avatar
Martin Reinecke committed
53
            else:
Martin Reinecke's avatar
stage 1    
Martin Reinecke committed
54
                raise TypeError("val must be of type numpy.ndarray")
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
Martin Reinecke's avatar
stage 1    
Martin Reinecke committed
59
        self._val.flags.writeable = False
Martin Reinecke's avatar
Martin Reinecke committed
60

Martin Reinecke's avatar
Martin Reinecke committed
61
62
63
64
65
66
67
68
69
70
    @property
    def sing(self):
        return self

    @property
    def mult(self):
        """returns equivalent MultiField"""
        from .multi_field import MultiField
        return MultiField(self._domain.mult, (self,))

Martin Reinecke's avatar
Martin Reinecke committed
71
72
73
74
    @staticmethod
    def scalar(val):
        return Field(Field._scalar_dom, val)

75
76
77
78
79
80
81
    # 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")

82
    @staticmethod
83
    def full(domain, val):
Martin Reinecke's avatar
Martin Reinecke committed
84
85
86
87
88
        """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
89
            Domain of the new Field.
Martin Reinecke's avatar
Martin Reinecke committed
90
        val : float/complex/int scalar
Philipp Arras's avatar
Docs    
Philipp Arras committed
91
            Fill value. Data type of the field is inferred from val.
Martin Reinecke's avatar
Martin Reinecke committed
92
93
94
95

        Returns
        -------
        Field
Philipp Arras's avatar
Docs    
Philipp Arras committed
96
            The newly created Field.
Martin Reinecke's avatar
Martin Reinecke committed
97
        """
98
99
        if not np.isscalar(val):
            raise TypeError("val must be a scalar")
100
101
102
        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
103
        return Field(domain, val)
104

105
    @staticmethod
Martin Reinecke's avatar
Martin Reinecke committed
106
    def from_raw(domain, arr):
Martin Reinecke's avatar
Martin Reinecke committed
107
108
109
110
111
        """Returns a Field constructed from `domain` and `arr`.

        Parameters
        ----------
        domain : DomainTuple, tuple of Domain, or Domain
Philipp Arras's avatar
Docs    
Philipp Arras committed
112
            The domain of the new Field.
Martin Reinecke's avatar
Martin Reinecke committed
113
114
115
116
        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
117
        return Field(DomainTuple.make(domain), arr)
Martin Reinecke's avatar
Martin Reinecke committed
118

Martin Reinecke's avatar
Martin Reinecke committed
119
    def cast_domain(self, new_domain):
Martin Reinecke's avatar
Martin Reinecke committed
120
121
122
123
124
125
126
127
128
129
130
        """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
131
            Field defined on `new_domain`, but with the same data as `self`.
Martin Reinecke's avatar
Martin Reinecke committed
132
        """
133
        return Field(DomainTuple.make(new_domain), self._val)
134

Martin Reinecke's avatar
Martin Reinecke committed
135
136
    @staticmethod
    def from_random(random_type, domain, dtype=np.float64, **kwargs):
137
        """Draws a random field with the given parameters.
138
139
140

        Parameters
        ----------
Martin Reinecke's avatar
Martin Reinecke committed
141
142
        random_type : 'pm1', 'normal', or 'uniform'
            The random distribution to use.
Martin Reinecke's avatar
Martin Reinecke committed
143
        domain : DomainTuple
Philipp Arras's avatar
Docs    
Philipp Arras committed
144
            The domain of the output random Field.
145
        dtype : type
Philipp Arras's avatar
Docs    
Philipp Arras committed
146
            The datatype of the output random Field.
Theo Steininger's avatar
Theo Steininger committed
147

148
149
        Returns
        -------
Martin Reinecke's avatar
Martin Reinecke committed
150
        Field
Martin Reinecke's avatar
Martin Reinecke committed
151
            The newly created Field.
152
        """
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
153
        from .random import Random
Martin Reinecke's avatar
Martin Reinecke committed
154
        domain = DomainTuple.make(domain)
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
155
156
157
        generator_function = getattr(Random, random_type)
        arr = generator_function(dtype=dtype, shape=domain.shape, **kwargs)
        return Field(domain, arr)
158

Theo Steininger's avatar
Theo Steininger committed
159
160
    @property
    def val(self):
Martin Reinecke's avatar
Martin Reinecke committed
161
        """numpy.ndarray : the array storing the field's entries.
Martin Reinecke's avatar
Martin Reinecke committed
162

Martin Reinecke's avatar
Martin Reinecke committed
163
164
        Notes
        -----
Martin Reinecke's avatar
Martin Reinecke committed
165
        The returned array is read-only.
166
        """
Martin Reinecke's avatar
Martin Reinecke committed
167
        return self._val
csongor's avatar
csongor committed
168

Martin Reinecke's avatar
Martin Reinecke committed
169
170
171
172
173
    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
174
175
    @property
    def dtype(self):
Martin Reinecke's avatar
Martin Reinecke committed
176
        """type : the data type of the field's entries"""
Martin Reinecke's avatar
Martin Reinecke committed
177
178
        return self._val.dtype

Martin Reinecke's avatar
Martin Reinecke committed
179
180
    @property
    def domain(self):
Martin Reinecke's avatar
Martin Reinecke committed
181
        """DomainTuple : the field's domain"""
Martin Reinecke's avatar
Martin Reinecke committed
182
183
        return self._domain

184
    @property
185
186
187
    def target(self):
        """DomainTuple : the field's domain"""
        return self._domain
csongor's avatar
csongor committed
188

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Theo Steininger's avatar
Theo Steininger committed
374
    # ---General unary/contraction methods---
375

Theo Steininger's avatar
Theo Steininger committed
376
    def __pos__(self):
377
        return self
378

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Martin Reinecke's avatar
Martin Reinecke committed
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
538
539
540
541
542
543
544
545
    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
            The result of the operation.
        """
        return self._contraction_helper('min', spaces)

    def s_min(self):
        return self._val.min()

    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
            The result of the operation.
        """
        return self._contraction_helper('max', spaces)

    def s_max(self):
        return self._val.max()
csongor's avatar
csongor committed
546

547
    def mean(self, spaces=None):
Martin Reinecke's avatar
Martin Reinecke committed
548
549
550
551
552
553
554
        """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
555
        spaces : None, int or tuple of int
Martin Reinecke's avatar
Martin Reinecke committed
556
            The operation is only carried out over the sub-domains in this
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
557
            tuple. If None, it is carried out over all sub-domains.
Martin Reinecke's avatar
Martin Reinecke committed
558
559
560

        Returns
        -------
Martin Reinecke's avatar
Martin Reinecke committed
561
562
        Field
            The result of the operation.
Martin Reinecke's avatar
Martin Reinecke committed
563
        """
564
565
        if self.scalar_weight(spaces) is not None:
            return self._contraction_helper('mean', spaces)
Martin Reinecke's avatar
Martin Reinecke committed
566
        # MR FIXME: not very efficient
567
568
        # MR FIXME: do we need "spaces" here?
        tmp = self.weight(1, spaces)
Martin Reinecke's avatar
Martin Reinecke committed
569
        return tmp.sum(spaces)*(1./tmp.total_volume(spaces))
csongor's avatar
csongor committed
570

Martin Reinecke's avatar
Martin Reinecke committed
571
572
573
574
575
576
577
578
579
580
581
582
583
    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()

584
    def var(self, spaces=None):
Martin Reinecke's avatar
Martin Reinecke committed
585
586
587
588
        """Determines the variance over the sub-domains given by `spaces`.

        Parameters
        ----------
Philipp Arras's avatar
Philipp Arras committed
589
        spaces : None, int or tuple of int
Martin Reinecke's avatar
Martin Reinecke committed
590
591
            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
592
            Default: None.
Martin Reinecke's avatar
Martin Reinecke committed
593
594
595

        Returns
        -------
Martin Reinecke's avatar
Martin Reinecke committed
596
597
        Field
            The result of the operation.
Martin Reinecke's avatar
Martin Reinecke committed
598
        """
599
600
        if self.scalar_weight(spaces) is not None:
            return self._contraction_helper('var', spaces)
Martin Reinecke's avatar
Martin Reinecke committed
601
602
        # MR FIXME: not very efficient or accurate
        m1 = self.mean(spaces)
Martin Reinecke's avatar
fixes    
Martin Reinecke committed
603
604
        from .operators.contraction_operator import ContractionOperator
        op = ContractionOperator(self._domain, spaces)
Martin Reinecke's avatar
more    
Martin Reinecke committed
605
        m1 = op.adjoint_times(m1.mult).sing
Martin Reinecke's avatar
Martin Reinecke committed
606
        if utilities.iscomplextype(self.dtype):
607
            sq = abs(self-m1)**2
Martin Reinecke's avatar
Martin Reinecke committed
608
        else:
609
610
            sq = (self-m1)**2
        return sq.mean(spaces)
csongor's avatar
csongor committed
611

Martin Reinecke's avatar
Martin Reinecke committed
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
    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()

630
    def std(self, spaces=None):
Martin Reinecke's avatar
Martin Reinecke committed
631
632
633
634
635
636
637
        """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
638
        spaces : None, int or tuple of int
Martin Reinecke's avatar
Martin Reinecke committed
639
640
            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
641
            Default: None.
Martin Reinecke's avatar
Martin Reinecke committed
642
643
644

        Returns
        -------
Martin Reinecke's avatar
Martin Reinecke committed
645
646
        Field
            The result of the operation.
Martin Reinecke's avatar
Martin Reinecke committed
647
        """
648
        from .sugar import sqrt
649
650
651
        if self.scalar_weight(spaces) is not None:
            return self._contraction_helper('std', spaces)
        return sqrt(self.var(spaces))
csongor's avatar
csongor committed
652

Martin Reinecke's avatar
Martin Reinecke committed
653
654
655
656
657
658
659
660
661
662
663
664
665
666
    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
667
    def __repr__(self):
Martin Reinecke's avatar
5->6    
Martin Reinecke committed
668
        return "<nifty6.Field>"
Theo Steininger's avatar
Theo Steininger committed
669
670

    def __str__(self):
Martin Reinecke's avatar
5->6    
Martin Reinecke committed
671
        return "nifty6.Field instance\n- domain      = " + \
672
               self._domain.__str__() + \
Martin Reinecke's avatar
Martin Reinecke committed
673
               "\n- val         = " + repr(self._val)
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
674

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

680
681
682
    def extract_part(self, dom):
        if dom != self._domain:
            raise ValueError("domain mismatch")
Martin Reinecke's avatar
more    
Martin Reinecke committed
683
684
685
        return self

    def unite(self, other):
Martin Reinecke's avatar
Martin Reinecke committed
686
687
688
689
        return self+other

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

691
    def sigmoid(self):
Martin Reinecke's avatar
Martin Reinecke committed
692
693
        return 0.5*(1.+self.tanh())

Martin Reinecke's avatar
Martin Reinecke committed
694
    def clip(self, min=None, max=None):
Martin Reinecke's avatar
stage 1    
Martin Reinecke committed
695
696
697
        min = min.val if isinstance(min, Field) else min
        max = max.val if isinstance(max, Field) else max
        return Field(self._domain, np.clip(self._val, min, max))
698

Martin Reinecke's avatar
Martin Reinecke committed
699
700
701
702
703
    def where(self, iftrue, iffalse):
        iftrue = itrue.val if isinstance(iftrue, Field) else iftrue
        iffalse = iffalse.val if isinstance(iffalse, Field) else iffalse
        return Field(self._domain, np.where(self._val, iftrue, iffalse))

704
705
706
    def one_over(self):
        return 1/self

Martin Reinecke's avatar
Martin Reinecke committed
707
708
709
710
    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
711
            if other._domain != self._domain:
Martin Reinecke's avatar
Martin Reinecke committed
712
713
714
715
716
                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
717

Martin Reinecke's avatar
Martin Reinecke committed
718

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

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
741

742
743
for f in ["sqrt", "exp", "log", "sin", "cos", "tan", "sinh", "cosh", "tanh",
          "absolute", "sinc", "sign", "log10", "log1p", "expm1"]:
Martin Reinecke's avatar
Martin Reinecke committed
744
745
    def func(f):
        def func2(self):
Martin Reinecke's avatar
stage 1    
Martin Reinecke committed
746
            return Field(self._domain, getattr(np, f)(self.val))
Martin Reinecke's avatar
Martin Reinecke committed
747
748
        return func2
    setattr(Field, f, func(f))