field.py 31.1 KB
Newer Older
csongor's avatar
csongor committed
1
2
3
from __future__ import division
import numpy as np

4
from d2o import distributed_data_object,\
5
    STRATEGIES as DISTRIBUTION_STRATEGIES
csongor's avatar
csongor committed
6

7
from nifty.config import nifty_configuration as gc
csongor's avatar
csongor committed
8

9
from nifty.field_types import FieldType
10

11
from nifty.spaces.space import Space
12
from nifty.spaces.power_space import PowerSpace
csongor's avatar
csongor committed
13

csongor's avatar
csongor committed
14
import nifty.nifty_utilities as utilities
15
16
from nifty.random import Random

17
from keepers import Loggable
18

csongor's avatar
csongor committed
19

20
class Field(object, Loggable):
theos's avatar
theos committed
21
    # ---Initialization methods---
22

theos's avatar
theos committed
23
    def __init__(self, domain=None, val=None, dtype=None, field_type=None,
24
                 distribution_strategy=None, copy=False):
csongor's avatar
csongor committed
25

26
        self.domain = self._parse_domain(domain=domain, val=val)
27
        self.domain_axes = self._get_axes_tuple(self.domain)
csongor's avatar
csongor committed
28

29
        self.field_type = self._parse_field_type(field_type, val=val)
30

theos's avatar
theos committed
31
32
33
34
35
36
        try:
            start = len(reduce(lambda x, y: x+y, self.domain_axes))
        except TypeError:
            start = 0
        self.field_type_axes = self._get_axes_tuple(self.field_type,
                                                    start=start)
37

theos's avatar
theos committed
38
        self.dtype = self._infer_dtype(dtype=dtype,
Jait Dixit's avatar
Jait Dixit committed
39
                                       val=val,
theos's avatar
theos committed
40
41
                                       domain=self.domain,
                                       field_type=self.field_type)
42

43
44
45
        self.distribution_strategy = self._parse_distribution_strategy(
                                distribution_strategy=distribution_strategy,
                                val=val)
csongor's avatar
csongor committed
46
47
48

        self.set_val(new_val=val, copy=copy)

49
    def _parse_domain(self, domain, val=None):
50
        if domain is None:
51
52
53
54
            if isinstance(val, Field):
                domain = val.domain
            else:
                domain = ()
55
        elif isinstance(domain, Space):
56
            domain = (domain,)
57
58
59
        elif not isinstance(domain, tuple):
            domain = tuple(domain)

csongor's avatar
csongor committed
60
        for d in domain:
61
            if not isinstance(d, Space):
62
63
64
                raise TypeError(
                    "Given domain contains something that is not a "
                    "nifty.space.")
csongor's avatar
csongor committed
65
66
        return domain

67
    def _parse_field_type(self, field_type, val=None):
68
        if field_type is None:
69
70
71
72
            if isinstance(val, Field):
                field_type = val.field_type
            else:
                field_type = ()
73
        elif isinstance(field_type, FieldType):
74
            field_type = (field_type,)
75
76
        elif not isinstance(field_type, tuple):
            field_type = tuple(field_type)
77
        for ft in field_type:
78
            if not isinstance(ft, FieldType):
79
80
                raise TypeError(
                    "Given object is not a nifty.FieldType.")
81
82
        return field_type

theos's avatar
theos committed
83
84
85
86
87
88
89
90
91
92
    def _get_axes_tuple(self, things_with_shape, start=0):
        i = start
        axes_list = []
        for thing in things_with_shape:
            l = []
            for j in range(len(thing.shape)):
                l += [i]
                i += 1
            axes_list += [tuple(l)]
        return tuple(axes_list)
93

94
    def _infer_dtype(self, dtype, val, domain, field_type):
csongor's avatar
csongor committed
95
        if dtype is None:
96
97
98
            if isinstance(val, Field) or \
               isinstance(val, distributed_data_object):
                dtype = val.dtype
theos's avatar
theos committed
99
100
101
102
103
104
105
            dtype_tuple = (np.dtype(gc['default_field_dtype']),)
        else:
            dtype_tuple = (np.dtype(dtype),)
        if domain is not None:
            dtype_tuple += tuple(np.dtype(sp.dtype) for sp in domain)
        if field_type is not None:
            dtype_tuple += tuple(np.dtype(ft.dtype) for ft in field_type)
csongor's avatar
csongor committed
106

theos's avatar
theos committed
107
        dtype = reduce(lambda x, y: np.result_type(x, y), dtype_tuple)
108

