field.py 49.2 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

12 13
from nifty.field_types import FieldType,\
                              FieldArray
14

15
from nifty.spaces.space import Space
csongor's avatar
csongor committed
16

csongor's avatar
csongor committed
17
import nifty.nifty_utilities as utilities
18
from nifty_random import random
csongor's avatar
csongor committed
19 20 21 22

POINT_DISTRIBUTION_STRATEGIES = DISTRIBUTION_STRATEGIES['global']


23
class Field(object):
csongor's avatar
csongor committed
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 105 106 107 108
    """
        ..         ____   __             __          __
        ..       /   _/ /__/           /  /        /  /
        ..      /  /_   __   _______  /  /    ____/  /
        ..     /   _/ /  / /   __  / /  /   /   _   /
        ..    /  /   /  / /  /____/ /  /_  /  /_/  /
        ..   /__/   /__/  \______/  \___/  \______|  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).

    """

109
    def __init__(self, domain=None, val=None, codomain=None,
110
                 dtype=None, field_type=None, copy=False,
111
                 datamodel=None, **kwargs):
csongor's avatar
csongor committed
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
        """
            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...
136
        if isinstance(val, Field):
csongor's avatar
csongor committed
137 138 139 140 141
            self._init_from_field(f=val,
                                  domain=domain,
                                  codomain=codomain,
                                  copy=copy,
                                  dtype=dtype,
142
                                  field_type=field_type,
csongor's avatar
csongor committed
143 144 145 146 147 148 149 150
                                  datamodel=datamodel,
                                  **kwargs)
        else:
            self._init_from_array(val=val,
                                  domain=domain,
                                  codomain=codomain,
                                  copy=copy,
                                  dtype=dtype,
151
                                  field_type=field_type,
csongor's avatar
csongor committed
152 153 154
                                  datamodel=datamodel,
                                  **kwargs)

155
    def _init_from_field(self, f, domain, codomain, copy, dtype,
156
                         field_type, datamodel, **kwargs):
csongor's avatar
csongor committed
157 158 159 160 161 162
        # check domain
        if domain is None:
            domain = f.domain

        # check codomain
        if codomain is None:
csongor's avatar
csongor committed
163
            if self._check_codomain(domain, f.codomain):
csongor's avatar
csongor committed
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,
                              copy=copy,
                              dtype=dtype,
                              datamodel=datamodel,
                              **kwargs)

183
    def _init_from_array(self, val, domain, codomain, copy, dtype,
184
                         field_type, datamodel, **kwargs):
csongor's avatar
csongor committed
185
        # check domain
186
        self.domain = self._parse_domain(domain=domain)
187
        self.domain_axes = self._get_axes_tuple(self.domain)
csongor's avatar
csongor committed
188 189 190

        # check codomain
        if codomain is None:
191
            self.codomain = self._build_codomain(domain=self.domain)
192 193 194
        else:
            self.codomain = self._parse_codomain(codomain, self.domain)

195
        self.field_type = self._parse_field_type(field_type)
196
        self.field_type_axes = self._get_axes_tuple(self.field_type)
197 198 199 200 201 202 203

        if dtype is None:
            dtype = self._infer_dtype(domain=self.domain,
                                      dtype=dtype,
                                      field_type=self.field_type)
        self.dtype = dtype

204
        self._comm = getattr(gdi[gc['mpi_module']], gc['default_comm'])
205 206 207 208 209 210 211

        if datamodel in DISTRIBUTION_STRATEGIES['all']:
            self.datamodel = datamodel
        elif isinstance(val, distributed_data_object):
            self.datamodel = val.distribution_strategy
        else:
            self.datamodel = gc['default_datamodel']
csongor's avatar
csongor committed
212 213 214

        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 218 219
                val = self.get_random_values(domain=self.domain,
                                             codomain=self.codomain,
                                             **kwargs)
csongor's avatar
csongor committed
220 221
        self.set_val(new_val=val, copy=copy)

222 223 224 225 226
    def _infer_dtype(self, domain=None, dtype=None, field_type=None):
        dtype_tuple = (np.dtype(gc['default_field_dtype']),)
        if domain is not None:
            dtype_tuple += tuple(np.dtype(sp.dtype) for sp in domain)
        if field_type is not None:
227
            dtype_tuple += tuple(np.dtype(ft.dtype) for ft in field_type)
228

csongor's avatar
csongor committed
229
        dtype = reduce(lambda x, y: np.result_type(x, y), dtype_tuple)
csongor's avatar
csongor committed
230 231
        return dtype

232
    def _get_axes_tuple(self, things_with_shape):
csongor's avatar
csongor committed
233
        i = 0
234 235
        axes_list = []
        for thing in things_with_shape:
csongor's avatar
csongor committed
236
            l = []
237
            for j in range(len(thing.shape)):
csongor's avatar
csongor committed
238 239
                l += [i]
                i += 1
240
            axes_list += [tuple(l)]
241
        return tuple(axes_list)
csongor's avatar
csongor committed
242

243
    def _parse_domain(self, domain):
244 245 246
        if domain is None:
            domain = ()
        elif not isinstance(domain, tuple):
247
            domain = (domain,)
csongor's avatar
csongor committed
248
        for d in domain:
249
            if not isinstance(d, Space):
csongor's avatar
csongor committed
250
                raise TypeError(about._errors.cstring(
251 252
                    "ERROR: Given domain contains something that is not a "
                    "nifty.space."))
csongor's avatar
csongor committed
253 254
        return domain

255 256 257 258 259 260 261
    def _parse_codomain(self, codomain, domain):
        if not isinstance(codomain, tuple):
            codomain = (codomain,)
        if len(domain) != len(codomain):
            raise ValueError(about._errors.cstring(
                "ERROR: domain and codomain do not have the same length."))
        for (cd, d) in zip(codomain, domain):
262
            if not isinstance(cd, Space):
263 264 265 266 267 268 269 270
                raise TypeError(about._errors.cstring(
                    "ERROR: Given codomain contains something that is not a"
                    "nifty.space."))
            if not d.check_codomain(cd):
                raise ValueError(about._errors.cstring(
                    "ERROR: codomain contains a space that is not compatible "
                    "to its domain-counterpart."))
        return codomain
csongor's avatar
csongor committed
271

272 273 274 275 276 277
    def _parse_field_type(self, field_type):
        if field_type is None:
            field_type = ()
        elif not isinstance(field_type, tuple):
            field_type = (field_type,)
        for ft in field_type:
278
            if not isinstance(ft, FieldType):
279
                raise TypeError(about._errors.cstring(
280
                    "ERROR: Given object is not a nifty.FieldType."))
281 282 283
        return field_type

    def _build_codomain(self, domain):
284 285
        codomain = tuple(sp.get_codomain() for sp in domain)
        return codomain
csongor's avatar
csongor committed
286

287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
    def get_random_values(self, **kwargs):
        arg = random.parse_arguments(self, **kwargs)

        if arg is None:
            return self.cast(0)

        # Prepare the empty distributed_data_object
        sample = distributed_data_object(
                                    global_shape=self.shape,
                                    dtype=self.dtype)

        # Case 1: uniform distribution over {-1,+1}/{1,i,-1,-i}
        if arg['random'] == 'pm1':
            sample.apply_generator(lambda s: random.pm1(dtype=self.dtype,
                                                        shape=s))

        # Case 2: normal distribution with zero-mean and a given standard
        #         deviation or variance
        elif arg['random'] == 'gau':
            std = arg['std']
            if np.isscalar(std) or std is None:
                processed_std = std
            else:
                try:
                    processed_std = sample.distributor. \
                        extract_local_data(std)
                except(AttributeError):
                    processed_std = std

            sample.apply_generator(lambda s: random.gau(dtype=self.dtype,
                                                        shape=s,
                                                        mean=arg['mean'],
                                                        std=processed_std))

        # Case 3: uniform distribution
        elif arg['random'] == 'uni':
            sample.apply_generator(lambda s: random.uni(dtype=self.dtype,
                                                        shape=s,
                                                        vmin=arg['vmin'],
                                                        vmax=arg['vmax']))
        return sample
csongor's avatar
csongor committed
328

csongor's avatar
csongor committed
329
    def __len__(self):
330
        return int(self.dim[0])
csongor's avatar
csongor committed
331

332
    def copy(self, domain=None, codomain=None, field_type=None, **kwargs):
csongor's avatar
csongor committed
333
        copied_val = self._unary_operation(self.get_val(), op='copy', **kwargs)
334 335 336
        new_field = self.copy_empty(domain=domain,
                                    codomain=codomain,
                                    field_type=field_type)
337
        new_field.set_val(new_val=copied_val, copy=True)
csongor's avatar
csongor committed
338 339 340 341 342 343 344
        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
345
        # copy domain, codomain and val
csongor's avatar
csongor committed
346 347 348 349 350
        for key, value in self.__dict__.items():
            if key != 'val':
                new_field.__dict__[key] = value
            else:
                new_field.__dict__[key] = \
351
                    self._unary_operation(self.val, op='copy_empty')
csongor's avatar
csongor committed
352 353
        return new_field

354
    def copy_empty(self, domain=None, codomain=None, dtype=None,
355
                   datamodel=None, field_type=None, **kwargs):
csongor's avatar
csongor committed
356 357
        if domain is None:
            domain = self.domain
358

csongor's avatar
csongor committed
359 360
        if codomain is None:
            codomain = self.codomain
361

csongor's avatar
csongor committed
362 363
        if dtype is None:
            dtype = self.dtype
364

csongor's avatar
csongor committed
365 366 367
        if datamodel is None:
            datamodel = self.datamodel

368 369 370 371
        if field_type is None:
            field_type = self.field_type

        _fast_copyable = True
372
        for i in xrange(len(self.domain)):
373 374 375 376 377 378
            if self.domain[i] is not domain[i]:
                _fast_copyable = False
                break
            if self.codomain[i] is not codomain[i]:
                _fast_copyable = False
                break
379 380 381 382 383 384

        for i in xrange(len(self.field_type)):
            if self.field_type[i] is not field_type[i]:
                _fast_copyable = False
                break

385 386
        if (_fast_copyable and dtype == self.dtype and
                datamodel == self.datamodel and kwargs == {}):
csongor's avatar
csongor committed
387 388
            new_field = self._fast_copy_empty()
        else:
389
            new_field = Field(domain=domain, codomain=codomain, dtype=dtype,
390 391
                              datamodel=datamodel, field_type=field_type,
                              **kwargs)
csongor's avatar
csongor committed
392 393 394 395 396 397 398 399 400 401 402 403
        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.

        """
