field.py 24.5 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
8
9
from nifty.config import about,\
                         nifty_configuration as gc,\
                         dependency_injector as gdi
csongor's avatar
csongor committed
10

11
from nifty.field_types import FieldType
12

13
from nifty.spaces.space import Space
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
20

POINT_DISTRIBUTION_STRATEGIES = DISTRIBUTION_STRATEGIES['global']
theos's avatar
theos committed
21
COMM = getattr(gdi[gc['mpi_module']], gc['default_comm'])
csongor's avatar
csongor committed
22
23


24
class Field(object):
theos's avatar
theos committed
25
    # ---Initialization methods---
26

theos's avatar
theos committed
27
28
    def __init__(self, domain=None, val=None, dtype=None, field_type=None,
                 datamodel=None, copy=False):
csongor's avatar
csongor committed
29

30
        self.domain = self._parse_domain(domain=domain, val=val)
31
        self.domain_axes = self._get_axes_tuple(self.domain)
csongor's avatar
csongor committed
32

33
        self.field_type = self._parse_field_type(field_type, val=val)
34

theos's avatar
theos committed
35
36
37
38
39
40
        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)
41

theos's avatar
theos committed
42
        self.dtype = self._infer_dtype(dtype=dtype,
Jait Dixit's avatar
Jait Dixit committed
43
                                       val=val,
theos's avatar
theos committed
44
45
                                       domain=self.domain,
                                       field_type=self.field_type)
46

theos's avatar
theos committed
47
48
        self.datamodel = self._parse_datamodel(datamodel=datamodel,
                                               val=val)
csongor's avatar
csongor committed
49
50
51

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

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

csongor's avatar
csongor committed
63
        for d in domain:
64
            if not isinstance(d, Space):
csongor's avatar
csongor committed
65
                raise TypeError(about._errors.cstring(
66
67
                    "ERROR: Given domain contains something that is not a "
                    "nifty.space."))
csongor's avatar
csongor committed
68
69
        return domain

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

theos's avatar
theos committed
86
87
88
89
90
91
92
93
94
95
    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)
96

97
    def _infer_dtype(self, dtype, val, domain, field_type):
csongor's avatar
csongor committed
98
        if dtype is None:
99
100
101
            if isinstance(val, Field) or \
               isinstance(val, distributed_data_object):
                dtype = val.dtype
theos's avatar
theos committed
102
103
104
105
106
107
108
            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
109

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

theos's avatar
theos committed
112
        return dtype
113

theos's avatar
theos committed
114
    def _parse_datamodel(self, datamodel, val):
115
116
117
118
119
120
121
122
123
124
125
126
127
128
        if datamodel is None:
            if isinstance(val, distributed_data_object):
                datamodel = val.distribution_strategy
            elif isinstance(val, Field):
                datamodel = val.datamodel
            else:
                about.warnings.cprint("WARNING: Datamodel set to default!")
                datamodel = gc['default_datamodel']
        elif datamodel not in DISTRIBUTION_STRATEGIES['all']:
            raise ValueError(about._errors.cstring(
                    "ERROR: Invalid datamodel!"))
        return datamodel

    # ---Factory methods---
129

130
131
132
133
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
169
170
171
172
173
    @classmethod
    def from_random(cls, random_type, domain=None, dtype=None, field_type=None,
                    datamodel=None, **kwargs):
        # create a initially empty field
        f = cls(domain=domain, dtype=dtype, field_type=field_type,
                datamodel=datamodel)

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

#        elif random_type == 'syn':
#            pass

csongor's avatar
csongor committed
174
        else:
175
176
            raise KeyError(about._errors.cstring(
                "ERROR: unsupported random key '" + str(random_type) + "'."))
csongor's avatar
csongor committed
177

178
        return random_arguments
csongor's avatar
csongor committed
179