theos's avatar
theos committed
109
        return dtype
110

111
112
    def _parse_distribution_strategy(self, distribution_strategy, val):
        if distribution_strategy is None:
113
            if isinstance(val, distributed_data_object):
114
                distribution_strategy = val.distribution_strategy
115
            elif isinstance(val, Field):
116
                distribution_strategy = val.distribution_strategy
117
            else:
118
                self.logger.info("Datamodel set to default!")
119
                distribution_strategy = gc['default_distribution_strategy']
120
        elif distribution_strategy not in DISTRIBUTION_STRATEGIES['global']:
121
122
123
            raise ValueError(
                    "distribution_strategy must be a global-type "
                    "strategy.")
124
        return distribution_strategy
125
126

    # ---Factory methods---
127

128
129
    @classmethod
    def from_random(cls, random_type, domain=None, dtype=None, field_type=None,
130
                    distribution_strategy=None, **kwargs):
131
132
        # create a initially empty field
        f = cls(domain=domain, dtype=dtype, field_type=field_type,
133
                distribution_strategy=distribution_strategy)
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168

        # now use the processed input in terms of f in order to parse the
        # random arguments
        random_arguments = cls._parse_random_arguments(random_type=random_type,
                                                       f=f,
                                                       **kwargs)

        # extract the distributed_dato_object from f and apply the appropriate
        # random number generator to it
        sample = f.get_val(copy=False)
        generator_function = getattr(Random, random_type)
        sample.apply_generator(
            lambda shape: generator_function(dtype=f.dtype,
                                             shape=shape,
                                             **random_arguments))
        return f

    @staticmethod
    def _parse_random_arguments(random_type, f, **kwargs):

        if random_type == "pm1":
            random_arguments = {}

        elif random_type == "normal":
            mean = kwargs.get('mean', 0)
            std = kwargs.get('std', 1)
            random_arguments = {'mean': mean,
                                'std': std}

        elif random_type == "uniform":
            low = kwargs.get('low', 0)
            high = kwargs.get('high', 1)
            random_arguments = {'low': low,
                                'high': high}

csongor's avatar
csongor committed
169
        else:
170
171
            raise KeyError(
                "unsupported random key '" + str(random_type) + "'.")
csongor's avatar
csongor committed
172

173
        return random_arguments
csongor's avatar
csongor committed
174

175
176
177
178
179
180
181
182
183
    # ---Powerspectral methods---

    def power_analyze(self, spaces=None, log=False, nbin=None, binbounds=None,
                      real_signal=True):
        # assert that all spaces in `self.domain` are either harmonic or
        # power_space instances
        for sp in self.domain:
            if not sp.harmonic and not isinstance(sp, PowerSpace):
                raise AttributeError(
184
                    "Field has a space in `domain` which is neither "
185
186
187
                    "harmonic nor a PowerSpace.")

        # check if the `spaces` input is valid
188
189
190
191
192
        spaces = utilities.cast_axis_to_tuple(spaces, len(self.domain))
        if spaces is None:
            if len(self.domain) == 1:
                spaces = (0,)
            else:
193
194
195
                raise ValueError(
                    "Field has multiple spaces as domain "
                    "but `spaces` is None.")
196
197

        if len(spaces) == 0:
198
199
            raise ValueError(
                "No space for analysis specified.")
200
        elif len(spaces) > 1:
201
202
            raise ValueError(
                "Conversion of only one space at a time is allowed.")
203
204
205
206

        space_index = spaces[0]

        if not self.domain[space_index].harmonic:
207
208
            raise ValueError(
                "The analyzed space must be harmonic.")
209

210
211
212
213
214
215
        # Create the target PowerSpace instance:
        # If the associated signal-space field was real, we extract the
        # hermitian and anti-hermitian parts of `self` and put them
        # into the real and imaginary parts of the power spectrum.
        # If it was complex, all the power is put into a real power spectrum.

216
217
218
219
        distribution_strategy = \
            self.val.get_axes_local_distribution_strategy(
                self.domain_axes[space_index])

220
221
222
223
224
        if real_signal:
            power_dtype = np.dtype('complex')
        else:
            power_dtype = np.dtype('float')

225
226
        harmonic_domain = self.domain[space_index]
        power_domain = PowerSpace(harmonic_domain=harmonic_domain,
227
                                  distribution_strategy=distribution_strategy,
228
229
                                  log=log, nbin=nbin, binbounds=binbounds,
                                  dtype=power_dtype)
230

231
        # extract pindex and rho from power_domain