404 405 406 407
        new_val = self.cast(new_val)
        if copy:
            new_val = self.unary_operation(new_val, op='copy')
        self.val = new_val
csongor's avatar
csongor committed
408 409
        return self.val

410 411 412 413 414
    def get_val(self, copy=False):
        if copy:
            return self.val.copy()
        else:
            return self.val
csongor's avatar
csongor committed
415 416

    def __getitem__(self, key):
csongor's avatar
csongor committed
417 418 419 420
        return self.val[key]

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

422 423
    @property
    def shape(self):
424 425 426 427 428 429 430
        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
431

432
        return global_shape
csongor's avatar
csongor committed
433

434 435
    @property
    def dim(self):
csongor's avatar
csongor committed
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
        """
            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.

        """
452
        return reduce(lambda x, y: x * y, self.shape)
csongor's avatar
csongor committed
453

454 455 456 457 458 459
    @property
    def dof(self):
        dof_tuple = ()
        dof_tuple += tuple(sp.dof for sp in self.domain)
        dof_tuple += tuple(ft.dof for ft in self.field_type)
        try:
460
            return reduce(lambda x, y: x * y, dof_tuple)
461 462 463
        except TypeError:
            return ()

csongor's avatar
csongor committed
464 465 466
    def cast(self, x=None, dtype=None):
        if dtype is None:
            dtype = self.dtype