180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
    def power_analyze(self, spaces=None, log=False, nbin=None, binbounds=None):
        # 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:
                raise ValueError(about._errors.cstring(
                    "ERROR: Field has multiple spaces as domain "
                    "but `spaces` is None."))

        if len(spaces) == 0:
            raise ValueError(about._errors.cstring(
                "ERROR: No space for analysis specified."))
        elif len(spaces) > 1:
            raise ValueError(about._errors.cstring(
                "ERROR: Conversion of only one space at a time is allowed."))

        space_index = spaces[0]

        if not self.domain[space_index].harmonic:
            raise ValueError(about._errors.cstring(
                "ERROR: Conversion of only one space at a time is allowed."))

        # create the target PowerSpace instance
        distribution_strategy = \
            self.val.get_axes_local_distribution_strategy(
                self.domain_axes[space_index])

        harmonic_domain = self.domain[space_index]
        power_domain = PowerSpace(harmonic_domain=harmonic_domain,
                                  datamodel=distribution_strategy,
                                  log=log, nbin=nbin, binbounds=binbounds)

        # extract pindex and rho from power_domain and calculate the spectrum
        pindex = power_domain.pindex
        rho = power_domain.rho
        power_spectrum = self._calculate_power_spectrum(
                                            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']:
            raise ValueError("ERROR: pindex's distribution strategy must be "
                             "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(
                    "ERROR: A slicing distributor shall not be reshaped to "
                    "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

    def power_synthesize(self):
        # check that all spaces in self.domain are real or instances of power_space
        # check if field is real- or complex-valued

theos's avatar
theos committed
281
    # ---Properties---
282

theos's avatar
theos committed
283
    def set_val(self, new_val=None, copy=False):
284
285
        new_val = self.cast(new_val)
        if copy:
theos's avatar
theos committed
286
287
288
            new_val = new_val.copy()
        self._val = new_val
        return self._val
csongor's avatar
csongor committed
289

290
291
    def get_val(self, copy=False):
        if copy:
theos's avatar
theos committed
292
            return self._val.copy()
293
        else:
theos's avatar
theos committed
294
            return self._val
csongor's avatar
csongor committed
295

theos's avatar
theos committed
296
297
298
    @property
    def val(self):
        return self._val
csongor's avatar
csongor committed
299

theos's avatar
theos committed
300
301
302
    @val.setter
    def val(self, new_val):
        self._val = self.cast(new_val)
csongor's avatar
csongor committed
303

304
305
    @property
    def shape(self):
306
307
308
309
310
311
312
        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
313

314
        return global_shape
csongor's avatar
csongor committed
315

316
317
    @property
    def dim(self):
theos's avatar
theos committed
318
319
320
321
322
323
324
        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
325

326
327
    @property
    def dof(self):
theos's avatar
theos committed
328
329
330
331
332
333
334
335
        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)
336
        try:
theos's avatar
theos committed
337
            return reduce(lambda x, y: x * y, volume_tuple)
338
        except TypeError:
theos's avatar
theos committed
339
            return 0
340

theos's avatar
theos committed
341
    # ---Special unary/binary operations---
342

csongor's avatar
csongor committed
343
344
345
    def cast(self, x=None, dtype=None):
        if dtype is None:
            dtype = self.dtype
346
347
        else:
            dtype = np.dtype(dtype)
348

theos's avatar
theos committed
349
        casted_x = self._actual_cast(x, dtype=dtype)
350
351

        for ind, sp in enumerate(self.domain):
352
            casted_x = sp.complement_cast(casted_x,
theos's avatar
theos committed
353
                                          axes=self.domain_axes[ind])
354
355
356

        for ind, ft in enumerate(self.field_type):
            casted_x = ft.complement_cast(casted_x,
theos's avatar
theos committed
357
                                          axes=self.field_type_axes[ind])
358
359

        return casted_x
csongor's avatar
csongor committed
360

theos's avatar
theos committed
361
    def _actual_cast(self, x, dtype=None):
362
        if isinstance(x, Field):
csongor's avatar
csongor committed
363
364
365
366
367
            x = x.get_val()

        if dtype is None:
            dtype = self.dtype

theos's avatar
theos committed
368
369
370
        x = distributed_data_object(x,
                                    global_shape=self.shape,
                                    dtype=dtype,
csongor's avatar
csongor committed
371
372
                                    distribution_strategy=self.datamodel)

theos's avatar
theos committed
373
374
375
376
377
378
379
380
381
382
383
        return x

    def copy(self, domain=None, dtype=None, field_type=None,
             datamodel=None):
        copied_val = self.get_val(copy=True)
        new_field = self.copy_empty(domain=domain,
                                    dtype=dtype,
                                    field_type=field_type,
                                    datamodel=datamodel)
        new_field.set_val(new_val=copied_val, copy=False)
        return new_field
csongor's avatar
csongor committed
384

theos's avatar
theos committed
385
386
387
388
    def copy_empty(self, domain=None, dtype=None, field_type=None,
                   datamodel=None):
        if domain is None:
            domain = self.domain
csongor's avatar
csongor committed
389
        else:
theos's avatar
theos committed
390
            domain = self._parse_domain(domain)
csongor's avatar
csongor committed
391

theos's avatar
theos committed
392
393
394
395
        if dtype is None:
            dtype = self.dtype
        else:
            dtype = np.dtype(dtype)
csongor's avatar
csongor committed
396

theos's avatar
theos committed
397
398
399
400
        if field_type is None:
            field_type = self.field_type
        else:
            field_type = self._parse_field_type(field_type)
csongor's avatar
csongor committed
401

theos's avatar
theos committed
402
403
        if datamodel is None:
            datamodel = self.datamodel
csongor's avatar
csongor committed
404

theos's avatar
theos committed
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
        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
                datamodel == self.datamodel):
            new_field = self._fast_copy_empty()
        else:
            new_field = Field(domain=domain,
                              dtype=dtype,
                              field_type=field_type,
                              datamodel=datamodel)
        return new_field