232
233
        pindex = power_domain.pindex
        rho = power_domain.rho
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251

        if real_signal:
            hermitian_part, anti_hermitian_part = \
                harmonic_domain.hermitian_decomposition(
                                            self.val,
                                            axes=self.domain_axes[space_index])

            [hermitian_power, anti_hermitian_power] = \
                [self._calculate_power_spectrum(
                                            x=part,
                                            pindex=pindex,
                                            rho=rho,
                                            axes=self.domain_axes[space_index])
                 for part in [hermitian_part, anti_hermitian_part]]

            power_spectrum = hermitian_power + 1j * anti_hermitian_power
        else:
            power_spectrum = self._calculate_power_spectrum(
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
                                            x=self.val,
                                            pindex=pindex,
                                            rho=rho,
                                            axes=self.domain_axes[space_index])

        # create the result field and put power_spectrum into it
        result_domain = list(self.domain)
        result_domain[space_index] = power_domain

        result_field = self.copy_empty(domain=result_domain)
        result_field.set_val(new_val=power_spectrum, copy=False)

        return result_field

    def _calculate_power_spectrum(self, x, pindex, rho, axes=None):
        fieldabs = abs(x)
        fieldabs **= 2

        if axes is not None:
            pindex = self._shape_up_pindex(
                                    pindex=pindex,
                                    target_shape=x.shape,
                                    target_strategy=x.distribution_strategy,
                                    axes=axes)
        power_spectrum = pindex.bincount(weights=fieldabs,
                                         axis=axes)
        if axes is not None:
            new_rho_shape = [1, ] * len(power_spectrum.shape)
            new_rho_shape[axes[0]] = len(rho)
            rho = rho.reshape(new_rho_shape)
        power_spectrum /= rho

        power_spectrum **= 0.5
        return power_spectrum

    def _shape_up_pindex(self, pindex, target_shape, target_strategy, axes):
        if pindex.distribution_strategy not in \
                DISTRIBUTION_STRATEGIES['global']:
290
            raise ValueError("pindex's distribution strategy must be "
291
292
293
294
295
296
                             "global-type")

        if pindex.distribution_strategy in DISTRIBUTION_STRATEGIES['slicing']:
            if ((0 not in axes) or
                    (target_strategy is not pindex.distribution_strategy)):
                raise ValueError(
297
                    "A slicing distributor shall not be reshaped to "
298
299
300
301
302
303
304
305
306
307
308
309
310
                    "something non-sliced.")

        semiscaled_shape = [1, ] * len(target_shape)
        for i in axes:
            semiscaled_shape[i] = target_shape[i]
        local_data = pindex.get_local_data(copy=False)
        semiscaled_local_data = local_data.reshape(semiscaled_shape)
        result_obj = pindex.copy_empty(global_shape=target_shape,
                                       distribution_strategy=target_strategy)
        result_obj.set_full_data(semiscaled_local_data, copy=False)

        return result_obj

311
312
    def power_synthesize(self, spaces=None, real_signal=True,
                         mean=None, std=None):
313
        # assert that all spaces in `self.domain` are either of signal-type or
314
315
        # power_space instances
        for sp in self.domain:
316
            if not sp.harmonic and not isinstance(sp, PowerSpace):
317
                raise AttributeError(
318
                    "Field has a space in `domain` which is neither "
319
320
                    "harmonic nor a PowerSpace.")

321
322
323
324
325
326
        # check if the `spaces` input is valid
        spaces = utilities.cast_axis_to_tuple(spaces, len(self.domain))
        if spaces is None:
            if len(self.domain) == 1:
                spaces = (0,)
            else:
327
328
329
                raise ValueError(
                    "Field has multiple spaces as domain "
                    "but `spaces` is None.")
330
331

        if len(spaces) == 0:
332
333
            raise ValueError(
                "No space for synthesis specified.")
334
        elif len(spaces) > 1:
335
336
            raise ValueError(
                "Conversion of only one space at a time is allowed.")
337
338
339
340

        power_space_index = spaces[0]
        power_domain = self.domain[power_space_index]
        if not isinstance(power_domain, PowerSpace):
341
342
            raise ValueError(
                "A PowerSpace is needed for field synthetization.")
343
344
345
346
347
348
349
350
351
352
353
354
355
356

        # create the result domain
        result_domain = list(self.domain)
        harmonic_domain = power_domain.harmonic_domain
        result_domain[power_space_index] = harmonic_domain

        # create random samples: one or two, depending on whether the
        # power spectrum is real or complex

        if issubclass(power_domain.dtype.type, np.complexfloating):
            result_list = [None, None]
        else:
            result_list = [None]

