nifty_field.py 47.6 KB
Newer Older
csongor's avatar
csongor committed
1
2
3
4
from __future__ import division
import numpy as np
import pylab as pl

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

8
9
10
from nifty.config import about, \
    nifty_configuration as gc, \
    dependency_injector as gdi
csongor's avatar
csongor committed
11

csongor's avatar
csongor committed
12
13
from nifty.nifty_core import space

csongor's avatar
csongor committed
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import nifty.nifty_utilities as utilities

POINT_DISTRIBUTION_STRATEGIES = DISTRIBUTION_STRATEGIES['global']


class field(object):
    """
        ..         ____   __             __          __
        ..       /   _/ /__/           /  /        /  /
        ..      /  /_   __   _______  /  /    ____/  /
        ..     /   _/ /  / /   __  / /  /   /   _   /
        ..    /  /   /  / /  /____/ /  /_  /  /_/  /
        ..   /__/   /__/  \______/  \___/  \______|  class

        Basic NIFTy class for fields.

        Parameters
        ----------
        domain : space
            The space wherein valid arguments live.

        val : {scalar, ndarray}, *optional*
            Defines field values, either to be given by a number interpreted
            as a constant array, or as an arbitrary array consistent with the
            space defined in domain or to be drawn from a random distribution
            controlled by kwargs.

        codomain : space, *optional*
            The space wherein the operator output lives (default: domain).


        Other Parameters
        ----------------
        random : string
            Indicates that the field values should be drawn from a certain
            distribution using a pseudo-random number generator.
            Supported distributions are:

            - "pm1" (uniform distribution over {+1,-1} or {+1,+i,-1,-i}
            - "gau" (normal distribution with zero-mean and a given standard
                deviation or variance)
            - "syn" (synthesizes from a given power spectrum)
            - "uni" (uniform distribution over [vmin,vmax[)

        dev : scalar
            Sets the standard deviation of the Gaussian distribution
            (default=1).

        var : scalar
            Sets the variance of the Gaussian distribution, outranking the dev
            parameter (default=1).

        spec : {scalar, list, array, field, function}
            Specifies a power spectrum from which the field values should be
            synthesized (default=1). Can be given as a constant, or as an
            array with indvidual entries per mode.
        log : bool
            Flag specifying if the spectral binning is performed on logarithmic
            scale or not; if set, the number of used bins is set
            automatically (if not given otherwise); by default no binning
            is done (default: None).
        nbin : integer
            Number of used spectral bins; if given `log` is set to ``False``;
            integers below the minimum of 3 induce an automatic setting;
            by default no binning is done (default: None).
        binbounds : {list, array}
            User specific inner boundaries of the bins, which are preferred
            over the above parameters; by default no binning is done
            (default: None).

        vmin : scalar
            Sets the lower limit for the uniform distribution.
        vmax : scalar
            Sets the upper limit for the uniform distribution.

        Attributes
        ----------
        domain : space
            The space wherein valid arguments live.

        val : {scalar, ndarray}, *optional*
            Defines field values, either to be given by a number interpreted
            as a constant array, or as an arbitrary array consistent with the
            space defined in domain or to be drawn from a random distribution
            controlled by the keyword arguments.

        codomain : space, *optional*
            The space wherein the operator output lives (default: domain).

    """

csongor's avatar
csongor committed
105
106
107
    def __init__(self, domain=None, val=None, codomain=None,
                 comm=gc['default_comm'], copy=False, dtype=np.dtype('float64'),
                 datamodel='fftw', **kwargs):
csongor's avatar
csongor committed
108
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
144
145
146
147
148
149
150
151
        """
            Sets the attributes for a field class instance.

        Parameters
        ----------
        domain : space
            The space wherein valid arguments live.

        val : {scalar,ndarray}, *optional*
            Defines field values, either to be given by a number interpreted
            as a constant array, or as an arbitrary array consistent with the
            space defined in domain or to be drawn from a random distribution
            controlled by the keyword arguments.

        codomain : space, *optional*
            The space wherein the operator output lives (default: domain).

        Returns
        -------
        Nothing

        """
        # If the given val was a field, try to cast it accordingly to the given
        # domain and codomain, etc...
        if isinstance(val, field):
            self._init_from_field(f=val,
                                  domain=domain,
                                  codomain=codomain,
                                  comm=comm,
                                  copy=copy,
                                  dtype=dtype,
                                  datamodel=datamodel,
                                  **kwargs)
        else:
            self._init_from_array(val=val,
                                  domain=domain,
                                  codomain=codomain,
                                  comm=comm,
                                  copy=copy,
                                  dtype=dtype,
                                  datamodel=datamodel,
                                  **kwargs)

    def _init_from_field(self, f, domain, codomain, comm, copy, dtype,
csongor's avatar
csongor committed
152
                         datamodel, **kwargs):
csongor's avatar
csongor committed
153
154
155
156
157
158
        # check domain
        if domain is None:
            domain = f.domain

        # check codomain
        if codomain is None:
csongor's avatar
csongor committed
159
            if self._check_codomain(domain, f.codomain):
csongor's avatar
csongor committed
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
                codomain = f.codomain
            else:
                codomain = self.get_codomain(domain)

        # Check if the given field lives in a space which is compatible to the
        # given domain
        if f.domain != domain:
            # Try to transform the given field to the given domain/codomain
            f = f.transform(new_domain=domain,
                            new_codomain=codomain)

        self._init_from_array(domain=domain,
                              val=f.val,
                              codomain=codomain,
                              comm=comm,
                              copy=copy,
                              dtype=dtype,
                              datamodel=datamodel,
                              **kwargs)

    def _init_from_array(self, val, domain, codomain, comm, copy, dtype,
                         datamodel, **kwargs):
        if dtype is None:
csongor's avatar
csongor committed
183
            dtype = self._get_dtype_from_domain(domain)
csongor's avatar
csongor committed
184
185
186
        self.dtype = dtype
        self.comm = self._parse_comm(comm)

csongor's avatar
csongor committed
187
188
189
190
191
192
193
194
        # if val is a distributed data object, we take it's datamodel,
        # since we don't want to redistribute large amounts of data, if not
        # necessary
        if isinstance(val, distributed_data_object):
            if datamodel != val.distribution_strategy:
                about.warnings.cprint("WARNING: datamodel set to val's "
                                      "datamodel.")
            datamodel = val.distribution_strategy
csongor's avatar
csongor committed
195
196
197
198
199
200
201
        if datamodel not in DISTRIBUTION_STRATEGIES['global']:
            about.warnings.cprint("WARNING: datamodel set to default.")
            self.datamodel = \
                gc['default_distribution_strategy']
        else:
            self.datamodel = datamodel
        # check domain
csongor's avatar
csongor committed
202
203
        self.domain = self._check_valid_domain(domain=domain)
        self._axis_list = self._get_axis_list_from_domain(domain=domain)
csongor's avatar
csongor committed
204
205
206

        # check codomain
        if codomain is None:
csongor's avatar
csongor committed
207
208
            codomain = self.get_codomain(domain=domain)
        elif not self._check_codomain(domain=domain, codomain=codomain):
csongor's avatar
csongor committed
209
210
211
212
213
214
            raise ValueError(about._errors.cstring(
                "ERROR: The given codomain is not compatible to the domain."))
        self.codomain = codomain

        if val is None:
            if kwargs == {}:
csongor's avatar
csongor committed
215
                val = self.cast(0)
csongor's avatar
csongor committed
216
            else:
csongor's avatar
csongor committed
217
                val = map(lambda z: self.get_random_values(domain = self.domain,
csongor's avatar
csongor committed
218
                    codomain=z, **kwargs), self.codomain)
csongor's avatar
csongor committed
219
220
        self.set_val(new_val=val, copy=copy)

csongor's avatar
csongor committed
221
222
223
224
225
226
227
228
229
230
231
232
233
    def _get_dtype_from_domain(self, domain=None):
        if domain is None:
            domain = self.domain
        dtype_tuple = tuple(space.dtype for space in domain)
        dtype = np.result_type(dtype_tuple)
        return dtype

    def _get_axis_list_from_domain(self, domain=None):
        if domain is None:
            domain = self.domain
        axis_list = [space.get_shape() for space in domain]
        return axis_list

csongor's avatar
csongor committed
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
    def _parse_comm(self, comm):
        # check if comm is a string -> the name of comm is given
        # -> Extract it from the mpi_module
        if isinstance(comm, str):
            if gc.validQ('default_comm', comm):
                result_comm = getattr(gdi[gc['mpi_module']], comm)
            else:
                raise ValueError(about._errors.cstring(
                    "ERROR: The given communicator-name is not supported."))
        # check if the given comm object is an instance of default Intracomm
        else:
            if isinstance(comm, gdi[gc['mpi_module']].Intracomm):
                result_comm = comm
            else:
                raise ValueError(about._errors.cstring(
                    "ERROR: The given comm object is not an instance of the " +
                    "default-MPI-module's Intracomm Class."))
        return result_comm

csongor's avatar
csongor committed
253
    def _check_valid_domain(self, domain):
csongor's avatar
csongor committed
254
        if not isinstance(domain, tuple):
csongor's avatar
csongor committed
255
256
257
258
259
260
            raise TypeError(about._errors.cstring(
                "ERROR: The given domain is not a list."))
        for d in domain:
            if not isinstance(d, space):
                raise TypeError(about._errors.cstring(
                    "ERROR: Given domain is not a space."))
csongor's avatar
csongor committed
261
            elif d.dtype > self.dtype:
csongor's avatar
csongor committed
262
                raise AttributeError(about._errors.cstring(
csongor's avatar
csongor committed
263
                    "ERROR: The dtype of a space in the domain is larger than "
csongor's avatar
csongor committed
264
265
266
                    "the field's dtype."))
        return domain

csongor's avatar
csongor committed
267
    def _check_codomain(self, domain, codomain):
csongor's avatar
csongor committed
268
269
        if codomain is None:
            return False
csongor's avatar
csongor committed
270
        if len(domain) == len(codomain):
csongor's avatar
csongor committed
271
272
273
274
275
276
            return np.all(map((lambda d, c: d._check_codomain(c)), domain,
                              codomain))
        else:
            return False

    def get_codomain(self, domain):
csongor's avatar
csongor committed
277
278
        if len(domain) == 1:
            return (domain[0].get_codomain(),)
csongor's avatar
csongor committed
279
        else:
280
281
282
            codomain = tuple(space.get_codomain() for space in domain)
            self.codomain = codomain
            return codomain
csongor's avatar
csongor committed
283

csongor's avatar
csongor committed
284
285
286
287
288

    def get_random_values(self, **kwargs):
        raise NotImplementedError(about._errors.cstring(
            "ERROR: no generic instance method 'enforce_power'."))

csongor's avatar
csongor committed
289
    def __len__(self):
290
        return int(self.get_dim()[0])
csongor's avatar
csongor committed
291
292
293
294
295
296
297

    def apply_scalar_function(self, function, inplace=False):
        if inplace:
            working_field = self
        else:
            working_field = self.copy_empty()

