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

Theo Steininger's avatar
Theo Steininger committed
4
5
from keepers import Versionable,\
                    Loggable
Jait Dixit's avatar
Jait Dixit committed
6

7
from d2o import distributed_data_object,\
8
    STRATEGIES as DISTRIBUTION_STRATEGIES
csongor's avatar
csongor committed
9

10
from nifty.config import nifty_configuration as gc
csongor's avatar
csongor committed
11

12
from nifty.domain_object import DomainObject
13

14
from nifty.spaces.power_space import PowerSpace
csongor's avatar
csongor committed
15

csongor's avatar
csongor committed
16
import nifty.nifty_utilities as utilities
17
18
from nifty.random import Random

csongor's avatar
csongor committed
19

Jait Dixit's avatar
Jait Dixit committed
20
class Field(Loggable, Versionable, object):
Theo Steininger's avatar
Theo Steininger committed
21
    # ---Initialization methods---
22

23
    def __init__(self, domain=None, val=None, dtype=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

Theo Steininger's avatar
Theo Steininger committed
29
        self.dtype = self._infer_dtype(dtype=dtype,
Jait Dixit's avatar
Jait Dixit committed
30
                                       val=val,
31
                                       domain=self.domain)
32

33
34
35
        self.distribution_strategy = self._parse_distribution_strategy(
                                distribution_strategy=distribution_strategy,
                                val=val)
csongor's avatar
csongor committed
36

37
38
39
40
        if val is None:
            self._val = None
        else:
            self.set_val(new_val=val, copy=copy)
csongor's avatar
csongor committed
41

42
    def _parse_domain(self, domain, val=None):
43
        if domain is None:
44
45
46
47
            if isinstance(val, Field):
                domain = val.domain
            else:
                domain = ()
48
        elif isinstance(domain, DomainObject):
49
            domain = (domain,)
50
51
52
        elif not isinstance(domain, tuple):
            domain = tuple(domain)

csongor's avatar
csongor committed
53
        for d in domain:
54
            if not isinstance(d, DomainObject):
55
56
                raise TypeError(
                    "Given domain contains something that is not a "
57
                    "DomainObject instance.")
csongor's avatar
csongor committed
58
59
        return domain

Theo Steininger's avatar
Theo Steininger committed
60
61
62
63
64
65
66
67
68
69
    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)
70

71
    def _infer_dtype(self, dtype, val, domain):
csongor's avatar
csongor committed
72
        if dtype is None:
73
74
75
            if isinstance(val, Field) or \
               isinstance(val, distributed_data_object):
                dtype = val.dtype
Theo Steininger's avatar
Theo Steininger committed
76
77
78
79
80
            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)
csongor's avatar
csongor committed
81

Theo Steininger's avatar
Theo Steininger committed
82
        dtype = reduce(lambda x, y: np.result_type(x, y), dtype_tuple)
83

Theo Steininger's avatar
Theo Steininger committed
84
        return dtype
85

86
87
    def _parse_distribution_strategy(self, distribution_strategy, val):
        if distribution_strategy is None:
88
            if isinstance(val, distributed_data_object):
89
                distribution_strategy = val.distribution_strategy
90
            elif isinstance(val, Field):
91
                distribution_strategy = val.distribution_strategy
92
            else:
93
                self.logger.debug("distribution_strategy set to default!")
94
                distribution_strategy = gc['default_distribution_strategy']
95
        elif distribution_strategy not in DISTRIBUTION_STRATEGIES['global']:
96
97
98
            raise ValueError(
                    "distribution_strategy must be a global-type "
                    "strategy.")
99
        return distribution_strategy
100
101

    # ---Factory methods---
102

103
    @classmethod
104
    def from_random(cls, random_type, domain=None, dtype=None,
105
                    distribution_strategy=None, **kwargs):
106
        # create a initially empty field
107
        f = cls(domain=domain, dtype=dtype,
108
                distribution_strategy=distribution_strategy)
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143

        # 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
144
        else:
145
146
            raise KeyError(
                "unsupported random key '" + str(random_type) + "'.")
csongor's avatar
csongor committed
147

148
        return random_arguments
csongor's avatar
csongor committed
149

150
151
152
153
154
155
156
157
158
    # ---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(
159
                    "Field has a space in `domain` which is neither "
160
161
162
                    "harmonic nor a PowerSpace.")

        # check if the `spaces` input is valid
163
164
165
166
167
        spaces = utilities.cast_axis_to_tuple(spaces, len(self.domain))
        if spaces is None:
            if len(self.domain) == 1:
                spaces = (0,)
            else:
168
169
170
                raise ValueError(
                    "Field has multiple spaces as domain "
                    "but `spaces` is None.")
171
172

        if len(spaces) == 0:
173
174
            raise ValueError(
                "No space for analysis specified.")
175
        elif len(spaces) > 1:
176
177
            raise ValueError(
                "Conversion of only one space at a time is allowed.")
178
179
180
181

        space_index = spaces[0]

        if not self.domain[space_index].harmonic:
182
183
            raise ValueError(
                "The analyzed space must be harmonic.")
184

185
186
187
188
189
190
        # 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.

191
192
193
194
        distribution_strategy = \
            self.val.get_axes_local_distribution_strategy(
                self.domain_axes[space_index])

195
196
197
198
199
        if real_signal:
            power_dtype = np.dtype('complex')
        else:
            power_dtype = np.dtype('float')

200
201
        harmonic_domain = self.domain[space_index]
        power_domain = PowerSpace(harmonic_domain=harmonic_domain,
202
                                  distribution_strategy=distribution_strategy,
203
204
                                  log=log, nbin=nbin, binbounds=binbounds,
                                  dtype=power_dtype)
205

206
        # extract pindex and rho from power_domain