357
358
        result_list = [self.__class__.from_random(
                             'normal',
359
360
361
                             mean=mean,
                             std=std,
                             domain=result_domain,
362
363
364
                             dtype=harmonic_domain.dtype,
                             field_type=self.field_type,
                             distribution_strategy=self.distribution_strategy)
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
                       for x in result_list]

        # from now on extract the values from the random fields for further
        # processing without killing the fields.
        # if the signal-space field should be real, hermitianize the field
        # components
        if real_signal:
            result_val_list = [harmonic_domain.hermitian_decomposition(
                                    x.val,
                                    axes=x.domain_axes[power_space_index])[0]
                               for x in result_list]
        else:
            result_val_list = [x.val for x in result_list]

        # weight the random fields with the power spectrum
        # therefore get the pindex from the power space
        pindex = power_domain.pindex
        # take the local data from pindex. This data must be compatible to the
        # local data of the field given the slice of the PowerSpace
        local_distribution_strategy = \
            result_list[0].val.get_axes_local_distribution_strategy(
                result_list[0].domain_axes[power_space_index])

        if pindex.distribution_strategy is not local_distribution_strategy:
389
            self.logger.warn(
390
                "The distribution_stragey of pindex does not fit the "
391
392
393
394
395
396
                "slice_local distribution strategy of the synthesized field.")

        # Now use numpy advanced indexing in order to put the entries of the
        # power spectrum into the appropriate places of the pindex array.
        # Do this for every 'pindex-slice' in parallel using the 'slice(None)'s
        local_pindex = pindex.get_local_data(copy=False)
theos's avatar
theos committed
397
        full_spec = self.val.get_full_data()
398
399
400
401
402

        local_blow_up = [slice(None)]*len(self.shape)
        local_blow_up[self.domain_axes[power_space_index][0]] = local_pindex

        # here, the power_spectrum is distributed into the new shape
theos's avatar
theos committed
403
        local_rescaler = full_spec[local_blow_up]
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424

        # apply the rescaler to the random fields
        result_val_list[0].apply_scalar_function(
                                            lambda x: x * local_rescaler.real,
                                            inplace=True)

        if issubclass(power_domain.dtype.type, np.complexfloating):
            result_val_list[1].apply_scalar_function(
                                            lambda x: x * local_rescaler.imag,
                                            inplace=True)

        # store the result into the fields
        [x.set_val(new_val=y, copy=False) for x, y in
            zip(result_list, result_val_list)]

        if issubclass(power_domain.dtype.type, np.complexfloating):
            result = result_list[0] + 1j*result_list[1]
        else:
            result = result_list[0]

        return result
425

theos's avatar
theos committed
426
    # ---Properties---
427

theos's avatar
theos committed
428
    def set_val(self, new_val=None, copy=False):
429
430
        new_val = self.cast(new_val)
        if copy:
theos's avatar
theos committed
431
432
433
            new_val = new_val.copy()
        self._val = new_val
        return self._val
csongor's avatar
csongor committed
434

435
436
    def get_val(self, copy=False):
        if copy:
theos's avatar
theos committed
437
            return self._val.copy()
438
        else:
theos's avatar
theos committed
439
            return self._val
csongor's avatar
csongor committed
440

theos's avatar
theos committed
441
442
443
    @property
    def val(self):
        return self._val
csongor's avatar
csongor committed
444

theos's avatar
theos committed
445
446
447
    @val.setter
    def val(self, new_val):
        self._val = self.cast(new_val)
csongor's avatar
csongor committed
448

449
450
    @property
    def shape(self):
451
452
453
454
455
456
457
        shape_tuple = ()
        shape_tuple += tuple(sp.shape for sp in self.domain)
        shape_tuple += tuple(ft.shape for ft in self.field_type)
        try:
            global_shape = reduce(lambda x, y: x + y, shape_tuple)
        except TypeError:
            global_shape = ()
csongor's avatar
csongor committed
458

459
        return global_shape
csongor's avatar
csongor committed
460

461
462
    @property
    def dim(self):
theos's avatar
theos committed
463
464
465
466
467
468
469
        dim_tuple = ()
        dim_tuple += tuple(sp.dim for sp in self.domain)
        dim_tuple += tuple(ft.dim for ft in self.field_type)
        try:
            return reduce(lambda x, y: x * y, dim_tuple)
        except TypeError:
            return 0
csongor's avatar
csongor committed
470

