nifty_core.py 58.6 KB
Newer Older
1
2
# NIFTY (Numerical Information Field Theory) has been developed at the
# Max-Planck-Institute for Astrophysics.
Marco Selig's avatar
Marco Selig committed
3
##
4
# Copyright (C) 2013 Max-Planck-Society
Marco Selig's avatar
Marco Selig committed
5
##
6
7
# Author: Marco Selig
# Project homepage: <http://www.mpa-garching.mpg.de/ift/nifty/>
Marco Selig's avatar
Marco Selig committed
8
##
9
10
11
12
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
Marco Selig's avatar
Marco Selig committed
13
##
14
15
16
17
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
Marco Selig's avatar
Marco Selig committed
18
##
19
20
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
Marco Selig's avatar
Marco Selig committed
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

"""
    ..                  __   ____   __
    ..                /__/ /   _/ /  /_
    ..      __ ___    __  /  /_  /   _/  __   __
    ..    /   _   | /  / /   _/ /  /   /  / /  /
    ..   /  / /  / /  / /  /   /  /_  /  /_/  /
    ..  /__/ /__/ /__/ /__/    \___/  \___   /  core
    ..                               /______/

    .. The NIFTY project homepage is http://www.mpa-garching.mpg.de/ift/nifty/

    NIFTY [#]_, "Numerical Information Field Theory", is a versatile
    library designed to enable the development of signal inference algorithms
    that operate regardless of the underlying spatial grid and its resolution.
    Its object-oriented framework is written in Python, although it accesses
    libraries written in Cython, C++, and C for efficiency.

    NIFTY offers a toolkit that abstracts discretized representations of
    continuous spaces, fields in these spaces, and operators acting on fields
    into classes. Thereby, the correct normalization of operations on fields is
    taken care of automatically without concerning the user. This allows for an
    abstract formulation and programming of inference algorithms, including
    those derived within information field theory. Thus, NIFTY permits its user
Marco Selig's avatar
Marco Selig committed
45
    to rapidly prototype algorithms in 1D and then apply the developed code in
Marco Selig's avatar
Marco Selig committed
46
47
48
49
50
    higher-dimensional settings of real world problems. The set of spaces on
    which NIFTY operates comprises point sets, n-dimensional regular grids,
    spherical spaces, their harmonic counterparts, and product spaces
    constructed as combinations of those.

51
52
53
54
55
56
57
    References
    ----------
    .. [#] Selig et al., "NIFTY -- Numerical Information Field Theory --
        a versatile Python library for signal inference",
        `A&A, vol. 554, id. A26 <http://dx.doi.org/10.1051/0004-6361/201321236>`_,
        2013; `arXiv:1301.4499 <http://www.arxiv.org/abs/1301.4499>`_

Marco Selig's avatar
Marco Selig committed
58
59
60
61
62
63
    Class & Feature Overview
    ------------------------
    The NIFTY library features three main classes: **spaces** that represent
    certain grids, **fields** that are defined on spaces, and **operators**
    that apply to fields.

64
65
    .. Overview of all (core) classes:
    ..
Marco Selig's avatar
Marco Selig committed
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
    .. - switch
    .. - notification
    .. - _about
    .. - random
    .. - space
    ..     - point_space
    ..     - rg_space
    ..     - lm_space
    ..     - gl_space
    ..     - hp_space
    ..     - nested_space
    .. - field
    .. - operator
    ..     - diagonal_operator
    ..         - power_operator
    ..     - projection_operator
    ..     - vecvec_operator
    ..     - response_operator
    .. - probing
    ..     - trace_probing
    ..     - diagonal_probing

88
89
    Overview of the main classes and functions:

Marco Selig's avatar
Marco Selig committed
90
91
    .. automodule:: nifty

92
93
94
95
96
97
98
99
100
101
102
103
104
105
    - :py:class:`space`
        - :py:class:`point_space`
        - :py:class:`rg_space`
        - :py:class:`lm_space`
        - :py:class:`gl_space`
        - :py:class:`hp_space`
        - :py:class:`nested_space`
    - :py:class:`field`
    - :py:class:`operator`
        - :py:class:`diagonal_operator`
            - :py:class:`power_operator`
        - :py:class:`projection_operator`
        - :py:class:`vecvec_operator`
        - :py:class:`response_operator`
Marco Selig's avatar
Marco Selig committed
106

107
        .. currentmodule:: nifty.nifty_tools
Marco Selig's avatar
Marco Selig committed
108

109
110
        - :py:class:`invertible_operator`
        - :py:class:`propagator_operator`
Marco Selig's avatar
Marco Selig committed
111

112
        .. currentmodule:: nifty.nifty_explicit
Marco Selig's avatar
Marco Selig committed
113

114
        - :py:class:`explicit_operator`
Marco Selig's avatar
Marco Selig committed
115

116
    .. automodule:: nifty
Marco Selig's avatar
Marco Selig committed
117

118
119
120
    - :py:class:`probing`
        - :py:class:`trace_probing`
        - :py:class:`diagonal_probing`
Marco Selig's avatar
Marco Selig committed
121

122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
        .. currentmodule:: nifty.nifty_explicit

        - :py:class:`explicit_probing`

    .. currentmodule:: nifty.nifty_tools

    - :py:class:`conjugate_gradient`
    - :py:class:`steepest_descent`

    .. currentmodule:: nifty.nifty_explicit

    - :py:func:`explicify`

    .. currentmodule:: nifty.nifty_power

    - :py:func:`weight_power`,
      :py:func:`smooth_power`,
      :py:func:`infer_power`,
      :py:func:`interpolate_power`
Marco Selig's avatar
Marco Selig committed
141
142
143
144

"""
from __future__ import division
import numpy as np
Marco Selig's avatar
Marco Selig committed
145
import pylab as pl
146