csongor's avatar
csongor committed
427

theos's avatar
theos committed
428
429
430
431
432
433
434
435
436
437
438
439
440
441
    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():
            if key != 'val':
                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):
442
        if inplace:
csongor's avatar
csongor committed
443
444
445
446
            new_field = self
        else:
            new_field = self.copy_empty()

447
        new_val = self.get_val(copy=False)
csongor's avatar
csongor committed
448

csongor's avatar
csongor committed
449
        if spaces is None:
theos's avatar
theos committed
450
451
452
            spaces = range(len(self.domain))
        else:
            spaces = utilities.cast_axis_to_tuple(spaces, len(self.domain))
csongor's avatar
csongor committed
453

454
        for ind, sp in enumerate(self.domain):
theos's avatar
theos committed
455
456
457
458
459
            if ind in spaces:
                new_val = sp.weight(new_val,
                                    power=power,
                                    axes=self.domain_axes[ind],
                                    inplace=inplace)
460
461

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

theos's avatar
theos committed
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
    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:
                raise ValueError(about._errors.cstring(
                    "ERROR: domains are incompatible."))
            # 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()

493
    def norm(self, q=2):
csongor's avatar
csongor committed
494
495
496
497
498
499
500
501
502
503
504
505
506
507
        """
            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.

        """
508
        if q == 2:
509
            return (self.dot(x=self)) ** (1 / 2)
csongor's avatar
csongor committed
510
        else:
511
            return self.dot(x=self ** (q - 1)) ** (1 / q)
csongor's avatar
csongor committed
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527

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

528
        new_val = self.get_val(copy=False)
theos's avatar
theos committed
529
        new_val = new_val.conjugate()
530
        work_field.set_val(new_val=new_val, copy=False)
csongor's avatar
csongor committed
531
532
533

        return work_field

theos's avatar
theos committed
534
    # ---General unary/contraction methods---
535

theos's avatar
theos committed
536
537
    def __pos__(self):
        return self.copy()
538

theos's avatar
theos committed
539
540
541
542
    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
543
544
        return return_field

theos's avatar
theos committed
545
546
547
548
549
    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
550

theos's avatar
theos committed
551
552
553
554
555
556
    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
557

theos's avatar
theos committed
558
559
560
561
        if types is None:
            types = xrange(len(self.field_type))
        else:
            types = utilities.cast_axis_to_tuple(types, len(self.field_type))
562

theos's avatar
theos committed
563
564
565
566
        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)
567
        try:
theos's avatar
theos committed
568
            axes_list = reduce(lambda x, y: x+y, axes_list)
569
        except TypeError:
theos's avatar
theos committed
570
            axes_list = ()
csongor's avatar
csongor committed
571

theos's avatar
theos committed
572
573
574
        # perform the contraction on the d2o
        data = self.get_val(copy=False)
        data = getattr(data, op)(axis=axes_list)
csongor's avatar
csongor committed
575

theos's avatar
theos committed
576
577
578
        # 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
579
        else:
theos's avatar
theos committed
580
581
582
583
584
585
586
587
588
589
590
            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
591

theos's avatar
theos committed
592
593
    def sum(self, spaces=None, types=None):
        return self._contraction_helper('sum', spaces, types)
csongor's avatar
csongor committed
594

theos's avatar
theos committed
595
596
    def prod(self, spaces=None, types=None):
        return self._contraction_helper('prod', spaces, types)
csongor's avatar
csongor committed
597

theos's avatar
theos committed
598
599
    def all(self, spaces=None, types=None):
        return self._contraction_helper('all', spaces, types)
csongor's avatar
csongor committed
600

theos's avatar
theos committed
601
602
    def any(self, spaces=None, types=None):
        return self._contraction_helper('any', spaces, types)
csongor's avatar
csongor committed
603

theos's avatar
theos committed
604
605
    def min(self, spaces=None, types=None):
        return self._contraction_helper('min', spaces, types)
csongor's avatar
csongor committed
606

theos's avatar
theos committed
607
608
    def nanmin(self, spaces=None, types=None):
        return self._contraction_helper('nanmin', spaces, types)
csongor's avatar
csongor committed
609

theos's avatar
theos committed
610
611
    def max(self, spaces=None, types=None):
        return self._contraction_helper('max', spaces, types)
csongor's avatar
csongor committed
612

theos's avatar
theos committed
613
614
    def nanmax(self, spaces=None, types=None):
        return self._contraction_helper('nanmax', spaces, types)
csongor's avatar
csongor committed
615