471
472
    @property
    def dof(self):
theos's avatar
theos committed
473
474
475
476
477
478
479
480
        dof = self.dim
        if issubclass(self.dtype.type, np.complexfloating):
            dof *= 2
        return dof

    @property
    def total_volume(self):
        volume_tuple = tuple(sp.total_volume for sp in self.domain)
481
        try:
theos's avatar
theos committed
482
            return reduce(lambda x, y: x * y, volume_tuple)
483
        except TypeError:
theos's avatar
theos committed
484
            return 0
485

theos's avatar
theos committed
486
    # ---Special unary/binary operations---
487

csongor's avatar
csongor committed
488
489
490
    def cast(self, x=None, dtype=None):
        if dtype is None:
            dtype = self.dtype
491
492
        else:
            dtype = np.dtype(dtype)
493

494
495
        casted_x = x

496
        for ind, sp in enumerate(self.domain):
497
            casted_x = sp.pre_cast(casted_x,
498
499
500
501
502
503
504
                                   axes=self.domain_axes[ind])

        for ind, ft in enumerate(self.field_type):
            casted_x = ft.pre_cast(casted_x,
                                   axes=self.field_type_axes[ind])

        casted_x = self._actual_cast(casted_x, dtype=dtype)
505
506

        for ind, sp in enumerate(self.domain):
507
508
            casted_x = sp.post_cast(casted_x,
                                    axes=self.domain_axes[ind])
509
510

        for ind, ft in enumerate(self.field_type):
511
512
            casted_x = ft.post_cast(casted_x,
                                    axes=self.field_type_axes[ind])
513
514

        return casted_x
csongor's avatar
csongor committed
515

theos's avatar
theos committed
516
    def _actual_cast(self, x, dtype=None):
517
        if isinstance(x, Field):
csongor's avatar
csongor committed
518
519
520
521
522
            x = x.get_val()

        if dtype is None:
            dtype = self.dtype

523
        return_x = distributed_data_object(
524
525
526
                            global_shape=self.shape,
                            dtype=dtype,
                            distribution_strategy=self.distribution_strategy)
527
528
        return_x.set_full_data(x, copy=False)
        return return_x
theos's avatar
theos committed
529
530

    def copy(self, domain=None, dtype=None, field_type=None,
531
             distribution_strategy=None):
theos's avatar
theos committed
532
        copied_val = self.get_val(copy=True)
533
534
535
536
537
        new_field = self.copy_empty(
                                domain=domain,
                                dtype=dtype,
                                field_type=field_type,
                                distribution_strategy=distribution_strategy)
theos's avatar
theos committed
538
539
        new_field.set_val(new_val=copied_val, copy=False)
        return new_field
csongor's avatar
csongor committed
540

theos's avatar
theos committed
541
    def copy_empty(self, domain=None, dtype=None, field_type=None,
542
                   distribution_strategy=None):
theos's avatar
theos committed
543
544
        if domain is None:
            domain = self.domain
csongor's avatar
csongor committed
545
        else:
theos's avatar
theos committed
546
            domain = self._parse_domain(domain)
csongor's avatar
csongor committed
547

theos's avatar
theos committed
548
549
550
551
        if dtype is None:
            dtype = self.dtype
        else:
            dtype = np.dtype(dtype)
csongor's avatar
csongor committed
552

theos's avatar
theos committed
553
554
555
556
        if field_type is None:
            field_type = self.field_type
        else:
            field_type = self._parse_field_type(field_type)
csongor's avatar
csongor committed
557

558
559
        if distribution_strategy is None:
            distribution_strategy = self.distribution_strategy
csongor's avatar
csongor committed
560

theos's avatar
theos committed
561
562
563
564
565
566
567
568
569
570
571
572
573
574
        fast_copyable = True
        try:
            for i in xrange(len(self.domain)):
                if self.domain[i] is not domain[i]:
                    fast_copyable = False
                    break
            for i in xrange(len(self.field_type)):
                if self.field_type[i] is not field_type[i]:
                    fast_copyable = False
                    break
        except IndexError:
            fast_copyable = False

        if (fast_copyable and dtype == self.dtype and
575
                distribution_strategy == self.distribution_strategy):
theos's avatar
theos committed
576
577
578
579
580
            new_field = self._fast_copy_empty()
        else:
            new_field = Field(domain=domain,
                              dtype=dtype,
                              field_type=field_type,
581
                              distribution_strategy=distribution_strategy)
theos's avatar
theos committed
582
        return new_field
csongor's avatar
csongor committed
583