147
148
149
from d2o import distributed_data_object,\
                STRATEGIES as DISTRIBUTION_STRATEGIES

150
from nifty_paradict import space_paradict,\
151
    point_space_paradict
Ultimanet's avatar
Ultimanet committed
152

csongor's avatar
csongor committed
153
from nifty.config import about
154

Ultimanet's avatar
Ultimanet committed
155
from nifty_random import random
Marco Selig's avatar
Marco Selig committed
156

157
POINT_DISTRIBUTION_STRATEGIES = DISTRIBUTION_STRATEGIES['global']
Marco Selig's avatar
Marco Selig committed
158

Ultimanet's avatar
Ultimanet committed
159
160

class space(object):
Marco Selig's avatar
Marco Selig committed
161
    """
Ultimanet's avatar
Ultimanet committed
162
163
164
165
166
167
168
        ..     _______   ______    ____ __   _______   _______
        ..   /  _____/ /   _   | /   _   / /   ____/ /   __  /
        ..  /_____  / /  /_/  / /  /_/  / /  /____  /  /____/
        .. /_______/ /   ____/  \______|  \______/  \______/  class
        ..          /__/

        NIFTY base class for spaces and their discretizations.
Marco Selig's avatar
Marco Selig committed
169

Ultimanet's avatar
Ultimanet committed
170
171
172
        The base NIFTY space class is an abstract class from which other
        specific space subclasses, including those preimplemented in NIFTY
        (e.g. the regular grid class) must be derived.
Marco Selig's avatar
Marco Selig committed
173
174
175

        Parameters
        ----------
176
        dtype : numpy.dtype, *optional*
Ultimanet's avatar
Ultimanet committed
177
178
            Data type of the field values for a field defined on this space
            (default: numpy.float64).
179
        datamodel :
Marco Selig's avatar
Marco Selig committed
180
181
182

        See Also
        --------
Ultimanet's avatar
Ultimanet committed
183
184
185
186
187
188
189
190
        point_space :  A class for unstructured lists of numbers.
        rg_space : A class for regular cartesian grids in arbitrary dimensions.
        hp_space : A class for the HEALPix discretization of the sphere
            [#]_.
        gl_space : A class for the Gauss-Legendre discretization of the sphere
            [#]_.
        lm_space : A class for spherical harmonic components.
        nested_space : A class for product spaces.
Marco Selig's avatar
Marco Selig committed
191

Ultimanet's avatar
Ultimanet committed
192
193
194
195
196
197
198
199
        References
        ----------
        .. [#] K.M. Gorski et al., 2005, "HEALPix: A Framework for
               High-Resolution Discretization and Fast Analysis of Data
               Distributed on the Sphere", *ApJ* 622..759G.
        .. [#] M. Reinecke and D. Sverre Seljebotn, 2013, "Libsharp - spherical
               harmonic transforms revisited";
               `arXiv:1303.4945 <http://www.arxiv.org/abs/1303.4945>`_
Marco Selig's avatar
Marco Selig committed
200
201
202

        Attributes
        ----------
Ultimanet's avatar
Ultimanet committed
203
        para : {single object, list of objects}
204
205
206
            This is a freeform list of parameters that derivatives of the space
            class can use.
        dtype : numpy.dtype
Ultimanet's avatar
Ultimanet committed
207
208
209
210
211
212
213
            Data type of the field values for a field defined on this space.
        discrete : bool
            Whether the space is inherently discrete (true) or a discretization
            of a continuous space (false).
        vol : numpy.ndarray
            An array of pixel volumes, only one component if the pixels all
            have the same volume.
Marco Selig's avatar
Marco Selig committed
214
    """
215

Ultima's avatar
Ultima committed
216
    def __init__(self):
Marco Selig's avatar
Marco Selig committed
217
        """
Ultimanet's avatar
Ultimanet committed
218
            Sets the attributes for a space class instance.
Marco Selig's avatar
Marco Selig committed
219
220
221

            Parameters
            ----------
222
            dtype : numpy.dtype, *optional*
Ultimanet's avatar
Ultimanet committed
223
224
                Data type of the field values for a field defined on this space
                (default: numpy.float64).
225
            datamodel :
Marco Selig's avatar
Marco Selig committed
226

Ultimanet's avatar
Ultimanet committed
227
228
229
            Returns
            -------
            None
Marco Selig's avatar
Marco Selig committed
230
        """
231
        self.paradict = space_paradict()
232

Ultimanet's avatar
Ultimanet committed
233
234
235
    @property
    def para(self):
        return self.paradict['default']
236

Ultimanet's avatar
Ultimanet committed
237
238
239
    @para.setter
    def para(self, x):
        self.paradict['default'] = x
Marco Selig's avatar
Marco Selig committed
240

Ultima's avatar
Ultima committed
241
242
243
    def __hash__(self):
        return hash(())

244
    def _identifier(self):
Marco Selig's avatar
Marco Selig committed
245
        """
246
247
248
        _identiftier returns an object which contains all information needed
        to uniquely idetnify a space. It returns a (immutable) tuple which
        therefore can be compared.
249
        """
250
251
252
253
254
255
256
257
258
259
260
261
        return tuple(sorted(vars(self).items()))

    def __eq__(self, x):
        if isinstance(x, type(self)):
            return self._identifier() == x._identifier()
        else:
            return False

    def __ne__(self, x):
        return not self.__eq__(x)

    def __len__(self):
ultimanet's avatar
ultimanet committed
262
        return int(self.get_dim())
Marco Selig's avatar
Marco Selig committed
263