207
208
        pindex = power_domain.pindex
        rho = power_domain.rho
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226

        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(
227
228
229
230
231
232
233
234
235
                                            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

236
237
238
        result_field = self.copy_empty(
                   domain=result_domain,
                   distribution_strategy=power_spectrum.distribution_strategy)
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
        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']:
267
            raise ValueError("pindex's distribution strategy must be "
268
269
270
271
272
273
                             "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(
274
                    "A slicing distributor shall not be reshaped to "
275
276
277
278
279
280
281
282
283
284
285
286
287
                    "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

288
289
    def power_synthesize(self, spaces=None, real_signal=True,
                         mean=None, std=None):
290

291
        # assert that all spaces in `self.domain` are either of signal-type or
292
293
        # power_space instances
        for sp in self.domain:
294
            if not sp.harmonic and not isinstance(sp, PowerSpace):
295
                raise AttributeError(
296
                    "Field has a space in `domain` which is neither "
297
298
                    "harmonic nor a PowerSpace.")

299
300
301
302
303
304
        # 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:
305
306
307
                raise ValueError(
                    "Field has multiple spaces as domain "
                    "but `spaces` is None.")
308
309

        if len(spaces) == 0:
310
311
            raise ValueError(
                "No space for synthesis specified.")
312
        elif len(spaces) > 1:
313
314
            raise ValueError(
                "Conversion of only one space at a time is allowed.")
315
316
317
318

        power_space_index = spaces[0]
        power_domain = self.domain[power_space_index]
        if not isinstance(power_domain, PowerSpace):
319
320
            raise ValueError(
                "A PowerSpace is needed for field synthetization.")
321
322
323
324
325
326
327
328
329
330
331
332
333
334

        # 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]

335
336
        result_list = [self.__class__.from_random(
                             'normal',
337
338
339
                             mean=mean,
                             std=std,
                             domain=result_domain,
340
341
                             dtype=harmonic_domain.dtype,
                             distribution_strategy=self.distribution_strategy)
342
343
344
345
346
347
348
349
350
                       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,
351
352
                                    axes=x.domain_axes[power_space_index],
                                    preserve_gaussian_variance=True)[0]
353
354
                               for x in result_list]
        else:
355
356
357
358
359
#            # if the synthesized field is complex in signal space,
#            # one must correct the variance here, since one draws
#            # sqrt(twice) the power via real- and imaginary-part
#            result_val_list = [x.val*np.sqrt(0.5) for x in result_list]
             result_val_list = [x.val for x in result_list]
360
361
362
363
364
365
366
367
368
369
370

        # 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:
371
            self.logger.warn(
372
                "The distribution_stragey of pindex does not fit the "
373
374
375
376
377
378
                "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)
379
        full_spec = self.val.get_full_data()
380
381
382
383
384

        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
385
        local_rescaler = full_spec[local_blow_up]
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406

        # 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
407

Theo Steininger's avatar
Theo Steininger committed
408
    # ---Properties---
409

Theo Steininger's avatar
Theo Steininger committed
410
    def set_val(self, new_val=None, copy=False):
411
412
        new_val = self.cast(new_val)
        if copy:
Theo Steininger's avatar
Theo Steininger committed
413
414
            new_val = new_val.copy()
        self._val = new_val
415
        return self
csongor's avatar
csongor committed
416

417
    def get_val(self, copy=False):
418
419
420
        if self._val is None:
            self.set_val(None)

421
        if copy:
Theo Steininger's avatar
Theo Steininger committed
422
            return self._val.copy()
423
        else:
Theo Steininger's avatar
Theo Steininger committed
424
            return self._val
csongor's avatar
csongor committed
425

Theo Steininger's avatar
Theo Steininger committed
426
427
    @property
    def val(self):
428
        return self.get_val(copy=False)
csongor's avatar
csongor committed
429

Theo Steininger's avatar
Theo Steininger committed
430
431
    @val.setter
    def val(self, new_val):
432
        self.set_val(new_val=new_val, copy=False)
csongor's avatar
csongor committed
433

434
435
    @property
    def shape(self):
436
        shape_tuple = tuple(sp.shape for sp in self.domain)
437
438
439
440
        try:
            global_shape = reduce(lambda x, y: x + y, shape_tuple)
        except TypeError:
            global_shape = ()
csongor's avatar
csongor committed
441

442
        return global_shape
csongor's avatar
csongor committed
443

444
445
    @property
    def dim(self):
446
        dim_tuple = tuple(sp.dim for sp in self.domain)
Theo Steininger's avatar
Theo Steininger committed
447
448
449
450
        try:
            return reduce(lambda x, y: x * y, dim_tuple)
        except TypeError:
            return 0
csongor's avatar
csongor committed
451

452
453
    @property
    def dof(self):
Theo Steininger's avatar
Theo Steininger committed
454
455
456
457
458
459
460
461
        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)
462
        try:
Theo Steininger's avatar
Theo Steininger committed
463
            return reduce(lambda x, y: x * y, volume_tuple)
464
        except TypeError:
Theo Steininger's avatar
Theo Steininger committed
465
            return 0
466

Theo Steininger's avatar
Theo Steininger committed
467
    # ---Special unary/binary operations---
468

csongor's avatar
csongor committed
469
470
471
    def cast(self, x=None, dtype=None):
        if dtype is None:
            dtype = self.dtype
472
473
        else:
            dtype = np.dtype(dtype)
474

475
476
        casted_x = x

477
        for ind, sp in enumerate(self.domain):
478
            casted_x = sp.pre_cast(casted_x,
479
480
481
                                   axes=self.domain_axes[ind])

        casted_x = self._actual_cast(casted_x, dtype=dtype)
482
483

        for ind, sp in enumerate(self.domain):
484
485
            casted_x = sp.post_cast(casted_x,
                                    axes=self.domain_axes[ind])
486

487
        return casted_x
csongor's avatar
csongor committed
488

Theo Steininger's avatar
Theo Steininger committed
489
    def _actual_cast(self, x, dtype=None):
490
        if isinstance(x, Field):
csongor's avatar
csongor committed
491
492
493
494
495
            x = x.get_val()

        if dtype is None:
            dtype = self.dtype

496
        return_x = distributed_data_object(
497
498
499
                            global_shape=self.shape,
                            dtype=dtype,
                            distribution_strategy=self.distribution_strategy)
500
501
        return_x.set_full_data(x, copy=False)
        return return_x
Theo Steininger's avatar
Theo Steininger committed
502

503
    def copy(self, domain=None, dtype=None, distribution_strategy=None):
Theo Steininger's avatar
Theo Steininger committed
504
        copied_val = self.get_val(copy=True)
505
506
507
508
        new_field = self.copy_empty(
                                domain=domain,
                                dtype=dtype,
                                distribution_strategy=distribution_strategy)
Theo Steininger's avatar
Theo Steininger committed
509
510
        new_field.set_val(new_val=copied_val, copy=False)
        return new_field
csongor's avatar
csongor committed
511

512
    def copy_empty(self, domain=None, dtype=None, distribution_strategy=None):
Theo Steininger's avatar
Theo Steininger committed
513
514
        if domain is None:
            domain = self.domain
csongor's avatar
csongor committed
515
        else:
Theo Steininger's avatar
Theo Steininger committed
516
            domain = self._parse_domain(domain)
csongor's avatar
csongor committed
517

Theo Steininger's avatar
Theo Steininger committed
518
519
520
521
        if dtype is None:
            dtype = self.dtype
        else:
            dtype = np.dtype(dtype)
csongor's avatar
csongor committed
522

523
524
        if distribution_strategy is None:
            distribution_strategy = self.distribution_strategy
csongor's avatar
csongor committed
525

Theo Steininger's avatar
Theo Steininger committed
526
527
528
529
530
531
532
533
534
535
        fast_copyable = True
        try:
            for i in xrange(len(self.domain)):
                if self.domain[i] is not domain[i]:
                    fast_copyable = False
                    break
        except IndexError:
            fast_copyable = False

        if (fast_copyable and dtype == self.dtype and
536
                distribution_strategy == self.distribution_strategy):
Theo Steininger's avatar
Theo Steininger committed
537
538
539
540
            new_field = self._fast_copy_empty()
        else:
            new_field = Field(domain=domain,
                              dtype=dtype,
541
                              distribution_strategy=distribution_strategy)
Theo Steininger's avatar
Theo Steininger committed
542
        return new_field
csongor's avatar
csongor committed
543

Theo Steininger's avatar
Theo Steininger committed
544
545
546
547
548
549
550
    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():
551
            if key != '_val':
Theo Steininger's avatar
Theo Steininger committed
552
553
554
555
556
557
                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):