467 468
        else:
            dtype = np.dtype(dtype)
469

csongor's avatar
csongor committed
470
        casted_x = self._cast_to_d2o(x, dtype=dtype)
471 472

        for ind, sp in enumerate(self.domain):
473
            casted_x = sp.complement_cast(casted_x,
474
                                          axis=self.domain_axes[ind])
475 476 477

        for ind, ft in enumerate(self.field_type):
            casted_x = ft.complement_cast(casted_x,
478
                                          axis=self.field_type_axes[ind])
479 480

        return casted_x
csongor's avatar
csongor committed
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504

    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).
        """
505
        if isinstance(x, Field):
csongor's avatar
csongor committed
506 507 508 509 510 511
            x = x.get_val()

        if dtype is None:
            dtype = self.dtype

        if shape is None:
theos's avatar
theos committed
512
            shape = self.shape
csongor's avatar
csongor committed
513 514 515

        # Case 1: x is a distributed_data_object
        if isinstance(x, distributed_data_object):
516 517 518
            if x.comm is not self._comm:
                raise ValueError(about._errors.cstring(
                    "ERROR: comms do not match."))
csongor's avatar
csongor committed
519 520 521 522 523
            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
524
                if x.dim == self.dim:
csongor's avatar
csongor committed
525 526 527 528 529 530 531 532 533 534 535 536
                    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
537
                    return self._cast_to_d2o(temp, dtype=dtype, **kwargs)
csongor's avatar
csongor committed
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571

                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,
theos's avatar
theos committed
572
                                        global_shape=self.shape,
csongor's avatar
csongor committed
573
                                        dtype=dtype,
574 575
                                        distribution_strategy=self.datamodel,
                                        comm=self._comm)
csongor's avatar
csongor committed
576 577 578
            # Cast the d2o
            return self.cast(x, dtype=dtype)

579
    def weight(self, power=1, inplace=False, spaces=None):
csongor's avatar
csongor committed
580 581 582 583 584 585 586 587 588 589
        """
            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).