264
    def copy(self):
265
        return space(para=self.para,
266
                     dtype=self.dtype)
Marco Selig's avatar
Marco Selig committed
267

Ultimanet's avatar
Ultimanet committed
268
    def getitem(self, data, key):
269
        raise NotImplementedError(about._errors.cstring(
Ultimanet's avatar
Ultimanet committed
270
            "ERROR: no generic instance method 'getitem'."))
Marco Selig's avatar
Marco Selig committed
271

csongor's avatar
csongor committed
272
    def setitem(self, data, update, key):
273
        raise NotImplementedError(about._errors.cstring(
Ultimanet's avatar
Ultimanet committed
274
            "ERROR: no generic instance method 'getitem'."))
275

Ultimanet's avatar
Ultimanet committed
276
    def apply_scalar_function(self, x, function, inplace=False):
277
        raise NotImplementedError(about._errors.cstring(
Ultimanet's avatar
Ultimanet committed
278
            "ERROR: no generic instance method 'apply_scalar_function'."))
Marco Selig's avatar
Marco Selig committed
279

Ultimanet's avatar
Ultimanet committed
280
    def unary_operation(self, x, op=None):
281
        raise NotImplementedError(about._errors.cstring(
Ultimanet's avatar
Ultimanet committed
282
            "ERROR: no generic instance method 'unary_operation'."))
283

Ultimanet's avatar
Ultimanet committed
284
    def binary_operation(self, x, y, op=None):
285
        raise NotImplementedError(about._errors.cstring(
Ultimanet's avatar
Ultimanet committed
286
            "ERROR: no generic instance method 'binary_operation'."))
Marco Selig's avatar
Marco Selig committed
287

288
    def get_shape(self):
289
        raise NotImplementedError(about._errors.cstring(
Ultimanet's avatar
Ultimanet committed
290
            "ERROR: no generic instance method 'shape'."))
Marco Selig's avatar
Marco Selig committed
291

ultimanet's avatar
ultimanet committed
292
    def get_dim(self):
Marco Selig's avatar
Marco Selig committed
293
        """
Ultimanet's avatar
Ultimanet committed
294
            Computes the dimension of the space, i.e.\  the number of pixels.
Marco Selig's avatar
Marco Selig committed
295
296
297

            Parameters
            ----------
Ultimanet's avatar
Ultimanet committed
298
299
300
            split : bool, *optional*
                Whether to return the dimension split up, i.e. the numbers of
                pixels in each direction, or not (default: False).
Marco Selig's avatar
Marco Selig committed
301

Ultimanet's avatar
Ultimanet committed
302
303
304
305
            Returns
            -------
            dim : {int, numpy.ndarray}
                Dimension(s) of the space.
Marco Selig's avatar
Marco Selig committed
306
        """
307
        raise NotImplementedError(about._errors.cstring(
308
            "ERROR: no generic instance method 'dim'."))
Marco Selig's avatar
Marco Selig committed
309

310
    def get_dof(self):
Marco Selig's avatar
Marco Selig committed
311
        """
Ultimanet's avatar
Ultimanet committed
312
            Computes the number of degrees of freedom of the space.
Marco Selig's avatar
Marco Selig committed
313
314
315

            Returns
            -------
Ultimanet's avatar
Ultimanet committed
316
317
            dof : int
                Number of degrees of freedom of the space.
Marco Selig's avatar
Marco Selig committed
318
        """
319
        raise NotImplementedError(about._errors.cstring(
320
            "ERROR: no generic instance method 'dof'."))
Marco Selig's avatar
Marco Selig committed
321

322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
    def cast(self, x, verbose=False):
        """
            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).
        """
        raise NotImplementedError(about._errors.cstring(
            "ERROR: no generic instance method 'cast'."))
Marco Selig's avatar
Marco Selig committed
347

348
    # TODO: Move enforce power into power_indices class
349
    def enforce_power(self, spec, **kwargs):
Marco Selig's avatar
Marco Selig committed
350
        """
Ultimanet's avatar
Ultimanet committed
351
            Provides a valid power spectrum array from a given object.
Marco Selig's avatar
Marco Selig committed
352
353
354

            Parameters
            ----------
Ultimanet's avatar
Ultimanet committed
355
356
357
358
            spec : {scalar, list, numpy.ndarray, nifty.field, function}
                Fiducial power spectrum from which a valid power spectrum is to
                be calculated. Scalars are interpreted as constant power
                spectra.
Marco Selig's avatar
Marco Selig committed
359
360
361

            Returns
            -------
Ultimanet's avatar
Ultimanet committed
362
363
364
365
366
367
368
369
370
371
372
373
            spec : numpy.ndarray
                Valid power spectrum.

            Other parameters
            ----------------
            size : int, *optional*
                Number of bands the power spectrum shall have (default: None).
            kindex : numpy.ndarray, *optional*
                Scale of each band.
            codomain : nifty.space, *optional*
                A compatible codomain for power indexing (default: None).
            log : bool, *optional*
374
375
                Flag specifying if the spectral binning is performed on
                logarithmic
Ultimanet's avatar
Ultimanet committed
376
377
378
379
                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*
380
381
                Number of used spectral bins; if given `log` is set to
                ``False``;
Ultimanet's avatar
Ultimanet committed
382
383
384
385
386
                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
387
388
                (default: None).
            vmin : {scalar, list, ndarray, field}, *optional*
Ultimanet's avatar
Ultimanet committed
389
390
                Lower limit of the uniform distribution if ``random == "uni"``
                (default: 0).
Marco Selig's avatar
Marco Selig committed
391
392

        """