558
        if inplace:
csongor's avatar
csongor committed
559
560
561
562
            new_field = self
        else:
            new_field = self.copy_empty()

563
        new_val = self.get_val(copy=False)
csongor's avatar
csongor committed
564

565
        spaces = utilities.cast_axis_to_tuple(spaces, len(self.domain))
csongor's avatar
csongor committed
566
        if spaces is None:
Theo Steininger's avatar
Theo Steininger committed
567
            spaces = range(len(self.domain))
csongor's avatar
csongor committed
568

569
        for ind, sp in enumerate(self.domain):
Theo Steininger's avatar
Theo Steininger committed
570
571
572
573
574
            if ind in spaces:
                new_val = sp.weight(new_val,
                                    power=power,
                                    axes=self.domain_axes[ind],
                                    inplace=inplace)
575
576

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

579
580
581
582
583
    def dot(self, x=None, spaces=None, bare=False):

        if not isinstance(x, Field):
            raise ValueError("The dot-partner must be an instance of " +
                             "the NIFTy field class")
Theo Steininger's avatar
Theo Steininger committed
584
585
586

        # Compute the dot respecting the fact of discrete/continous spaces
        if bare:
587
            y = self
588
589
        else:
            y = self.weight(power=1)
Theo Steininger's avatar
Theo Steininger committed
590