csongor's avatar
csongor committed
298
        data_object = map(
csongor's avatar
csongor committed
299
300
301
302
303
304
305
            lambda z: self.domain.apply_scalar_function(z, function, inplace),
            self.get_val())

        working_field.set_val(data_object)
        return working_field

    def copy(self, domain=None, codomain=None):
csongor's avatar
csongor committed
306
        copied_val = map(
csongor's avatar
csongor committed
307
308
309
310
311
312
313
314
315
316
317
            lambda z: self.domain.unary_operation(z, op='copy'),
            self.get_val())
        new_field = self.copy_empty(domain=domain, codomain=codomain)
        new_field.set_val(new_val=copied_val)
        return new_field

    def _fast_copy_empty(self):
        # make an empty field
        new_field = EmptyField()
        # repair its class
        new_field.__class__ = self.__class__
csongor's avatar
csongor committed
318
        # copy domain, codomain and val
csongor's avatar
csongor committed
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
        for key, value in self.__dict__.items():
            if key != 'val':
                new_field.__dict__[key] = value
            else:
                new_field.__dict__[key] = \
                    self.domain.unary_operation(self.val, op='copy_empty')
        return new_field

    def copy_empty(self, domain=None, codomain=None, dtype=None, comm=None,
                   datamodel=None, **kwargs):
        if domain is None:
            domain = self.domain
        if codomain is None:
            codomain = self.codomain
        if dtype is None:
            dtype = self.dtype
        if comm is None:
            comm = self.comm
        if datamodel is None:
            datamodel = self.datamodel

        if (domain is self.domain and
341
342
343
344
345
                    codomain is self.codomain and
                    dtype == self.dtype and
                    comm == self.comm and
                    datamodel == self.datamodel and
                    kwargs == {}):
csongor's avatar
csongor committed
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
            new_field = self._fast_copy_empty()
        else:
            new_field = field(domain=domain, codomain=codomain, dtype=dtype,
                              comm=comm, datamodel=datamodel, **kwargs)
        return new_field

    def set_val(self, new_val=None, copy=False):
        """
            Resets the field values.

            Parameters
            ----------
            new_val : {scalar, ndarray}
                New field values either as a constant or an arbitrary array.

        """
        if new_val is not None:
            if copy:
csongor's avatar
csongor committed
364
                new_val = map(
365
366
                    lambda z: self.unary_operation(z, 'copy'),
                    new_val)
csongor's avatar
csongor committed
367
            self.val = self.cast(new_val)
csongor's avatar
csongor committed
368
369
370
371
372
373
374
375
        return self.val

    def get_val(self):
        return self.val

    # TODO: Add functionality for boolean indexing.

    def __getitem__(self, key):
csongor's avatar
csongor committed
376
377
378
379
        return self.val[key]

    def __setitem__(self, key, item):
        self.val[key] = item
csongor's avatar
csongor committed
380
381
382

    def get_shape(self):
        if len(self.domain) > 1:
383
384
            global_shape = reduce(lambda x, y: x.get_shape() + y.get_shape(),
                                  self.domain)
csongor's avatar
csongor committed
385
386
387
388
389
390
391
392
        else:
            global_shape = self.domain[0].get_shape()

        if isinstance(global_shape, tuple):
            return global_shape
        else:
            return ()

393
    def get_dim(self):
csongor's avatar
csongor committed
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
        """
            Computes the (array) dimension of the underlying space.

            Parameters
            ----------
            split : bool
                Sets the output to be either split up per axis or
                in form of total number of field entries in all
                dimensions (default=False)

            Returns
            -------
            dim : {scalar, ndarray}
                Dimension of space.

        """
        return np.prod(self.get_shape())

    def get_dof(self, split=False):
        dim = self.get_dim()
        if np.issubdtype(self.dtype, np.complex):
415
            return 2 * dim
csongor's avatar
csongor committed
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
        else:
            return dim

    def _map(self, function, *args):
        return utilities.field_map(self.get_shape(), function, *args)

    def cast(self, x=None, dtype=None):
        if dtype is not None:
            dtype = np.dtype(dtype)
        if dtype is None:
            dtype = self.dtype
        casted_x = self._cast_to_d2o(x, dtype=dtype)
        return self._complement_cast(casted_x)

    def _cast_to_d2o(self, x, dtype=None, shape=None, **kwargs):
        """
            Computes valid field values from a given object, trying
            to translate the given data into a valid form. Thereby it is as
            benevolent as possible.

            Parameters
            ----------
            x : {float, numpy.ndarray, nifty.field}
                Object to be transformed into an array of valid field values.

            Returns
            -------
            x : numpy.ndarray, distributed_data_object
                Array containing the field values, which are compatible to the
                space.

            Other parameters
            ----------------
            verbose : bool, *optional*
                Whether the method should raise a warning if information is
                lost during casting (default: False).
        """
        if isinstance(x, field):
            x = x.get_val()

        if dtype is None:
            dtype = self.dtype

        if shape is None:
            shape = self.get_shape()

        # Case 1: x is a distributed_data_object
        if isinstance(x, distributed_data_object):
            to_copy = False

            # Check the shape
            if np.any(np.array(x.shape) != np.array(shape)):
                # Check if at least the number of degrees of freedom is equal
                if x.get_dim() == self.get_dim():
                    try:
                        temp = x.copy_empty(global_shape=shape)
                        temp.set_local_data(x, copy=False)
                    except:
                        # If the number of dof is equal or 1, use np.reshape...
                        about.warnings.cflush(
                            "WARNING: Trying to reshape the data. This " +
                            "operation is expensive as it consolidates the " +
                            "full data!\n")
                        temp = x
                        temp = np.reshape(temp, shape)
                    # ... and cast again