590
            inplace : bool, *optional*
csongor's avatar
csongor committed
591 592 593 594 595
                Whether to overwrite the field values or not (default: False).

            Returns
            -------
            field   : field, *optional*
596
                If inplace is False, the weighted field is returned.
csongor's avatar
csongor committed
597 598 599
                Otherwise, nothing is returned.

        """
600
        if inplace:
csongor's avatar
csongor committed
601 602 603 604
            new_field = self
        else:
            new_field = self.copy_empty()

605
        new_val = self.get_val(copy=False)
csongor's avatar
csongor committed
606

csongor's avatar
csongor committed
607
        if spaces is None:
theos's avatar
theos committed
608
            spaces = range(len(self.shape))
csongor's avatar
csongor committed
609

610 611 612
        for ind, sp in enumerate(self.domain):
            new_val = sp.calc_weight(new_val,
                                     power=power,
613
                                     axes=self.domain_axes[ind])
614 615

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

618
    def norm(self, q=2):
csongor's avatar
csongor committed
619 620 621 622 623 624 625 626 627 628 629 630 631 632
        """
            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.

        """
633
        if q == 2:
634
            return (self.dot(x=self)) ** (1 / 2)
csongor's avatar
csongor committed
635
        else:
636
            return self.dot(x=self ** (q - 1)) ** (1 / q)
csongor's avatar
csongor committed
637

638
    def dot(self, x=None, bare=False):
csongor's avatar
csongor committed
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660
        """
            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
661
        elif isinstance(x, Field):
662 663
            for ind, sp in enumerate(self.domain):
                assert sp == x.domain[ind]
csongor's avatar
csongor committed
664 665 666

            # whether the domain matches exactly or not:
            # extract the data from x and try to dot with this