591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
        if spaces is None:
            x_val = x.get_val(copy=False)
            y_val = y.get_val(copy=False)
            result = (x_val.conjugate() * y_val).sum()
            return result
        else:
            # create a diagonal operator which is capable of taking care of the
            # axes-matching
            from nifty.operators.diagonal_operator import DiagonalOperator
            diagonal = y.val.conjugate()
            diagonalOperator = DiagonalOperator(domain=y.domain,
                                                diagonal=diagonal,
                                                copy=False)
            dotted = diagonalOperator(x, spaces=spaces)
            return dotted.sum(spaces=spaces)
Theo Steininger's avatar
Theo Steininger committed
606

607
    def norm(self, q=2):
csongor's avatar
csongor committed
608
609
610
611
612
613
614
615
616
617
618
619
620
621
        """
            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.

        """
622
        if q == 2:
623
            return (self.dot(x=self)) ** (1 / 2)
csongor's avatar
csongor committed
624
        else:
625
            return self.dot(x=self ** (q - 1)) ** (1 / q)
csongor's avatar
csongor committed
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641

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

642
        new_val = self.get_val(copy=False)
Theo Steininger's avatar
Theo Steininger committed
643
        new_val = new_val.conjugate()
644
        work_field.set_val(new_val=new_val, copy=False)
csongor's avatar
csongor committed
645
646
647

        return work_field

Theo Steininger's avatar
Theo Steininger committed
648
    # ---General unary/contraction methods---
649

Theo Steininger's avatar
Theo Steininger committed
650
651
    def __pos__(self):
        return self.copy()
652

Theo Steininger's avatar
Theo Steininger committed
653
654
655
656
    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
657
658
        return return_field

Theo Steininger's avatar
Theo Steininger committed
659
660
661
662
663
    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
664

665
    def _contraction_helper(self, op, spaces):
Theo Steininger's avatar
Theo Steininger committed
666
667
668
669
670
        # 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
671

672
        axes_list = tuple(self.domain_axes[sp_index] for sp_index in spaces)
673
674

        try:
Theo Steininger's avatar
Theo Steininger committed
675
            axes_list = reduce(lambda x, y: x+y, axes_list)
676
        except TypeError:
Theo Steininger's avatar
Theo Steininger committed
677
            axes_list = ()
csongor's avatar
csongor committed
678

Theo Steininger's avatar
Theo Steininger committed
679
680
681
        # perform the contraction on the d2o
        data = self.get_val(copy=False)
        data = getattr(data, op)(axis=axes_list)
csongor's avatar
csongor committed
682

Theo Steininger's avatar
Theo Steininger committed
683
684
685
        # 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
686
        else:
Theo Steininger's avatar
Theo Steininger committed
687
688
689
            return_domain = tuple(self.domain[i]
                                  for i in xrange(len(self.domain))
                                  if i not in spaces)
690

Theo Steininger's avatar
Theo Steininger committed
691
692
693
694
            return_field = Field(domain=return_domain,
                                 val=data,
                                 copy=False)
            return return_field
csongor's avatar
csongor committed
695

696
697
    def sum(self, spaces=None):
        return self._contraction_helper('sum', spaces)
csongor's avatar
csongor committed
698

699
700
    def prod(self, spaces=None):
        return self._contraction_helper('prod', spaces)
csongor's avatar
csongor committed
701

702
703
    def all(self, spaces=None):
        return self._contraction_helper('all', spaces)
csongor's avatar
csongor committed
704

705
706
    def any(self, spaces=None):
        return self._contraction_helper('any', spaces)
csongor's avatar
csongor committed
707

708
709
    def min(self, spaces=None):
        return self._contraction_helper('min', spaces)
csongor's avatar
csongor committed
710

711
712
    def nanmin(self, spaces=None):
        return self._contraction_helper('nanmin', spaces)
csongor's avatar
csongor committed
713

714
715
    def max(self, spaces=None):
        return self._contraction_helper('max', spaces)
csongor's avatar
csongor committed
716

717
718
    def nanmax(self, spaces=None):
        return self._contraction_helper('nanmax', spaces)