csongor's avatar
csongor committed
482
                    return self._cast_to_d2o(temp, dtype=dtype, **kwargs)
csongor's avatar
csongor committed
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523

                else:
                    raise ValueError(about._errors.cstring(
                        "ERROR: Data has incompatible shape!"))

            # Check the dtype
            if x.dtype != dtype:
                if x.dtype > dtype:
                    about.warnings.cflush(
                        "WARNING: Datatypes are of conflicting precision " +
                        "(own: " + str(dtype) + " <> foreign: " +
                        str(x.dtype) + ") and will be casted! Potential " +
                        "loss of precision!\n")
                to_copy = True

            # Check the distribution_strategy
            if x.distribution_strategy != self.datamodel:
                to_copy = True

            if to_copy:
                temp = x.copy_empty(dtype=dtype,
                                    distribution_strategy=self.datamodel)
                temp.set_data(to_key=(slice(None),),
                              data=x,
                              from_key=(slice(None),))
                temp.hermitian = x.hermitian
                x = temp

            return x

        # Case 2: x is something else
        # Use general d2o casting
        else:
            x = distributed_data_object(x,
                                        global_shape=self.get_shape(),
                                        dtype=dtype,
                                        distribution_strategy=self.datamodel)
            # Cast the d2o
            return self.cast(x, dtype=dtype)

    def _complement_cast(self, x):
csongor's avatar
csongor committed
524
525
        for ind, space in enumerate(self.domain):
            space._complement_cast(x, axis=self._axis_list[ind])
csongor's avatar
csongor committed
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
        return x

    def set_domain(self, new_domain=None, force=False):
        """
            Resets the codomain of the field.

            Parameters
            ----------
            new_codomain : space
                 The new space wherein the transform of the field should live.
                 (default=None).

        """
        # check codomain
        if new_domain is None:
            new_domain = self.codomain.get_codomain()
        elif not force:
543
            assert (self.codomain.check_codomain(new_domain))
csongor's avatar
csongor committed
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
        self.domain = new_domain
        return self.domain

    def set_codomain(self, new_codomain=None, force=False):
        """
            Resets the codomain of the field.

            Parameters
            ----------
            new_codomain : space
                 The new space wherein the transform of the field should live.
                 (default=None).

        """
        # check codomain
        if new_codomain is None:
            new_codomain = self.domain.get_codomain()
        elif not force:
562
            assert (self.domain.check_codomain(new_codomain))
csongor's avatar
csongor committed
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
        self.codomain = new_codomain
        return self.codomain

    def weight(self, power=1, overwrite=False):
        """
            Returns the field values, weighted with the volume factors to a
            given power. The field values will optionally be overwritten.

            Parameters
            ----------
            power : scalar, *optional*
                Specifies the optional power coefficient to which the field
                values are taken (default=1).

            overwrite : bool, *optional*
                Whether to overwrite the field values or not (default: False).

            Returns
            -------
            field   : field, *optional*
                If overwrite is False, the weighted field is returned.
                Otherwise, nothing is returned.

        """
        if overwrite:
            new_field = self
        else:
            new_field = self.copy_empty()

csongor's avatar
csongor committed
592
        new_val = map(lambda y: self.domain.calc_weight(y, power=power),
593
                      self.get_val())
csongor's avatar
csongor committed
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613

        new_field.set_val(new_val=new_val)
        return new_field

    def norm(self, q=0.5):
        """
            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.

        """
        if q == 0.5:
614
            return (self.dot(x=self)) ** (1 / 2)
csongor's avatar
csongor committed
615
        else:
616
            return self.dot(x=self ** (q - 1)) ** (1 / q)
csongor's avatar
csongor committed
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659

    def dot(self, x=None, axis=None, bare=False):
        """
            Computes the inner product of the field with a given object
            implying the correct volume factor needed to reflect the
            discretization of the continuous fields.

            Parameters
            ----------
            x : {scalar, ndarray, field}, *optional*
                The object with which the inner product is computed
                (default=None).

            Returns
            -------
            dot : scalar
                The result of the inner product.

        """
        # Case 1: x equals None
        if x is None:
            return None

        # Case 2: x is a field
        elif isinstance(x, field):
            # if x lives in the cospace, transform it an make a
            # recursive call
            try:
                if self.domain.harmonic != x.domain.harmonic:
                    return self.dot(x=x.transform(), axis=axis)
            except(AttributeError):
                pass

            # whether the domain matches exactly or not:
            # extract the data from x and try to dot with this
            return self.dot(x=x.get_val(), axis=axis, bare=bare)

        # Case 3: x is something else
        else:
            # Cast the input in order to cure dtype and shape differences
            casted_x = self._cast_to_ishape(x)
            # Compute the dot respecting the fact of discrete/continous spaces
            if self.domain.discrete or bare:
csongor's avatar
csongor committed
660
                result = map(
csongor's avatar
csongor committed
661
662
663
664
                    lambda z1, z2: self.domain.calc_dot(z1, z2),
                    self.get_val(),
                    casted_x)
            else:
csongor's avatar
csongor committed
665
                result = map(
csongor's avatar
csongor committed
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
                    lambda z1, z2: self.domain.calc_dot(
                        self.domain.calc_weight(z1, power=1),
                        z2),
                    self.get_val(), casted_x)

            return np.sum(result, axis=axis)

    def vdot(self, *args, **kwargs):
        return self.dot(*args, **kwargs)

    def outer_dot(self, x=1, axis=None):

        # Use the fact that self.val is a numpy array of dtype np.object
        # -> The shape casting, etc... can be done by numpy
        # If ishape == (), self.val will be multiplied with x directly.
        if self.ishape == ():
            return self * x
        new_val = np.sum(self.get_val() * x, axis=axis)
        # if axis != None, the contraction was not overarching
        if np.dtype(new_val.dtype).type == np.object_:
            new_field = self.copy_empty(ishape=new_val.shape)
        else:
            new_field = self.copy_empty(ishape=())
        new_field.set_val(new_val=new_val)
        return new_field

    def tensor_product(self, x=None):
        if x is None:
            return self
        elif np.isscalar(x) == True:
            return self * x
        else:
            if self.ishape == ():
                temp_val = self.get_val()
                old_val = np.empty((1,), dtype=np.object)
                old_val[0] = temp_val
            else:
                old_val = self.get_val()

            new_val = np.tensordot(old_val, x, axes=0)

            if self.ishape == ():
                new_val = new_val[0]
            new_field = self.copy_empty(ishape=new_val.shape)
            new_field.set_val(new_val=new_val)

            return new_field

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

csongor's avatar
csongor committed
729
        new_val = map(
csongor's avatar
csongor committed
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
            lambda z: self.domain.unary_operation(z, 'conjugate'),
            self.get_val())
        work_field.set_val(new_val=new_val)

        return work_field

    def transform(self, new_domain=None, new_codomain=None, overwrite=False,
                  **kwargs):
        """
            Computes the transform of the field using the appropriate conjugate
            transformation.

            Parameters
            ----------
            codomain : space, *optional*
                Domain of the transform of the field (default:self.codomain)

            overwrite : bool, *optional*
                Whether to overwrite the field or not (default: False).

            Other Parameters
            ----------------
            iter : scalar
                Number of iterations (default: 0)

            Returns
            -------
            field : field, *optional*
                If overwrite is False, the transformed field is returned.
                Otherwise, nothing is returned.

        """
        if new_domain is None:
            new_domain = self.codomain

        if new_codomain is None:
            # try to recycle the old domain
            if new_domain.check_codomain(self.domain):
                new_codomain = self.domain
            else:
                new_codomain = new_domain.get_codomain()
        else:
772
            assert (new_domain.check_codomain(new_codomain))
csongor's avatar
csongor committed
773