theos's avatar
theos committed
584
585
586
587
588
589
590
    def _fast_copy_empty(self):
        # make an empty field
        new_field = EmptyField()
        # repair its class
        new_field.__class__ = self.__class__
        # copy domain, codomain and val
        for key, value in self.__dict__.items():
591
            if key != '_val':
theos's avatar
theos committed
592
593
594
595
596
597
                new_field.__dict__[key] = value
            else:
                new_field.__dict__[key] = self.val.copy_empty()
        return new_field

    def weight(self, power=1, inplace=False, spaces=None):
598
        if inplace:
csongor's avatar
csongor committed
599
600
601
602
            new_field = self
        else:
            new_field = self.copy_empty()

603
        new_val = self.get_val(copy=False)
csongor's avatar
csongor committed
604

csongor's avatar
csongor committed
605
        if spaces is None:
theos's avatar
theos committed
606
607
608
            spaces = range(len(self.domain))
        else:
            spaces = utilities.cast_axis_to_tuple(spaces, len(self.domain))
csongor's avatar
csongor committed
609

610
        for ind, sp in enumerate(self.domain):
theos's avatar
theos committed
611
612
613
614
615
            if ind in spaces:
                new_val = sp.weight(new_val,
                                    power=power,
                                    axes=self.domain_axes[ind],
                                    inplace=inplace)
616
617

        new_field.set_val(new_val=new_val, copy=False)
csongor's avatar
csongor committed
618
619
        return new_field

theos's avatar
theos committed
620
621
622
623
624
625
626
627
628
    def dot(self, x=None, bare=False):
        if isinstance(x, Field):
            try:
                assert len(x.domain) == len(self.domain)
                for index in xrange(len(self.domain)):
                    assert x.domain[index] == self.domain[index]
                for index in xrange(len(self.field_type)):
                    assert x.field_type[index] == self.field_type[index]
            except AssertionError:
629
630
                raise ValueError(
                    "domains are incompatible.")
theos's avatar
theos committed
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
            # extract the data from x and try to dot with this
            x = x.get_val(copy=False)

        # Compute the dot respecting the fact of discrete/continous spaces
        if bare:
            y = self
        else:
            y = self.weight(power=1)

        y = y.get_val(copy=False)

        # Cast the input in order to cure dtype and shape differences
        x = self.cast(x)

        dotted = x.conjugate() * y

        return dotted.sum()

649
    def norm(self, q=2):
csongor's avatar
csongor committed
650
651
652
653
654
655
656
657
658
659
660
661
662
663
        """
            Computes the Lq-norm of the field values.

            Parameters
            ----------
            q : scalar
                Parameter q of the Lq-norm (default: 2).

            Returns
            -------
            norm : scalar
                The Lq-norm of the field values.

        """
664
        if q == 2:
665
            return (self.dot(x=self)) ** (1 / 2)
csongor's avatar
csongor committed
666
        else:
667
            return self.dot(x=self ** (q - 1)) ** (1 / q)
csongor's avatar
csongor committed
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683

    def conjugate(self, inplace=False):
        """
            Computes the complex conjugate of the field.

            Returns
            -------
            cc : field
                The complex conjugated field.

        """
        if inplace:
            work_field = self
        else:
            work_field = self.copy_empty()

684
        new_val = self.get_val(copy=False)
theos's avatar
theos committed
685
        new_val = new_val.conjugate()
686
        work_field.set_val(new_val=new_val, copy=False)
csongor's avatar
csongor committed
687
688
689

        return work_field

theos's avatar
theos committed
690
    # ---General unary/contraction methods---
691

theos's avatar
theos committed
692
693
    def __pos__(self):
        return self.copy()
694

theos's avatar
theos committed
695
696
697
698
    def __neg__(self):
        return_field = self.copy_empty()
        new_val = -self.get_val(copy=False)
        return_field.set_val(new_val, copy=False)
csongor's avatar
csongor committed
699
700
        return return_field

theos's avatar
theos committed
701
702
703
704
705
    def __abs__(self):
        return_field = self.copy_empty()
        new_val = abs(self.get_val(copy=False))
        return_field.set_val(new_val, copy=False)
        return return_field
csongor's avatar
csongor committed
706

theos's avatar
theos committed
707
708
709
710
711
712
    def _contraction_helper(self, op, spaces, types):
        # build a list of all axes
        if spaces is None:
            spaces = xrange(len(self.domain))
        else:
            spaces = utilities.cast_axis_to_tuple(spaces, len(self.domain))