667
            return self.dot(x=x.get_val(), bare=bare)
csongor's avatar
csongor committed
668 669 670 671 672

        # Case 3: x is something else
        else:

            # Compute the dot respecting the fact of discrete/continous spaces
673 674 675 676 677
            if not bare:
                y = self.weight(power=1)
            else:
                y = self
            y = y.get_val(copy=False)
csongor's avatar
csongor committed
678

679 680
            # Cast the input in order to cure dtype and shape differences
            x = self.cast(x)
csongor's avatar
csongor committed
681

682
            dotted = x.conjugate() * y
csongor's avatar
csongor committed
683

684
            for ind in range(-1, -len(self.field_type_axes)-1, -1):
685 686
                dotted = self.field_type[ind].dot_contraction(
                            dotted,
687
                            axes=self.field_type_axes[ind])
csongor's avatar
csongor committed
688

689
            for ind in range(-1, -len(self.domain_axes)-1, -1):
690 691
                dotted = self.domain[ind].dot_contraction(
                            dotted,
692
                            axes=self.domain_axes[ind])
693
            return dotted
csongor's avatar
csongor committed
694

695 696
    def vdot(self, *args, **kwargs):
        return self.dot(*args, **kwargs)
csongor's avatar
csongor committed
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 729 730 731 732 733 734
#    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
csongor's avatar
csongor committed
735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750

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

751 752
        new_val = self.get_val(copy=False)
        new_val = self._unary_operation(new_val, op='conjugate')
csongor's avatar
csongor committed
753

754
        work_field.set_val(new_val=new_val, copy=False)
csongor's avatar
csongor committed
755 756 757

        return work_field

758
    def transform(self, spaces=None, **kwargs):
csongor's avatar
csongor committed
759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782
        """
            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.

        """
783 784

        try:
785
            iter(spaces)
786 787
        except TypeError:
            if spaces is None:
788
                spaces = xrange(len(self.domain_axes))
789
            else:
790
                spaces = (spaces, )
csongor's avatar
csongor committed
791

csongor's avatar
csongor committed
792
        new_val = self.get_val()
793 794 795 796
        new_domain = ()
        new_codomain = ()
        for ind in xrange(len(self.domain)):
            if ind in spaces:
797
                sp = self.domain[ind]
798
                cosp = self.codomain[ind]
799
                new_val = sp.calc_transform(new_val,
800 801
                                            codomain=cosp,
                                            axes=self.domain_axes[ind],
802
                                            **kwargs)
803 804 805 806 807
                new_domain += (self.codomain[ind],)
                new_codomain += (self.domain[ind],)
            else:
                new_domain += (self.domain[ind],)
                new_codomain += (self.codomain[ind],)
808 809 810

        return_field = self.copy_empty(domain=new_domain,
                                       codomain=new_codomain)
csongor's avatar
csongor committed
811
        return_field.set_val(new_val=new_val, copy=False)
812

csongor's avatar
csongor committed
813 814
        return return_field

815
    def smooth(self, sigma=0, spaces=None, **kwargs):
csongor's avatar
csongor committed
816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
        """
            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.

        """
840 841 842 843 844 845
        new_field = self.copy_empty()

        try:
            spaces_iterator = iter(spaces)
        except TypeError:
            if spaces is None:
846
                spaces_iterator = xrange(len(self.domain))
847 848
            else:
                spaces_iterator = (spaces, )
csongor's avatar
csongor committed
849

csongor's avatar
csongor committed
850
        new_val = self.get_val()
851 852 853 854
        for ind in spaces_iterator:
            sp = self.domain[ind]
            new_val = sp.calc_smooth(new_val,
                                     sigma=sigma,
855
                                     axes=self.domain_axes[ind],
856
                                     **kwargs)
csongor's avatar
csongor committed
857

858
        new_field.set_val(new_val=new_val, copy=False)