csongor's avatar
csongor committed
719

720
721
    def mean(self, spaces=None):
        return self._contraction_helper('mean', spaces)
csongor's avatar
csongor committed
722

723
724
    def var(self, spaces=None):
        return self._contraction_helper('var', spaces)
csongor's avatar
csongor committed
725

726
727
    def std(self, spaces=None):
        return self._contraction_helper('std', spaces)
csongor's avatar
csongor committed
728

Theo Steininger's avatar
Theo Steininger committed
729
    # ---General binary methods---
csongor's avatar
csongor committed
730

Theo Steininger's avatar
Theo Steininger committed
731
    def _binary_helper(self, other, op, inplace=False):
csongor's avatar
csongor committed
732
        # if other is a field, make sure that the domains match
733
        if isinstance(other, Field):
Theo Steininger's avatar
Theo Steininger committed
734
735
736
737
738
            try:
                assert len(other.domain) == len(self.domain)
                for index in xrange(len(self.domain)):
                    assert other.domain[index] == self.domain[index]
            except AssertionError:
739
740
                raise ValueError(
                    "domains are incompatible.")
Theo Steininger's avatar
Theo Steininger committed
741
            other = other.get_val(copy=False)
csongor's avatar
csongor committed
742

Theo Steininger's avatar
Theo Steininger committed
743
744
        self_val = self.get_val(copy=False)
        return_val = getattr(self_val, op)(other)
csongor's avatar
csongor committed
745
746
747
748

        if inplace:
            working_field = self
        else:
749
            working_field = self.copy_empty(dtype=return_val.dtype)
csongor's avatar
csongor committed
750

Theo Steininger's avatar
Theo Steininger committed
751
        working_field.set_val(return_val, copy=False)
csongor's avatar
csongor committed
752
753
754
        return working_field

    def __add__(self, other):
Theo Steininger's avatar
Theo Steininger committed
755
        return self._binary_helper(other, op='__add__')
756

757
    def __radd__(self, other):
Theo Steininger's avatar
Theo Steininger committed
758
        return self._binary_helper(other, op='__radd__')
csongor's avatar
csongor committed
759
760

    def __iadd__(self, other):
Theo Steininger's avatar
Theo Steininger committed
761
        return self._binary_helper(other, op='__iadd__', inplace=True)
csongor's avatar
csongor committed
762
763

    def __sub__(self, other):
Theo Steininger's avatar
Theo Steininger committed
764
        return self._binary_helper(other, op='__sub__')
csongor's avatar
csongor committed
765
766

    def __rsub__(self, other):
Theo Steininger's avatar
Theo Steininger committed
767
        return self._binary_helper(other, op='__rsub__')
csongor's avatar
csongor committed
768
769

    def __isub__(self, other):
Theo Steininger's avatar
Theo Steininger committed
770
        return self._binary_helper(other, op='__isub__', inplace=True)
csongor's avatar
csongor committed
771
772

    def __mul__(self, other):
Theo Steininger's avatar
Theo Steininger committed
773
        return self._binary_helper(other, op='__mul__')
774

775
    def __rmul__(self, other):
Theo Steininger's avatar
Theo Steininger committed
776
        return self._binary_helper(other, op='__rmul__')
csongor's avatar
csongor committed
777
778

    def __imul__(self, other):
Theo Steininger's avatar
Theo Steininger committed
779
        return self._binary_helper(other, op='__imul__', inplace=True)
csongor's avatar
csongor committed
780
781

    def __div__(self, other):
Theo Steininger's avatar
Theo Steininger committed
782
        return self._binary_helper(other, op='__div__')
csongor's avatar
csongor committed
783
784

    def __rdiv__(self, other):
Theo Steininger's avatar
Theo Steininger committed
785
        return self._binary_helper(other, op='__rdiv__')
csongor's avatar
csongor committed
786
787

    def __idiv__(self, other):
Theo Steininger's avatar
Theo Steininger committed
788
        return self._binary_helper(other, op='__idiv__', inplace=True)
789