393
        raise NotImplementedError(about._errors.cstring(
394
            "ERROR: no generic instance method 'enforce_power'."))
Marco Selig's avatar
Marco Selig committed
395

396
    def check_codomain(self, codomain):
Marco Selig's avatar
Marco Selig committed
397
        """
398
            Checks whether a given codomain is compatible to the space or not.
Marco Selig's avatar
Marco Selig committed
399
400
401

            Parameters
            ----------
402
403
            codomain : nifty.space
                Space to be checked for compatibility.
Marco Selig's avatar
Marco Selig committed
404
405
406

            Returns
            -------
407
408
            check : bool
                Whether or not the given codomain is compatible to the space.
Marco Selig's avatar
Marco Selig committed
409
        """
Ultima's avatar
Ultima committed
410
411
412
413
414
        if codomain is None:
            return False
        else:
            raise NotImplementedError(about._errors.cstring(
                "ERROR: no generic instance method 'check_codomain'."))
Marco Selig's avatar
Marco Selig committed
415

416
    def get_codomain(self, **kwargs):
Marco Selig's avatar
Marco Selig committed
417
        """
418
419
420
            Generates a compatible codomain to which transformations are
            reasonable, usually either the position basis or the basis of
            harmonic eigenmodes.
Marco Selig's avatar
Marco Selig committed
421
422
423

            Parameters
            ----------
424
425
426
427
            coname : string, *optional*
                String specifying a desired codomain (default: None).
            cozerocenter : {bool, numpy.ndarray}, *optional*
                Whether or not the grid is zerocentered for each axis or not
Ultimanet's avatar
Ultimanet committed
428
                (default: None).
429
430
431
432
            conest : list, *optional*
                List of nested spaces of the codomain (default: None).
            coorder : list, *optional*
                Permutation of the list of nested spaces (default: None).
Marco Selig's avatar
Marco Selig committed
433
434
435

            Returns
            -------
436
437
            codomain : nifty.space
                A compatible codomain.
Ultimanet's avatar
Ultimanet committed
438
        """
439
        raise NotImplementedError(about._errors.cstring(
440
            "ERROR: no generic instance method 'get_codomain'."))
Marco Selig's avatar
Marco Selig committed
441

442
    def get_random_values(self, **kwargs):
Marco Selig's avatar
Marco Selig committed
443
        """
Ultimanet's avatar
Ultimanet committed
444
445
            Generates random field values according to the specifications given
            by the parameters.
Marco Selig's avatar
Marco Selig committed
446

Ultimanet's avatar
Ultimanet committed
447
448
449
450
451
452
453
            Returns
            -------
            x : numpy.ndarray
                Valid field values.

            Other parameters
            ----------------
Marco Selig's avatar
Marco Selig committed
454
            random : string, *optional*
Ultimanet's avatar
Ultimanet committed
455
456
457
                Specifies the probability distribution from which the random
                numbers are to be drawn.
                Supported distributions are:
Marco Selig's avatar
Marco Selig committed
458
459

                - "pm1" (uniform distribution over {+1,-1} or {+1,+i,-1,-i}
460
461
                - "gau" (normal distribution with zero-mean and a given
                    standard deviation or variance)
Marco Selig's avatar
Marco Selig committed
462
463
464
465
                - "syn" (synthesizes from a given power spectrum)
                - "uni" (uniform distribution over [vmin,vmax[)

                (default: None).
Ultimanet's avatar
Ultimanet committed
466
467
468
469
470
            dev : float, *optional*
                Standard deviation (default: 1).
            var : float, *optional*
                Variance, overriding `dev` if both are specified
                (default: 1).
471
472
            spec : {scalar, list, numpy.ndarray, nifty.field, function},
                    *optional*
Ultimanet's avatar
Ultimanet committed
473
                Power spectrum (default: 1).
474
475
476
477
            pindex : numpy.ndarray, *optional*
                Indexing array giving the power spectrum index of each band
                (default: None).
            kindex : numpy.ndarray, *optional*
Ultimanet's avatar
Ultimanet committed
478
                Scale of each band (default: None).
479
            codomain : nifty.space, *optional*
Ultimanet's avatar
Ultimanet committed
480
                A compatible codomain with power indices (default: None).
481
            log : bool, *optional*
482
483
                Flag specifying if the spectral binning is performed on
                logarithmic
484
485
486
487
                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*
488
489
                Number of used spectral bins; if given `log` is set to
                ``False``;
490
491
492
493
494
                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
495
496
                (default: None).
            vmin : {scalar, list, ndarray, field}, *optional*
497
498
                Lower limit of the uniform distribution if ``random == "uni"``
                (default: 0).
Ultimanet's avatar
Ultimanet committed
499
500
501
502
            vmin : float, *optional*
                Lower limit for a uniform distribution (default: 0).
            vmax : float, *optional*
                Upper limit for a uniform distribution (default: 1).
Marco Selig's avatar
Marco Selig committed
503
        """
504
505
        raise NotImplementedError(about._errors.cstring(
            "ERROR: no generic instance method 'get_random_values'."))
Marco Selig's avatar
Marco Selig committed
506

507
    def calc_weight(self, x, power=1):
Marco Selig's avatar
Marco Selig committed
508
        """
509
510
            Weights a given array of field values with the pixel volumes (not
            the meta volumes) to a given power.
Marco Selig's avatar
Marco Selig committed
511
512
513

            Parameters
            ----------
514
515
516
517
            x : numpy.ndarray
                Array to be weighted.
            power : float, *optional*
                Power of the pixel volumes to be used (default: 1).
Marco Selig's avatar
Marco Selig committed
518
519
520

            Returns
            -------
521
522
            y : numpy.ndarray
                Weighted array.
Marco Selig's avatar
Marco Selig committed
523
        """