csongor's avatar
csongor committed
859 860 861 862 863 864 865 866 867 868 869 870 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
        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.

        """
900
        if ("codomain" in kwargs):
csongor's avatar
csongor committed
901 902 903
            kwargs.__delitem__("codomain")
            about.warnings.cprint("WARNING: codomain was removed from kwargs.")

904 905 906 907 908 909 910 911
#        power_spectrum = self.get_val()
#        for ind, space in self.domain:
#            power_spectrum = space.calc_smooth(power_spectrum,
#                                               codomain=self.codomain,
#                                               axis=self.axes_list[ind],
#                                               **kwargs)
#
#        return power_spectrum
csongor's avatar
csongor committed
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

    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
939
        any_zero_Q = np.any(map(lambda z: (z == 0), self.get_val()))
csongor's avatar
csongor committed
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 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
        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      = " + \
1032 1033 1034 1035 1036 1037
               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
1038

csongor's avatar
csongor committed
1039 1040 1041 1042 1043 1044
    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
1045 1046
    def all(self, **kwargs):
        return self._unary_operation(self.get_val(), op='all', **kwargs)
csongor's avatar
csongor committed
1047

csongor's avatar
csongor committed
1048 1049 1050
    def any(self, **kwargs):
        return self._unary_operation(self.get_val(), op='any', **kwargs)

csongor's avatar
csongor committed
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
    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
1070
        return self._unary_operation(self.get_val(), op='amin', **kwargs)
csongor's avatar
csongor committed
1071 1072

    def nanmin(self, **kwargs):
csongor's avatar
csongor committed
1073
        return self._unary_operation(self.get_val(), op='nanmin', **kwargs)
csongor's avatar
csongor committed
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093

    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
1094
        return self._unary_operation(self.get_val(), op='amax', **kwargs)
csongor's avatar
csongor committed
1095 1096

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

    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
1113
        return self._unary_operation(self.get_val(), op='median',
csongor's avatar
csongor committed
1114
                                     **kwargs)
csongor's avatar
csongor committed
1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129

    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
1130
        return self._unary_operation(self.get_val(), op='mean',
csongor's avatar
csongor committed
1131
                                     **kwargs)
csongor's avatar
csongor committed
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146

    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
1147
        return self._unary_operation(self.get_val(), op='std',
csongor's avatar
csongor committed
1148
                                     **kwargs)
csongor's avatar
csongor committed
1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163

    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
1164
        return self._unary_operation(self.get_val(), op='var',
csongor's avatar
csongor committed
1165
                                     **kwargs)
csongor's avatar
csongor committed
1166

1167
    def argmin(self, split=False, **kwargs):
csongor's avatar
csongor committed
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
        """
            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
1190
            return self._unary_operation(self.get_val(), op='argmin_nonflat',
csongor's avatar
csongor committed
1191
                                         **kwargs)
csongor's avatar
csongor committed
1192
        else:
csongor's avatar
csongor committed
1193
            return self._unary_operation(self.get_val(), op='argmin',
csongor's avatar
csongor committed
1194
                                         **kwargs)
csongor's avatar
csongor committed
1195

1196
    def argmax(self, split=False, **kwargs):
csongor's avatar
csongor committed
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
        """
            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
1219
            return self._unary_operation(self.get_val(), op='argmax_nonflat',
csongor's avatar
csongor committed
1220
                                         **kwargs)
csongor's avatar
csongor committed
1221
        else:
csongor's avatar
csongor committed
1222
            return self._unary_operation(self.get_val(), op='argmax',
csongor's avatar
csongor committed
1223
                                         **kwargs)
csongor's avatar
csongor committed
1224 1225 1226 1227 1228

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

    def __pos__(self):
        new_field = self.copy_empty()
csongor's avatar
csongor committed
1229
        new_val = self._unary_operation(self.get_val(), op='pos')
csongor's avatar
csongor committed
1230 1231 1232 1233 1234
        new_field.set_val(new_val=new_val)
        return new_field

    def __neg__(self):