csongor's avatar
csongor committed
713

theos's avatar
theos committed
714
715
716
717
        if types is None:
            types = xrange(len(self.field_type))
        else:
            types = utilities.cast_axis_to_tuple(types, len(self.field_type))
718

theos's avatar
theos committed
719
720
721
722
        axes_list = ()
        axes_list += tuple(self.domain_axes[sp_index] for sp_index in spaces)
        axes_list += tuple(self.field_type_axes[ft_index] for
                           ft_index in types)
723
        try:
theos's avatar
theos committed
724
            axes_list = reduce(lambda x, y: x+y, axes_list)
725
        except TypeError:
theos's avatar
theos committed
726
            axes_list = ()
csongor's avatar
csongor committed
727

theos's avatar
theos committed
728
729
730
        # perform the contraction on the d2o
        data = self.get_val(copy=False)
        data = getattr(data, op)(axis=axes_list)
csongor's avatar
csongor committed
731

theos's avatar
theos committed
732
733
734
        # check if the result is scalar or if a result_field must be constr.
        if np.isscalar(data):
            return data
csongor's avatar
csongor committed
735
        else:
theos's avatar
theos committed
736
737
738
739
740
741
742
743
744
745
746
            return_domain = tuple(self.domain[i]
                                  for i in xrange(len(self.domain))
                                  if i not in spaces)
            return_field_type = tuple(self.field_type[i]
                                      for i in xrange(len(self.field_type))
                                      if i not in types)
            return_field = Field(domain=return_domain,
                                 val=data,
                                 field_type=return_field_type,
                                 copy=False)
            return return_field
csongor's avatar
csongor committed
747

theos's avatar
theos committed
748
749
    def sum(self, spaces=None, types=None):
        return self._contraction_helper('sum', spaces, types)
csongor's avatar
csongor committed
750

theos's avatar
theos committed
751
752
    def prod(self, spaces=None, types=None):
        return self._contraction_helper('prod', spaces, types)
csongor's avatar
csongor committed
753

theos's avatar
theos committed
754
755
    def all(self, spaces=None, types=None):
        return self._contraction_helper('all', spaces, types)
csongor's avatar
csongor committed
756

theos's avatar
theos committed
757
758
    def any(self, spaces=None, types=None):
        return self._contraction_helper('any', spaces, types)
csongor's avatar
csongor committed
759

theos's avatar
theos committed
760
761
    def min(self, spaces=None, types=None):
        return self._contraction_helper('min', spaces, types)
csongor's avatar
csongor committed
762

theos's avatar
theos committed
763
764
    def nanmin(self, spaces=None, types=None):
        return self._contraction_helper('nanmin', spaces, types)
csongor's avatar
csongor committed
765

theos's avatar
theos committed
766
767
    def max(self, spaces=None, types=None):
        return self._contraction_helper('max', spaces, types)
csongor's avatar
csongor committed
768

theos's avatar
theos committed
769
770
    def nanmax(self, spaces=None, types=None):
        return self._contraction_helper('nanmax', spaces, types)
csongor's avatar
csongor committed
771

theos's avatar
theos committed
772
773
    def mean(self, spaces=None, types=None):
        return self._contraction_helper('mean', spaces, types)
csongor's avatar
csongor committed
774

theos's avatar
theos committed
775
776
    def var(self, spaces=None, types=None):
        return self._contraction_helper('var', spaces, types)
csongor's avatar
csongor committed
777

theos's avatar
theos committed
778
779
    def std(self, spaces=None, types=None):
        return self._contraction_helper('std', spaces, types)
csongor's avatar
csongor committed
780

theos's avatar
theos committed
781
    # ---General binary methods---
csongor's avatar
csongor committed
782

theos's avatar
theos committed
783
    def _binary_helper(self, other, op, inplace=False):
csongor's avatar
csongor committed
784
        # if other is a field, make sure that the domains match
785
        if isinstance(other, Field):
theos's avatar
theos committed
786
787
788
789
            try:
                assert len(other.domain) == len(self.domain)
                for index in xrange(len(self.domain)):
                    assert other.domain[index] == self.domain[index]
790
                assert len(other.field_type) == len(self.field_type)
theos's avatar
theos committed
791
792
793
                for index in xrange(len(self.field_type)):
                    assert other.field_type[index] == self.field_type[index]
            except AssertionError:
794
795
                raise ValueError(
                    "domains are incompatible.")
theos's avatar
theos committed
796
            other = other.get_val(copy=False)
csongor's avatar
csongor committed
797