524
        raise NotImplementedError(about._errors.cstring(
525
            "ERROR: no generic instance method 'calc_weight'."))
Marco Selig's avatar
Marco Selig committed
526

527
528
529
    def get_weight(self, power=1):
        raise NotImplementedError(about._errors.cstring(
            "ERROR: no generic instance method 'get_weight'."))
Marco Selig's avatar
Marco Selig committed
530

Ultima's avatar
Ultima committed
531
532
533
534
    def calc_norm(self, x, q):
        raise NotImplementedError(about._errors.cstring(
            "ERROR: no generic instance method 'norm'."))

535
    def calc_dot(self, x, y):
Marco Selig's avatar
Marco Selig committed
536
        """
537
538
            Computes the discrete inner product of two given arrays of field
            values.
Marco Selig's avatar
Marco Selig committed
539
540
541

            Parameters
            ----------
542
543
544
545
            x : numpy.ndarray
                First array
            y : numpy.ndarray
                Second array
Marco Selig's avatar
Marco Selig committed
546
547
548

            Returns
            -------
549
550
            dot : scalar
                Inner product of the two arrays.
Ultimanet's avatar
Ultimanet committed
551
        """
552
        raise NotImplementedError(about._errors.cstring(
553
            "ERROR: no generic instance method 'dot'."))
Marco Selig's avatar
Marco Selig committed
554

555
    def calc_transform(self, x, codomain=None, **kwargs):
Marco Selig's avatar
Marco Selig committed
556
        """
557
            Computes the transform of a given array of field values.
Marco Selig's avatar
Marco Selig committed
558

Ultimanet's avatar
Ultimanet committed
559
560
            Parameters
            ----------
561
562
563
564
565
            x : numpy.ndarray
                Array to be transformed.
            codomain : nifty.space, *optional*
                codomain space to which the transformation shall map
                (default: self).
Marco Selig's avatar
Marco Selig committed
566
567
568

            Returns
            -------
Ultimanet's avatar
Ultimanet committed
569
570
            Tx : numpy.ndarray
                Transformed array
571

Ultimanet's avatar
Ultimanet committed
572
573
574
575
            Other parameters
            ----------------
            iter : int, *optional*
                Number of iterations performed in specific transformations.
576
        """
577
578
        raise NotImplementedError(about._errors.cstring(
            "ERROR: no generic instance method 'calc_transform'."))
Marco Selig's avatar
Marco Selig committed
579

580
    def calc_smooth(self, x, sigma=0, **kwargs):
Marco Selig's avatar
Marco Selig committed
581
        """
Ultimanet's avatar
Ultimanet committed
582
583
            Smoothes an array of field values by convolution with a Gaussian
            kernel.
Marco Selig's avatar
Marco Selig committed
584
585
586

            Parameters
            ----------
Ultimanet's avatar
Ultimanet committed
587
588
589
590
591
            x : numpy.ndarray
                Array of field values to be smoothed.
            sigma : float, *optional*
                Standard deviation of the Gaussian kernel, specified in units
                of length in position space (default: 0).
Marco Selig's avatar
Marco Selig committed
592
593
594

            Returns
            -------
Ultimanet's avatar
Ultimanet committed
595
596
            Gx : numpy.ndarray
                Smoothed array.
Marco Selig's avatar
Marco Selig committed
597

Ultimanet's avatar
Ultimanet committed
598
599
600
601
            Other parameters
            ----------------
            iter : int, *optional*
                Number of iterations (default: 0).
Marco Selig's avatar
Marco Selig committed
602
        """
603
604
        raise NotImplementedError(about._errors.cstring(
            "ERROR: no generic instance method 'calc_smooth'."))
Marco Selig's avatar
Marco Selig committed
605

606
    def calc_power(self, x, **kwargs):
Marco Selig's avatar
Marco Selig committed
607
        """
Ultimanet's avatar
Ultimanet committed
608
            Computes the power of an array of field values.
Marco Selig's avatar
Marco Selig committed
609
610
611

            Parameters
            ----------
Ultimanet's avatar
Ultimanet committed
612
613
614
            x : numpy.ndarray
                Array containing the field values of which the power is to be
                calculated.
Marco Selig's avatar
Marco Selig committed
615
616
617
618

            Returns
            -------
            spec : numpy.ndarray
Ultimanet's avatar
Ultimanet committed
619
                Power contained in the input array.
Marco Selig's avatar
Marco Selig committed
620
621
622

            Other parameters
            ----------------
Ultimanet's avatar
Ultimanet committed
623
624
625
            pindex : numpy.ndarray, *optional*
                Indexing array assigning the input array components to
                components of the power spectrum (default: None).
626
            kindex : numpy.ndarray, *optional*
Ultimanet's avatar
Ultimanet committed
627
628
629
630
                Scale corresponding to each band in the power spectrum
                (default: None).
            rho : numpy.ndarray, *optional*
                Number of degrees of freedom per band (default: None).
631
632
633
            codomain : nifty.space, *optional*
                A compatible codomain for power indexing (default: None).
            log : bool, *optional*
634
635
                Flag specifying if the spectral binning is performed on
                logarithmic
636
637
638
639
                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*
640
641
                Number of used spectral bins; if given `log` is set to
                ``False``;
642
643
644
645
646
                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
647
648
                (default: None).
            vmin : {scalar, list, ndarray, field}, *optional*
649
650
                Lower limit of the uniform distribution if ``random == "uni"``
                (default: 0).
651

Marco Selig's avatar
Marco Selig committed
652
        """
653
654
        raise NotImplementedError(about._errors.cstring(
            "ERROR: no generic instance method 'calc_power'."))