csongor's avatar
csongor committed
774
        new_val = map(
csongor's avatar
csongor committed
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
            lambda z: self.domain.calc_transform(
                z, codomain=new_domain, **kwargs),
            self.get_val())

        if overwrite:
            return_field = self
            return_field.set_codomain(new_codomain=new_codomain, force=True)
            return_field.set_domain(new_domain=new_domain, force=True)
        else:
            return_field = self.copy_empty(domain=new_domain,
                                           codomain=new_codomain)
        return_field.set_val(new_val=new_val, copy=False)

        return return_field

    def smooth(self, sigma=0, inplace=False, **kwargs):
        """
            Smoothes the field by convolution with a Gaussian kernel.

            Parameters
            ----------
            sigma : scalar, *optional*
                standard deviation of the Gaussian kernel specified in units of
                length in position space (default: 0)

            overwrite : bool, *optional*
                Whether to overwrite the field or not (default: False).

            Other Parameters
            ----------------
            iter : scalar
                Number of iterations (default: 0)

            Returns
            -------
            field : field, *optional*
                If overwrite is False, the transformed field is returned.
                Otherwise, nothing is returned.

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

csongor's avatar
csongor committed
820
        new_val = map(
csongor's avatar
csongor committed
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
            lambda z: self.domain.calc_smooth(z, sigma=sigma, **kwargs),
            self.get_val())

        new_field.set_val(new_val=new_val)
        return new_field

    def power(self, **kwargs):
        """
            Computes the power spectrum of the field values.

            Other Parameters
            ----------------
            pindex : ndarray, *optional*
                Specifies the indexing array for the distribution of
                indices in conjugate space (default: None).
            kindex : numpy.ndarray, *optional*
                Scale corresponding to each band in the power spectrum
                (default: None).
            rho : scalar
                Number of degrees of freedom per irreducible band
                (default=None).
            log : bool, *optional*
                Flag specifying if the spectral binning is performed on
                logarithmic
                scale or not; if set, the number of used bins is set
                automatically (if not given otherwise); by default no binning
                is done (default: None).
            nbin : integer, *optional*
                Number of used spectral bins; if given `log` is set to
                ``False``;
                integers below the minimum of 3 induce an automatic setting;
                by default no binning is done (default: None).
            binbounds : {list, array}, *optional*
                User specific inner boundaries of the bins, which are preferred
                over the above parameters; by default no binning is done
                (default: None).
            iter : scalar
                Number of iterations (default: 0)

            Returns
            -------
            spec : ndarray
                Returns the power spectrum.

        """
866
        if ("codomain" in kwargs):
csongor's avatar
csongor committed
867
868
869
            kwargs.__delitem__("codomain")
            about.warnings.cprint("WARNING: codomain was removed from kwargs.")

csongor's avatar
csongor committed
870
        power_spectrum = map(
csongor's avatar
csongor committed
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
            lambda z: self.domain.calc_power(z, codomain=self.codomain,
                                             **kwargs),
            self.get_val())

        return power_spectrum

    def hat(self):
        """
            Translates the field into a diagonal operator.

            Returns
            -------
            D : operator
                The new diagonal operator instance.

        """
        from nifty.operators.nifty_operators import diagonal_operator
        return diagonal_operator(domain=self.domain,
                                 diag=self.get_val(),
                                 bare=False,
                                 ishape=self.ishape)

    def inverse_hat(self):
        """
            Translates the inverted field into a diagonal operator.

            Returns
            -------
            D : operator
                The new diagonal operator instance.

        """
csongor's avatar
csongor committed
903
        any_zero_Q = map(lambda z: (z == 0).any(), self.get_val())
csongor's avatar
csongor committed
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
        any_zero_Q = np.any(any_zero_Q)
        if any_zero_Q:
            raise AttributeError(
                about._errors.cstring("ERROR: singular operator."))
        else:
            from nifty.operators.nifty_operators import diagonal_operator
            return diagonal_operator(domain=self.domain,
                                     diag=(1 / self).get_val(),
                                     bare=False,
                                     ishape=self.ishape)

    def plot(self, **kwargs):
        """
            Plots the field values using matplotlib routines.

            Other Parameters
            ----------------
            title : string
                Title of the plot (default= "").
            vmin : scalar
                Minimum value displayed (default=min(x)).
            vmax : scalar
                Maximum value displayed (default=max(x)).
            power : bool
                Whether to plot the power spectrum or the array (default=None).
            unit : string
                The unit of the field values (default="").
            norm : scalar
                A normalization (default=None).
            cmap : cmap
                A color map (default=None).
            cbar : bool
                Whether to show the color bar or not (default=True).
            other : {scalar, ndarray, field}
                Object or tuple of objects to be added (default=None).
            legend : bool
                Whether to show the legend or not (default=False).
            mono : bool
                Whether to plot the monopol of the power spectrum or not
                (default=True).
            save : string, *optional*
                Valid file name where the figure is to be stored, by default
                the figure is not saved (default: False).
            error : {scalar, ndarray, field}
                object indicating some confidence intervall (default=None).
            iter : scalar
                Number of iterations (default: 0).
            kindex : scalar
                The spectral index per irreducible band (default=None).
            log : bool, *optional*
                Flag specifying if the spectral binning is performed on
                logarithmic
                scale or not; if set, the number of used bins is set
                automatically (if not given otherwise); by default no binning
                is done (default: None).
            nbin : integer, *optional*
                Number of used spectral bins; if given `log` is set to
                ``False``;
                integers below the minimum of 3 induce an automatic setting;
                by default no binning is done (default: None).
            binbounds : {list, array}, *optional*
                User specific inner boundaries of the bins, which are preferred
                over the above parameters; by default no binning is done
                (default: None).

            Notes
            -----
            The applicability of the keyword arguments depends on the
            respective space on which the field is defined. Confer to the
            corresponding :py:meth:`get_plot` method.

        """
        # if a save path is given, set pylab to not-interactive
        remember_interactive = pl.isinteractive()
        pl.matplotlib.interactive(not bool(kwargs.get("save", False)))

        if "codomain" in kwargs:
            kwargs.__delitem__("codomain")
            about.warnings.cprint("WARNING: codomain was removed from kwargs.")

        # draw/save the plot(s)
        self.domain.get_plot(self.val, codomain=self.codomain, **kwargs)

        # restore the pylab interactiveness
        pl.matplotlib.interactive(remember_interactive)

    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      = " + \
997
998
999
1000
1001
1002
               repr(self.domain) + \
               "\n- val         = " + repr(self.get_val()) + \
               "\n  - min.,max. = " + str(minmax) + \
               "\n  - mean = " + str(mean) + \
               "\n- codomain      = " + repr(self.codomain) + \
               "\n- ishape          = " + str(self.ishape)
csongor's avatar
csongor committed
1003

csongor's avatar
csongor committed
1004
1005
1006
1007
1008
1009
    def sum(self, **kwargs):
        return self._unary_operation(self.get_val(), op='sum', **kwargs)

    def prod(self, **kwargs):
        return self._unary_operation(self.get_val(), op='prod', **kwargs)

csongor's avatar
csongor committed
1010
1011
    def all(self, **kwargs):
        return self._unary_operation(self.get_val(), op='all', **kwargs)
csongor's avatar
csongor committed
1012

csongor's avatar
csongor committed
1013
1014
1015
    def any(self, **kwargs):
        return self._unary_operation(self.get_val(), op='any', **kwargs)

csongor's avatar
csongor committed
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
    def min(self, ignore=False, **kwargs):
        """
            Returns the minimum of the field values.

            Parameters
            ----------
            ignore : bool
                Whether to ignore NANs or not (default: False).

            Returns
            -------
            amin : {scalar, ndarray}
                Minimum field value.

            See Also
            --------
            np.amin, np.nanmin

        """
csongor's avatar
csongor committed
1035
        return self._unary_operation(self.get_val(), op='amin', **kwargs)
csongor's avatar
csongor committed
1036
1037

    def nanmin(self, **kwargs):
csongor's avatar
csongor committed
1038
        return self._unary_operation(self.get_val(), op='nanmin', **kwargs)
csongor's avatar
csongor committed
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058

    def max(self, **kwargs):
        """
            Returns the maximum of the field values.

            Parameters
            ----------
            ignore : bool
                Whether to ignore NANs or not (default: False).

            Returns
            -------
            amax : {scalar, ndarray}
                Maximum field value.

            See Also
            --------
            np.amax, np.nanmax

        """
csongor's avatar
csongor committed
1059
        return self._unary_operation(self.get_val(), op='amax', **kwargs)
csongor's avatar
csongor committed
1060
1061

    def nanmax(self, **kwargs):
csongor's avatar
csongor committed
1062
        return self._unary_operation(self.get_val(), op='nanmax', **kwargs)
csongor's avatar
csongor committed
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077

    def median(self, **kwargs):
        """
            Returns the median of the field values.

            Returns
            -------
            med : scalar
                Median field value.

            See Also
            --------
            np.median

        """
csongor's avatar
csongor committed
1078
        return self._unary_operation(self.get_val(), op='median',
csongor's avatar
csongor committed
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
                                  **kwargs)

    def mean(self, **kwargs):
        """
            Returns the mean of the field values.

            Returns
            -------
            mean : scalar
                Mean field value.

            See Also
            --------
            np.mean

        """
csongor's avatar
csongor committed
1095
        return self._unary_operation(self.get_val(), op='mean',
csongor's avatar
csongor committed
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
                                  **kwargs)

    def std(self, **kwargs):
        """
            Returns the standard deviation of the field values.

            Returns
            -------
            std : scalar
                Standard deviation of the field values.

            See Also
            --------
            np.std

        """
csongor's avatar
csongor committed
1112
        return self._unary_operation(self.get_val(), op='std',
csongor's avatar
csongor committed
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
                                  **kwargs)

    def var(self, **kwargs):
        """
            Returns the variance of the field values.

            Returns
            -------
            var : scalar
                Variance of the field values.

            See Also
            --------
            np.var

        """
csongor's avatar
csongor committed
1129
        return self._unary_operation(self.get_val(), op='var',
csongor's avatar
csongor committed
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
                                  **kwargs)

    def argmin(self, split=True, **kwargs):
        """
            Returns the index of the minimum field value.

            Parameters
            ----------
            split : bool
                Whether to split (unravel) the flat index or not; does not
                apply to multiple indices along some axis (default: True).

            Returns
            -------
            ind : {integer, tuple, array}
                Index of the minimum field value being an integer for
                one-dimensional fields, a tuple for multi-dimensional fields,
                and an array in case minima along some axis are requested.

            See Also
            --------
            np.argmax, np.argmin

        """
        if split:
csongor's avatar
csongor committed
1155
            return self._unary_operation(self.get_val(), op='argmin_nonflat',
csongor's avatar
csongor committed
1156
1157
                                      **kwargs)
        else:
csongor's avatar
csongor committed
1158
            return self._unary_operation(self.get_val(), op='argmin',
csongor's avatar
csongor committed
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
                                      **kwargs)

    def argmax(self, split=True, **kwargs):
        """
            Returns the index of the maximum field value.

            Parameters
            ----------
            split : bool
                Whether to split (unravel) the flat index or not; does not
                apply to multiple indices along some axis (default: True).

            Returns
            -------
            ind : {integer, tuple, array}
                Index of the maximum field value being an integer for
                one-dimensional fields, a tuple for multi-dimensional fields,
                and an array in case maxima along some axis are requested.

            See Also
            --------
            np.argmax, np.argmin

        """
        if split:
csongor's avatar
csongor committed
1184
            return self._unary_operation(self.get_val(), op='argmax_nonflat',
csongor's avatar
csongor committed
1185
1186
                                      **kwargs)
        else:
csongor's avatar
csongor committed
1187
            return self._unary_operation(self.get_val(), op='argmax',
csongor's avatar
csongor committed
1188
1189
1190
1191
1192
1193
                                      **kwargs)

    # TODO: Implement the full range of unary and binary operotions

    def __pos__(self):
        new_field = self.copy_empty()
csongor's avatar
csongor committed
1194
        new_val = self._unary_operation(self.get_val(), op='pos')
csongor's avatar
csongor committed
1195
1196
1197
1198
1199
        new_field.set_val(new_val=new_val)
        return new_field

    def __neg__(self):
        new_field = self.copy_empty()
csongor's avatar
csongor committed
1200
        new_val = self._unary_operation(self.get_val(), op='neg')
csongor's avatar
csongor committed
1201
1202
1203
1204
1205
        new_field.set_val(new_val=new_val)
        return new_field

    def __abs__(self):
        new_field = self.copy_empty()
csongor's avatar
csongor committed
1206
        new_val = self._unary_operation(self.get_val(), op='abs')
csongor's avatar
csongor committed
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
        new_field.set_val(new_val=new_val)
        return new_field

    def _binary_helper(self, other, op='None', inplace=False):
        # if other is a field, make sure that the domains match
        if isinstance(other, field):
            other = field(domain=self.domain,
                          val=other,
                          codomain=self.codomain,
                          copy=False)
        try:
            other_val = other.get_val()
        except AttributeError:
            other_val = other

        # bring other_val into the right shape
1223
        other_val = self._cast_to_d2o(other_val)
csongor's avatar
csongor committed
1224

csongor's avatar
csongor committed
1225
        new_val = map(
1226
            lambda z1, z2: self.binary_operation(z1, z2, op=op, cast=0),
csongor's avatar
csongor committed
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
            self.get_val(),
            other_val)

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

        working_field.set_val(new_val=new_val)
        return working_field

csongor's avatar
csongor committed
1238
    def _unary_operation(self, x, op='None', axis=None, **kwargs):
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
        """
        x must be a numpy array which is compatible with the space!
        Valid operations are

        """
        translation = {'pos': lambda y: getattr(y, '__pos__')(),
                       'neg': lambda y: getattr(y, '__neg__')(),
                       'abs': lambda y: getattr(y, '__abs__')(),
                       'real': lambda y: getattr(y, 'real'),
                       'imag': lambda y: getattr(y, 'imag'),
                       'nanmin': lambda y: getattr(y, 'nanmin')(axis=axis),
                       'amin': lambda y: getattr(y, 'amin')(axis=axis),
                       'nanmax': lambda y: getattr(y, 'nanmax')(axis=axis),
                       'amax': lambda y: getattr(y, 'amax')(axis=axis),
                       'median': lambda y: getattr(y, 'median')(axis=axis),
                       'mean': lambda y: getattr(y, 'mean')(axis=axis),
                       'std': lambda y: getattr(y, 'std')(axis=axis),
                       'var': lambda y: getattr(y, 'var')(axis=axis),
                       'argmin_nonflat': lambda y: getattr(y, 'argmin_nonflat')(
                           axis=axis),
                       'argmin': lambda y: getattr(y, 'argmin')(axis=axis),
                       'argmax_nonflat': lambda y: getattr(y, 'argmax_nonflat')(
                           axis=axis),
                       'argmax': lambda y: getattr(y, 'argmax')(axis=axis),
                       'conjugate': lambda y: getattr(y, 'conjugate')(),
                       'sum': lambda y: getattr(y, 'sum')(axis=axis),
                       'prod': lambda y: getattr(y, 'prod')(axis=axis),
                       'unique': lambda y: getattr(y, 'unique')(),
                       'copy': lambda y: getattr(y, 'copy')(),
                       'copy_empty': lambda y: getattr(y, 'copy_empty')(),
                       'isnan': lambda y: getattr(y, 'isnan')(),
                       'isinf': lambda y: getattr(y, 'isinf')(),
                       'isfinite': lambda y: getattr(y, 'isfinite')(),
                       'nan_to_num': lambda y: getattr(y, 'nan_to_num')(),
                       'all': lambda y: getattr(y, 'all')(axis=axis),
                       'any': lambda y: getattr(y, 'any')(axis=axis),
                       'None': lambda y: y}

        return translation[op](x, **kwargs)

    def binary_operation(self, x, y, op='None', cast=0):

        translation = {'add': lambda z: getattr(z, '__add__'),
                       'radd': lambda z: getattr(z, '__radd__'),
                       'iadd': lambda z: getattr(z, '__iadd__'),
                       'sub': lambda z: getattr(z, '__sub__'),
                       'rsub': lambda z: getattr(z, '__rsub__'),
                       'isub': lambda z: getattr(z, '__isub__'),
                       'mul': lambda z: getattr(z, '__mul__'),
                       'rmul': lambda z: getattr(z, '__rmul__'),
                       'imul': lambda z: getattr(z, '__imul__'),
                       'div': lambda z: getattr(z, '__div__'),
                       'rdiv': lambda z: getattr(z, '__rdiv__'),
                       'idiv': lambda z: getattr(z, '__idiv__'),
                       'pow': lambda z: getattr(z, '__pow__'),
                       'rpow': lambda z: getattr(z, '__rpow__'),
                       'ipow': lambda z: getattr(z, '__ipow__'),
                       'ne': lambda z: getattr(z, '__ne__'),
                       'lt': lambda z: getattr(z, '__lt__'),
                       'le': lambda z: getattr(z, '__le__'),
                       'eq': lambda z: getattr(z, '__eq__'),
                       'ge': lambda z: getattr(z, '__ge__'),
                       'gt': lambda z: getattr(z, '__gt__'),
                       'None': lambda z: lambda u: u}

        if (cast & 1) != 0:
            x = self.cast(x)
        if (cast & 2) != 0:
            y = self.cast(y)

        return translation[op](x)(y)

csongor's avatar
csongor committed
1311
1312
    def __add__(self, other):
        return self._binary_helper(other, op='add')
1313

csongor's avatar
csongor committed
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
    __radd__ = __add__

    def __iadd__(self, other):
        return self._binary_helper(other, op='iadd', inplace=True)

    def __sub__(self, other):
        return self._binary_helper(other, op='sub')

    def __rsub__(self, other):
        return self._binary_helper(other, op='rsub')

    def __isub__(self, other):
        return self._binary_helper(other, op='isub', inplace=True)

    def __mul__(self, other):
        return self._binary_helper(other, op='mul')
1330

csongor's avatar
csongor committed
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
    __rmul__ = __mul__

    def __imul__(self, other):
        return self._binary_helper(other, op='imul', inplace=True)

    def __div__(self, other):
        return self._binary_helper(other, op='div')

    def __rdiv__(self, other):
        return self._binary_helper(other, op='rdiv')

    def __idiv__(self, other):
        return self._binary_helper(other, op='idiv', inplace=True)
1344

csongor's avatar
csongor committed
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
    __truediv__ = __div__
    __itruediv__ = __idiv__

    def __pow__(self, other):
        return self._binary_helper(other, op='pow')

    def __rpow__(self, other):
        return self._binary_helper(other, op='rpow')

    def __ipow__(self, other):
        return self._binary_helper(other, op='ipow', inplace=True)

    def __lt__(self, other):
        return self._binary_helper(other, op='lt')

    def __le__(self, other):
        return self._binary_helper(other, op='le')

    def __ne__(self, other):
        if other is None:
            return True
        else:
            return self._binary_helper(other, op='ne')

    def __eq__(self, other):
        if other is None:
            return False
        else:
            return self._binary_helper(other, op='eq')

    def __ge__(self, other):
        return self._binary_helper(other, op='ge')

    def __gt__(self, other):
        return self._binary_helper(other, op='gt')

1381

csongor's avatar
csongor committed
1382
1383
1384
class EmptyField(field):
    def __init__(self):
        pass