csongor's avatar
csongor committed
790
    def __pow__(self, other):
Theo Steininger's avatar
Theo Steininger committed
791
        return self._binary_helper(other, op='__pow__')
csongor's avatar
csongor committed
792
793

    def __rpow__(self, other):
Theo Steininger's avatar
Theo Steininger committed
794
        return self._binary_helper(other, op='__rpow__')
csongor's avatar
csongor committed
795
796

    def __ipow__(self, other):
Theo Steininger's avatar
Theo Steininger committed
797
        return self._binary_helper(other, op='__ipow__', inplace=True)
csongor's avatar
csongor committed
798
799

    def __lt__(self, other):
Theo Steininger's avatar
Theo Steininger committed
800
        return self._binary_helper(other, op='__lt__')
csongor's avatar
csongor committed
801
802

    def __le__(self, other):
Theo Steininger's avatar
Theo Steininger committed
803
        return self._binary_helper(other, op='__le__')
csongor's avatar
csongor committed
804
805
806
807
808

    def __ne__(self, other):
        if other is None:
            return True
        else:
Theo Steininger's avatar
Theo Steininger committed
809
            return self._binary_helper(other, op='__ne__')
csongor's avatar
csongor committed
810
811
812
813
814

    def __eq__(self, other):
        if other is None:
            return False
        else:
Theo Steininger's avatar
Theo Steininger committed
815
            return self._binary_helper(other, op='__eq__')
csongor's avatar
csongor committed
816
817

    def __ge__(self, other):
Theo Steininger's avatar
Theo Steininger committed
818
        return self._binary_helper(other, op='__ge__')
csongor's avatar
csongor committed
819
820

    def __gt__(self, other):
Theo Steininger's avatar
Theo Steininger committed
821
822
823
824
825
826
827
828
829
830
831
832
833
        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
834

Jait Dixit's avatar
Jait Dixit committed
835
836
837
    # ---Serialization---

    def _to_hdf5(self, hdf5_group):
Theo Steininger's avatar
Theo Steininger committed
838
839
840
        hdf5_group.attrs['dtype'] = self.dtype.name
        hdf5_group.attrs['distribution_strategy'] = self.distribution_strategy
        hdf5_group.attrs['domain_axes'] = str(self.domain_axes)
841
        hdf5_group['num_domain'] = len(self.domain)
Jait Dixit's avatar
Jait Dixit committed
842

Theo Steininger's avatar
Theo Steininger committed
843
        ret_dict = {'val': self.val}
Jait Dixit's avatar
Jait Dixit committed
844
845
846
847
848
849
850

        for i in range(len(self.domain)):
            ret_dict['s_' + str(i)] = self.domain[i]

        return ret_dict

    @classmethod
Theo Steininger's avatar
Theo Steininger committed
851
    def _from_hdf5(cls, hdf5_group, repository):
Jait Dixit's avatar
Jait Dixit committed
852
853
854
855
856
857
        # create empty field
        new_field = EmptyField()
        # reset class
        new_field.__class__ = cls
        # set values
        temp_domain = []
858
        for i in range(hdf5_group['num_domain'][()]):
Theo Steininger's avatar
Theo Steininger committed
859
            temp_domain.append(repository.get('s_' + str(i), hdf5_group))
Jait Dixit's avatar
Jait Dixit committed
860
861
        new_field.domain = tuple(temp_domain)

Theo Steininger's avatar
Theo Steininger committed
862
863
864
865
866
        exec('new_field.domain_axes = ' + hdf5_group.attrs['domain_axes'])
        new_field._val = repository.get('val', hdf5_group)
        new_field.dtype = np.dtype(hdf5_group.attrs['dtype'])
        new_field.distribution_strategy =\
            hdf5_group.attrs['distribution_strategy']
Jait Dixit's avatar
Jait Dixit committed
867
868

        return new_field
869

Theo Steininger's avatar
Theo Steininger committed
870

871
class EmptyField(Field):
csongor's avatar
csongor committed
872
873
    def __init__(self):
        pass