Marco Selig's avatar
Marco Selig committed
655

656
657
658
659
660
661
662
    def calc_real_Q(self, x):
        raise NotImplementedError(about._errors.cstring(
            "ERROR: no generic instance method 'calc_real_Q'."))

    def calc_bincount(self, x, weights=None, minlength=None):
        raise NotImplementedError(about._errors.cstring(
            "ERROR: no generic instance method 'calc_bincount'."))
Marco Selig's avatar
Marco Selig committed
663

664
    def get_plot(self, x, **kwargs):
Marco Selig's avatar
Marco Selig committed
665
        """
Ultimanet's avatar
Ultimanet committed
666
667
            Creates a plot of field values according to the specifications
            given by the parameters.
668
669
670

            Parameters
            ----------
Ultimanet's avatar
Ultimanet committed
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
            x : numpy.ndarray
                Array containing the field values.

            Returns
            -------
            None

            Other parameters
            ----------------
            title : string, *optional*
                Title of the plot (default: "").
            vmin : float, *optional*
                Minimum value to be displayed (default: ``min(x)``).
            vmax : float, *optional*
                Maximum value to be displayed (default: ``max(x)``).
            power : bool, *optional*
                Whether to plot the power contained in the field or the field
                values themselves (default: False).
            unit : string, *optional*
                Unit of the field values (default: "").
            norm : string, *optional*
                Scaling of the field values before plotting (default: None).
            cmap : matplotlib.colors.LinearSegmentedColormap, *optional*
                Color map to be used for two-dimensional plots (default: None).
            cbar : bool, *optional*
                Whether to show the color bar or not (default: True).
            other : {single object, tuple of objects}, *optional*
                Object or tuple of objects to be added, where objects can be
                scalars, arrays, or fields (default: None).
            legend : bool, *optional*
                Whether to show the legend or not (default: False).
            mono : bool, *optional*
                Whether to plot the monopole 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 : {float, numpy.ndarray, nifty.field}, *optional*
                Object indicating some confidence interval to be plotted
                (default: None).
            kindex : numpy.ndarray, *optional*
                Scale corresponding to each band in the power spectrum
                (default: None).
            codomain : nifty.space, *optional*
                A compatible codomain for power indexing (default: None).
            log : bool, *optional*
716
717
                Flag specifying if the spectral binning is performed on
                logarithmic
718
719
720
                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).
Ultimanet's avatar
Ultimanet committed
721
            nbin : integer, *optional*
722
723
                Number of used spectral bins; if given `log` is set to
                ``False``;
724
                integers below the minimum of 3 induce an automatic setting;
725
                by default no binning is done (default: None).
Ultimanet's avatar
Ultimanet committed
726
            binbounds : {list, array}, *optional*
727
728
                User specific inner boundaries of the bins, which are preferred
                over the above parameters; by default no binning is done
729
730
                (default: None).
            vmin : {scalar, list, ndarray, field}, *optional*
Ultimanet's avatar
Ultimanet committed
731
732
733
734
                Lower limit of the uniform distribution if ``random == "uni"``
                (default: 0).
            iter : int, *optional*
                Number of iterations (default: 0).
Marco Selig's avatar
Marco Selig committed
735
736

        """
737
738
        raise NotImplementedError(about._errors.cstring(
            "ERROR: no generic instance method 'get_plot'."))
Marco Selig's avatar
Marco Selig committed
739

Ultimanet's avatar
Ultimanet committed
740
    def __repr__(self):
Ultima's avatar
Ultima committed
741
742
743
744
        string = ""
        string += str(type(self)) + "\n"
        string += "paradict: " + str(self.paradict) + "\n"
        return string
Marco Selig's avatar
Marco Selig committed
745

Ultimanet's avatar
Ultimanet committed
746
    def __str__(self):
Ultima's avatar
Ultima committed
747
        return self.__repr__()
Marco Selig's avatar
Marco Selig committed
748
749


Ultimanet's avatar
Ultimanet committed
750
class point_space(space):
Marco Selig's avatar
Marco Selig committed
751
    """
Ultimanet's avatar
Ultimanet committed
752
753
754
755
756
757
758
        ..                            __             __
        ..                          /__/           /  /_
        ..      ______    ______    __   __ ___   /   _/
        ..    /   _   | /   _   | /  / /   _   | /  /
        ..   /  /_/  / /  /_/  / /  / /  / /  / /  /_
        ..  /   ____/  \______/ /__/ /__/ /__/  \___/  space class
        .. /__/
Marco Selig's avatar
Marco Selig committed
759

Ultimanet's avatar
Ultimanet committed
760
        NIFTY subclass for unstructured spaces.
Marco Selig's avatar
Marco Selig committed
761

Ultimanet's avatar
Ultimanet committed
762
763
        Unstructured spaces are lists of values without any geometrical
        information.
Marco Selig's avatar
Marco Selig committed
764
765
766

        Parameters
        ----------
Ultimanet's avatar
Ultimanet committed
767
768
        num : int
            Number of points.
769
        dtype : numpy.dtype, *optional*
Ultimanet's avatar
Ultimanet committed
770
            Data type of the field values (default: None).
Marco Selig's avatar
Marco Selig committed
771

Ultimanet's avatar
Ultimanet committed
772
        Attributes
Marco Selig's avatar
Marco Selig committed
773
        ----------
Ultimanet's avatar
Ultimanet committed
774
775
        para : numpy.ndarray
            Array containing the number of points.
776
        dtype : numpy.dtype
Ultimanet's avatar
Ultimanet committed
777
778
779
780
781
782
            Data type of the field values.
        discrete : bool
            Parameter captioning the fact that a :py:class:`point_space` is
            always discrete.
        vol : numpy.ndarray
            Pixel volume of the :py:class:`point_space`, which is always 1.
Marco Selig's avatar
Marco Selig committed
783
    """