theos's avatar
theos committed
798
799
        self_val = self.get_val(copy=False)
        return_val = getattr(self_val, op)(other)
csongor's avatar
csongor committed
800
801
802
803
804
805

        if inplace:
            working_field = self
        else:
            working_field = self.copy_empty()

theos's avatar
theos committed
806
        working_field.set_val(return_val, copy=False)
csongor's avatar
csongor committed
807
808
809
        return working_field

    def __add__(self, other):
theos's avatar
theos committed
810
        return self._binary_helper(other, op='__add__')
811

812
    def __radd__(self, other):
theos's avatar
theos committed
813
        return self._binary_helper(other, op='__radd__')
csongor's avatar
csongor committed
814
815

    def __iadd__(self, other):
theos's avatar
theos committed
816
        return self._binary_helper(other, op='__iadd__', inplace=True)
csongor's avatar
csongor committed
817
818

    def __sub__(self, other):
theos's avatar
theos committed
819
        return self._binary_helper(other, op='__sub__')
csongor's avatar
csongor committed
820
821

    def __rsub__(self, other):
theos's avatar
theos committed
822
        return self._binary_helper(other, op='__rsub__')
csongor's avatar
csongor committed
823
824

    def __isub__(self, other):
theos's avatar
theos committed
825
        return self._binary_helper(other, op='__isub__', inplace=True)
csongor's avatar
csongor committed
826
827

    def __mul__(self, other):
theos's avatar
theos committed
828
        return self._binary_helper(other, op='__mul__')
829

830
    def __rmul__(self, other):
theos's avatar
theos committed
831
        return self._binary_helper(other, op='__rmul__')
csongor's avatar
csongor committed
832
833

    def __imul__(self, other):
theos's avatar
theos committed
834
        return self._binary_helper(other, op='__imul__', inplace=True)
csongor's avatar
csongor committed
835
836

    def __div__(self, other):
theos's avatar
theos committed
837
        return self._binary_helper(other, op='__div__')
csongor's avatar
csongor committed
838
839

    def __rdiv__(self, other):
theos's avatar
theos committed
840
        return self._binary_helper(other, op='__rdiv__')
csongor's avatar
csongor committed
841
842

    def __idiv__(self, other):
theos's avatar
theos committed
843
        return self._binary_helper(other, op='__idiv__', inplace=True)
844

csongor's avatar
csongor committed
845
    def __pow__(self, other):
theos's avatar
theos committed
846
        return self._binary_helper(other, op='__pow__')
csongor's avatar
csongor committed
847
848

    def __rpow__(self, other):
theos's avatar
theos committed
849
        return self._binary_helper(other, op='__rpow__')
csongor's avatar
csongor committed
850
851

    def __ipow__(self, other):
theos's avatar
theos committed
852
        return self._binary_helper(other, op='__ipow__', inplace=True)
csongor's avatar
csongor committed
853
854

    def __lt__(self, other):
theos's avatar
theos committed
855
        return self._binary_helper(other, op='__lt__')
csongor's avatar
csongor committed
856
857

    def __le__(self, other):
theos's avatar
theos committed
858
        return self._binary_helper(other, op='__le__')
csongor's avatar
csongor committed
859
860
861
862
863

    def __ne__(self, other):
        if other is None:
            return True
        else:
theos's avatar
theos committed
864
            return self._binary_helper(other, op='__ne__')
csongor's avatar
csongor committed
865
866
867
868
869

    def __eq__(self, other):
        if other is None:
            return False
        else:
theos's avatar
theos committed
870
            return self._binary_helper(other, op='__eq__')
csongor's avatar
csongor committed
871
872

    def __ge__(self, other):
theos's avatar
theos committed
873
        return self._binary_helper(other, op='__ge__')
csongor's avatar
csongor committed
874
875

    def __gt__(self, other):
theos's avatar
theos committed
876
877
878
879
880
881
882
883
884
885
886
887
888
        return self._binary_helper(other, op='__gt__')

    def __repr__(self):
        return "<nifty_core.field>"

    def __str__(self):
        minmax = [self.min(), self.max()]
        mean = self.mean()
        return "nifty_core.field instance\n- domain      = " + \
               repr(self.domain) + \
               "\n- val         = " + repr(self.get_val()) + \
               "\n  - min.,max. = " + str(minmax) + \
               "\n  - mean = " + str(mean)
csongor's avatar
csongor committed
889

890

891
class EmptyField(Field):
csongor's avatar
csongor committed
892
893
    def __init__(self):
        pass