theos's avatar
theos committed
616
617
    def mean(self, spaces=None, types=None):
        return self._contraction_helper('mean', spaces, types)
csongor's avatar
csongor committed
618

theos's avatar
theos committed
619
620
    def var(self, spaces=None, types=None):
        return self._contraction_helper('var', spaces, types)
csongor's avatar
csongor committed
621

theos's avatar
theos committed
622
623
    def std(self, spaces=None, types=None):
        return self._contraction_helper('std', spaces, types)
csongor's avatar
csongor committed
624

theos's avatar
theos committed
625
    # ---General binary methods---
csongor's avatar
csongor committed
626

theos's avatar
theos committed
627
    def _binary_helper(self, other, op, inplace=False):
csongor's avatar
csongor committed
628
        # if other is a field, make sure that the domains match
629
        if isinstance(other, Field):
theos's avatar
theos committed
630
631
632
633
            try:
                assert len(other.domain) == len(self.domain)
                for index in xrange(len(self.domain)):
                    assert other.domain[index] == self.domain[index]
634
                assert len(other.field_type) == len(self.field_type)
theos's avatar
theos committed
635
636
637
638
639
640
                for index in xrange(len(self.field_type)):
                    assert other.field_type[index] == self.field_type[index]
            except AssertionError:
                raise ValueError(about._errors.cstring(
                    "ERROR: domains are incompatible."))
            other = other.get_val(copy=False)
csongor's avatar
csongor committed
641

theos's avatar
theos committed
642
643
        self_val = self.get_val(copy=False)
        return_val = getattr(self_val, op)(other)
csongor's avatar
csongor committed
644
645
646
647
648
649

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

theos's avatar
theos committed
650
        working_field.set_val(return_val, copy=False)
csongor's avatar
csongor committed
651
652
653
        return working_field

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

656
    def __radd__(self, other):
theos's avatar
theos committed
657
        return self._binary_helper(other, op='__radd__')
csongor's avatar
csongor committed
658
659

    def __iadd__(self, other):
theos's avatar
theos committed
660
        return self._binary_helper(other, op='__iadd__', inplace=True)
csongor's avatar
csongor committed
661
662

    def __sub__(self, other):
theos's avatar
theos committed
663
        return self._binary_helper(other, op='__sub__')
csongor's avatar
csongor committed
664
665

    def __rsub__(self, other):
theos's avatar
theos committed
666
        return self._binary_helper(other, op='__rsub__')
csongor's avatar
csongor committed
667
668

    def __isub__(self, other):
theos's avatar
theos committed
669
        return self._binary_helper(other, op='__isub__', inplace=True)
csongor's avatar
csongor committed
670
671

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

674
    def __rmul__(self, other):
theos's avatar
theos committed
675
        return self._binary_helper(other, op='__rmul__')
csongor's avatar
csongor committed
676
677

    def __imul__(self, other):
theos's avatar
theos committed
678
        return self._binary_helper(other, op='__imul__', inplace=True)
csongor's avatar
csongor committed
679
680

    def __div__(self, other):
theos's avatar
theos committed
681
        return self._binary_helper(other, op='__div__')
csongor's avatar
csongor committed
682
683

    def __rdiv__(self, other):
theos's avatar
theos committed
684
        return self._binary_helper(other, op='__rdiv__')
csongor's avatar
csongor committed
685
686

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

csongor's avatar
csongor committed
689
    def __pow__(self, other):
theos's avatar
theos committed
690
        return self._binary_helper(other, op='__pow__')
csongor's avatar
csongor committed
691
692

    def __rpow__(self, other):
theos's avatar
theos committed
693
        return self._binary_helper(other, op='__rpow__')
csongor's avatar
csongor committed
694
695

    def __ipow__(self, other):
theos's avatar
theos committed
696
        return self._binary_helper(other, op='__ipow__', inplace=True)
csongor's avatar
csongor committed
697
698

    def __lt__(self, other):
theos's avatar
theos committed
699
        return self._binary_helper(other, op='__lt__')
csongor's avatar
csongor committed
700
701

    def __le__(self, other):
theos's avatar
theos committed
702
        return self._binary_helper(other, op='__le__')
csongor's avatar
csongor committed
703
704
705
706
707

    def __ne__(self, other):
        if other is None:
            return True
        else:
theos's avatar
theos committed
708
            return self._binary_helper(other, op='__ne__')
csongor's avatar
csongor committed
709
710
711
712
713

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

    def __ge__(self, other):
theos's avatar
theos committed
717
        return self._binary_helper(other, op='__ge__')
csongor's avatar
csongor committed
718
719

    def __gt__(self, other):
theos's avatar
theos committed
720
721
722
723
724
725
726
727
728
729
730
731
732
        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
733

734

735
class EmptyField(Field):
csongor's avatar
csongor committed
736
737
    def __init__(self):
        pass