784

csongor's avatar
csongor committed
785
    def __init__(self, num, dtype=np.dtype('float')):
Ultimanet's avatar
Ultimanet committed
786
787
        """
            Sets the attributes for a point_space class instance.
Marco Selig's avatar
Marco Selig committed
788

Ultimanet's avatar
Ultimanet committed
789
790
791
792
            Parameters
            ----------
            num : int
                Number of points.
793
            dtype : numpy.dtype, *optional*
Ultimanet's avatar
Ultimanet committed
794
                Data type of the field values (default: numpy.float64).
Marco Selig's avatar
Marco Selig committed
795

Ultimanet's avatar
Ultimanet committed
796
797
798
799
            Returns
            -------
            None.
        """
Ultima's avatar
Ultima committed
800
        self._cache_dict = {'check_codomain': {}}
801
802
        self.paradict = point_space_paradict(num=num)

803
804
        # parse dtype
        dtype = np.dtype(dtype)
Ultima's avatar
Ultima committed
805
806
807
808
809
810
811
812
813
        if dtype not in [np.dtype('bool'),
                         np.dtype('int16'),
                         np.dtype('int32'),
                         np.dtype('int64'),
                         np.dtype('float32'),
                         np.dtype('float64'),
                         np.dtype('complex64'),
                         np.dtype('complex128')]:
            raise ValueError(about._errors.cstring(
814
                             "WARNING: incompatible dtype: " + str(dtype)))
Ultima's avatar
Ultima committed
815
        self.dtype = dtype
816

Ultimanet's avatar
Ultimanet committed
817
        self.discrete = True
Ultima's avatar
Ultima committed
818
#        self.harmonic = False
819
        self.distances = (np.float(1),)
Marco Selig's avatar
Marco Selig committed
820

Ultimanet's avatar
Ultimanet committed
821
822
823
824
    @property
    def para(self):
        temp = np.array([self.paradict['num']], dtype=int)
        return temp
825

Ultimanet's avatar
Ultimanet committed
826
827
    @para.setter
    def para(self, x):
Ultima's avatar
Ultima committed
828
        self.paradict['num'] = x[0]
829

Ultima's avatar
Ultima committed
830
831
832
833
    def __hash__(self):
        # Extract the identifying parts from the vars(self) dict.
        result_hash = 0
        for (key, item) in vars(self).items():
Ultima's avatar
Ultima committed
834
835
            if key in ['_cache_dict']:
                continue
Ultima's avatar
Ultima committed
836
837
838
            result_hash ^= item.__hash__() * hash(key)
        return result_hash

839
840
841
842
843
    def _identifier(self):
        # Extract the identifying parts from the vars(self) dict.
        temp = [(ii[0],
                 ((lambda x: x[1].__hash__() if x[0] == 'comm' else x)(ii)))
                for ii in vars(self).iteritems()
Ultima's avatar
Ultima committed
844
                if ii[0] not in ['_cache_dict']
845
846
847
848
                ]
        # Return the sorted identifiers as a tuple.
        return tuple(sorted(temp))

849
    def copy(self):
850
        return point_space(num=self.paradict['num'],
csongor's avatar
csongor committed
851
                           dtype=self.dtype)
852

Ultimanet's avatar
Ultimanet committed
853
854
    def getitem(self, data, key):
        return data[key]
Marco Selig's avatar
Marco Selig committed
855

Ultimanet's avatar
Ultimanet committed
856
    def setitem(self, data, update, key):
857
        data[key] = update
Marco Selig's avatar
Marco Selig committed
858

Ultimanet's avatar
Ultimanet committed
859
    def apply_scalar_function(self, x, function, inplace=False):
860
        return x.apply_scalar_function(function, inplace=inplace)
861

862
    def unary_operation(self, x, op='None', axis=None, **kwargs):
Ultimanet's avatar
Ultimanet committed
863
864
865
        """
        x must be a numpy array which is compatible with the space!
        Valid operations are
866

Ultimanet's avatar
Ultimanet committed
867
        """
868
869
870
871
872
        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'),
873
874
875
876
877
878
879
880
                       '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),
881
882
                       'argmin_nonflat': lambda y: getattr(y, 'argmin_nonflat')(
                           axis=axis),
csongor's avatar
csongor committed
883
                       'argmin': lambda y: getattr(y, 'argmin')(axis=axis),
884
885
                       'argmax_nonflat': lambda y: getattr(y, 'argmax_nonflat')(
                           axis=axis),
csongor's avatar
csongor committed
886
                       'argmax': lambda y: getattr(y, 'argmax')(axis=axis),
887
                       'conjugate': lambda y: getattr(y, 'conjugate')(),
888
889
                       'sum': lambda y: getattr(y, 'sum')(axis=axis),
                       'prod': lambda y: getattr(y, 'prod')(axis=axis),
890
891
892
893
894
895
896
                       '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')(),
897
898
                       'all': lambda y: getattr(y, 'all')(axis=axis),
                       'any': lambda y: getattr(y, 'any')(axis=axis),
899
                       'None': lambda y: y}
Marco Selig's avatar
Marco Selig committed
900

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

Ultimanet's avatar
Ultimanet committed
903
    def binary_operation(self, x, y, op='None', cast=0):
904

Ultima's avatar
Ultima committed
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
        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}
927

Ultimanet's avatar
Ultimanet committed
928
929
930
        if (cast & 1) != 0:
            x = self.cast(x)
        if (cast & 2) != 0:
931
932
            y = self.cast(y)

Ultimanet's avatar
Ultimanet committed
933
        return translation[op](x)(y)
Marco Selig's avatar
Marco Selig committed
934

935
    def get_shape(self):
936
        return (self.paradict['num'],)
Marco Selig's avatar
Marco Selig committed
937

Ultima's avatar
Ultima committed
938
    def get_dim(self):
Ultimanet's avatar
Ultimanet committed
939
940
        """
            Computes the dimension of the space, i.e.\  the number of points.
Marco Selig's avatar
Marco Selig committed
941

Ultimanet's avatar
Ultimanet committed
942
943
944
945
946
            Parameters
            ----------
            split : bool, *optional*
                Whether to return the dimension as an array with one component
                or as a scalar (default: False).
Marco Selig's avatar
Marco Selig committed
947

Ultimanet's avatar
Ultimanet committed
948
949
950
951
952
            Returns
            -------
            dim : {int, numpy.ndarray}
                Dimension(s) of the space.
        """
Ultima's avatar
Ultima committed
953
        return np.prod(self.get_shape())
Marco Selig's avatar
Marco Selig committed
954

955
    def get_dof(self, split=False):
Ultimanet's avatar
Ultimanet committed
956
957
958
959
        """
            Computes the number of degrees of freedom of the space, i.e./  the
            number of points for real-valued fields and twice that number for
            complex-valued fields.
Marco Selig's avatar
Marco Selig committed
960

Ultimanet's avatar
Ultimanet committed
961
962
963
964
965
            Returns
            -------
            dof : int
                Number of degrees of freedom of the space.
        """
Ultima's avatar
Ultima committed
966
967
968
969
        if split:
            dof = self.get_shape()
            if issubclass(self.dtype.type, np.complexfloating):
                dof = tuple(np.array(dof)*2)
970
        else:
Ultima's avatar
Ultima committed
971
972
973
974
            dof = self.get_dim()
            if issubclass(self.dtype.type, np.complexfloating):
                dof = dof * 2
        return dof
975
976
977
978

    def get_vol(self, split=False):
        if split:
            return self.distances
Ultimanet's avatar
Ultimanet committed
979
        else:
980
            return np.prod(self.distances)
Marco Selig's avatar
Marco Selig committed
981

982
    def get_meta_volume(self, split=False):
Marco Selig's avatar
Marco Selig committed
983
        """
984
            Calculates the meta volumes.
Ultimanet's avatar
Ultimanet committed
985

986
987
988
989
990
            The meta volumes are the volumes associated with each component of
            a field, taking into account field components that are not
            explicitly included in the array of field values but are determined
            by symmetry conditions. In the case of an :py:class:`rg_space`, the
            meta volumes are simply the pixel volumes.
Marco Selig's avatar
Marco Selig committed
991
992
993

            Parameters
            ----------
994
995
996
            total : bool, *optional*
                Whether to return the total meta volume of the space or the
                individual ones of each pixel (default: False).
Marco Selig's avatar
Marco Selig committed
997
998
999

            Returns
            -------
1000
1001
            mol : {numpy.ndarray, float}
                Meta volume of the pixels or the complete space.
Ultimanet's avatar
Ultimanet committed
1002
        """
1003
1004
1005
1006
1007
        if not split:
            return self.get_dim() * self.get_vol()
        else:
            mol = self.cast(1, dtype=np.dtype('float'))
            return self.calc_weight(mol, power=1)
1008

Ultima's avatar
Ultima committed
1009
    def cast(self, x=None, dtype=None, **kwargs):
1010
        return self._cast_to_d2o(x=x, dtype=dtype, **kwargs)
1011

Ultima's avatar
Ultima committed
1012
    def _cast_to_d2o(self, x, dtype=None, **kwargs):
1013
1014
        """
            Computes valid field values from a given object, trying
1015
1016
            to translate the given data into a valid form. Thereby it is as
            benevolent as possible.
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031

            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*
1032
                Whether the method should raise a warning if information is
1033
1034
                lost during casting (default: False).
        """
1035
1036
        if dtype is not None:
            dtype = np.dtype(dtype)
1037
        if dtype is None:
1038
            dtype = self.dtype
1039

Ultima's avatar
Ultima committed
1040
        # Case 1: x is a distributed_data_object
1041
        if isinstance(x, distributed_data_object):
Ultima's avatar
Ultima committed
1042
1043
            to_copy = False

1044
            # Check the shape
1045
            if np.any(np.array(x.shape) != np.array(self.get_shape())):
1046
                # Check if at least the number of degrees of freedom is equal
1047
                if x.get_dim() == self.get_dim():
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
                    try:
                        temp = x.copy_empty(global_shape=self.get_shape())
                        temp.set_local_data(x.get_local_data(), 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.get_full_data()
                        temp = np.reshape(temp, self.get_shape())
1059
                    # ... and cast again
Ultima's avatar
Ultima committed
1060
1061
1062
                    return self._cast_to_d2o(temp,
                                             dtype=dtype,
                                             **kwargs)
1063

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

1068
            # Check the dtype
1069
            if x.dtype != dtype:
Ultima's avatar
Ultima committed
1070
1071
1072
1073
1074
1075
                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")
Ultima's avatar
Ultima committed
1076
1077
1078
                to_copy = True

            if to_copy:
csongor's avatar
csongor committed
1079
                temp = x.copy_empty(dtype=dtype)
1080
1081
                temp.set_data(to_key=(slice(None),),
                              data=x,
1082
                              from_key=(slice(None),))
1083
1084
                temp.hermitian = x.hermitian
                x = temp
1085

1086
            return x
1087