nifty_core.py 50.1 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

280
    def get_shape(self):
281
        raise NotImplementedError(about._errors.cstring(
Ultimanet's avatar
Ultimanet committed
282
            "ERROR: no generic instance method 'shape'."))
Marco Selig's avatar
Marco Selig committed
283

ultimanet's avatar
ultimanet committed
284
    def get_dim(self):
Marco Selig's avatar
Marco Selig committed
285
        """
Ultimanet's avatar
Ultimanet committed
286
            Computes the dimension of the space, i.e.\  the number of pixels.
Marco Selig's avatar
Marco Selig committed
287
288
289

            Parameters
            ----------
Ultimanet's avatar
Ultimanet committed
290
291
292
            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
293

Ultimanet's avatar
Ultimanet committed
294
295
296
297
            Returns
            -------
            dim : {int, numpy.ndarray}
                Dimension(s) of the space.
Marco Selig's avatar
Marco Selig committed
298
        """
299
        raise NotImplementedError(about._errors.cstring(
300
            "ERROR: no generic instance method 'dim'."))
Marco Selig's avatar
Marco Selig committed
301

302
    def get_dof(self):
Marco Selig's avatar
Marco Selig committed
303
        """
Ultimanet's avatar
Ultimanet committed
304
            Computes the number of degrees of freedom of the space.
Marco Selig's avatar
Marco Selig committed
305
306
307

            Returns
            -------
Ultimanet's avatar
Ultimanet committed
308
309
            dof : int
                Number of degrees of freedom of the space.
Marco Selig's avatar
Marco Selig committed
310
        """
311
        raise NotImplementedError(about._errors.cstring(
312
            "ERROR: no generic instance method 'dof'."))
Marco Selig's avatar
Marco Selig committed
313

csongor's avatar
csongor committed
314
315
    def _complement_cast(self, x, axis=None):
        return x
Marco Selig's avatar
Marco Selig committed
316

317
    # TODO: Move enforce power into power_indices class
318
    def enforce_power(self, spec, **kwargs):
Marco Selig's avatar
Marco Selig committed
319
        """
Ultimanet's avatar
Ultimanet committed
320
            Provides a valid power spectrum array from a given object.
Marco Selig's avatar
Marco Selig committed
321
322
323

            Parameters
            ----------
Ultimanet's avatar
Ultimanet committed
324
325
326
327
            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
328
329
330

            Returns
            -------
Ultimanet's avatar
Ultimanet committed
331
332
333
334
335
336
337
338
339
340
341
342
            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*
343
344
                Flag specifying if the spectral binning is performed on
                logarithmic
Ultimanet's avatar
Ultimanet committed
345
346
347
348
                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*
349
350
                Number of used spectral bins; if given `log` is set to
                ``False``;
Ultimanet's avatar
Ultimanet committed
351
352
353
354
355
                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
356
357
                (default: None).
            vmin : {scalar, list, ndarray, field}, *optional*
Ultimanet's avatar
Ultimanet committed
358
359
                Lower limit of the uniform distribution if ``random == "uni"``
                (default: 0).
Marco Selig's avatar
Marco Selig committed
360
361

        """
362
        raise NotImplementedError(about._errors.cstring(
363
            "ERROR: no generic instance method 'enforce_power'."))
Marco Selig's avatar
Marco Selig committed
364

365
    def check_codomain(self, codomain):
Marco Selig's avatar
Marco Selig committed
366
        """
367
            Checks whether a given codomain is compatible to the space or not.
Marco Selig's avatar
Marco Selig committed
368
369
370

            Parameters
            ----------
371
372
            codomain : nifty.space
                Space to be checked for compatibility.
Marco Selig's avatar
Marco Selig committed
373
374
375

            Returns
            -------
376
377
            check : bool
                Whether or not the given codomain is compatible to the space.
Marco Selig's avatar
Marco Selig committed
378
        """
Ultima's avatar
Ultima committed
379
380
381
382
383
        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
384

385
    def get_codomain(self, **kwargs):
Marco Selig's avatar
Marco Selig committed
386
        """
387
388
389
            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
390
391
392

            Parameters
            ----------
393
394
395
396
            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
397
                (default: None).
398
399
400
401
            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
402
403
404

            Returns
            -------
405
406
            codomain : nifty.space
                A compatible codomain.
Ultimanet's avatar
Ultimanet committed
407
        """
408
        raise NotImplementedError(about._errors.cstring(
409
            "ERROR: no generic instance method 'get_codomain'."))
Marco Selig's avatar
Marco Selig committed
410

411
    def get_random_values(self, **kwargs):
Marco Selig's avatar
Marco Selig committed
412
        """
Ultimanet's avatar
Ultimanet committed
413
414
            Generates random field values according to the specifications given
            by the parameters.
Marco Selig's avatar
Marco Selig committed
415

Ultimanet's avatar
Ultimanet committed
416
417
418
419
420
421
422
            Returns
            -------
            x : numpy.ndarray
                Valid field values.

            Other parameters
            ----------------
Marco Selig's avatar
Marco Selig committed
423
            random : string, *optional*
Ultimanet's avatar
Ultimanet committed
424
425
426
                Specifies the probability distribution from which the random
                numbers are to be drawn.
                Supported distributions are:
Marco Selig's avatar
Marco Selig committed
427
428

                - "pm1" (uniform distribution over {+1,-1} or {+1,+i,-1,-i}
429
430
                - "gau" (normal distribution with zero-mean and a given
                    standard deviation or variance)
Marco Selig's avatar
Marco Selig committed
431
432
433
434
                - "syn" (synthesizes from a given power spectrum)
                - "uni" (uniform distribution over [vmin,vmax[)

                (default: None).
Ultimanet's avatar
Ultimanet committed
435
436
437
438
439
            dev : float, *optional*
                Standard deviation (default: 1).
            var : float, *optional*
                Variance, overriding `dev` if both are specified
                (default: 1).
440
441
            spec : {scalar, list, numpy.ndarray, nifty.field, function},
                    *optional*
Ultimanet's avatar
Ultimanet committed
442
                Power spectrum (default: 1).
443
444
445
446
            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
447
                Scale of each band (default: None).
448
            codomain : nifty.space, *optional*
Ultimanet's avatar
Ultimanet committed
449
                A compatible codomain with power indices (default: None).
450
            log : bool, *optional*
451
452
                Flag specifying if the spectral binning is performed on
                logarithmic
453
454
455
456
                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*
457
458
                Number of used spectral bins; if given `log` is set to
                ``False``;
459
460
461
462
463
                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
464
465
                (default: None).
            vmin : {scalar, list, ndarray, field}, *optional*
466
467
                Lower limit of the uniform distribution if ``random == "uni"``
                (default: 0).
Ultimanet's avatar
Ultimanet committed
468
469
470
471
            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
472
        """
473
474
        raise NotImplementedError(about._errors.cstring(
            "ERROR: no generic instance method 'get_random_values'."))
Marco Selig's avatar
Marco Selig committed
475

476
    def calc_weight(self, x, power=1):
Marco Selig's avatar
Marco Selig committed
477
        """
478
479
            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
480
481
482

            Parameters
            ----------
483
484
485
486
            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
487
488
489

            Returns
            -------
490
491
            y : numpy.ndarray
                Weighted array.
Marco Selig's avatar
Marco Selig committed
492
        """
493
        raise NotImplementedError(about._errors.cstring(
494
            "ERROR: no generic instance method 'calc_weight'."))
Marco Selig's avatar
Marco Selig committed
495

496
497
498
    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
499

Ultima's avatar
Ultima committed
500
501
502
503
    def calc_norm(self, x, q):
        raise NotImplementedError(about._errors.cstring(
            "ERROR: no generic instance method 'norm'."))

504
    def calc_dot(self, x, y):
Marco Selig's avatar
Marco Selig committed
505
        """
506
507
            Computes the discrete inner product of two given arrays of field
            values.
Marco Selig's avatar
Marco Selig committed
508
509
510

            Parameters
            ----------
511
512
513
514
            x : numpy.ndarray
                First array
            y : numpy.ndarray
                Second array
Marco Selig's avatar
Marco Selig committed
515
516
517

            Returns
            -------
518
519
            dot : scalar
                Inner product of the two arrays.
Ultimanet's avatar
Ultimanet committed
520
        """
521
        raise NotImplementedError(about._errors.cstring(
522
            "ERROR: no generic instance method 'dot'."))
Marco Selig's avatar
Marco Selig committed
523

524
    def calc_transform(self, x, codomain=None, **kwargs):
Marco Selig's avatar
Marco Selig committed
525
        """
526
            Computes the transform of a given array of field values.
Marco Selig's avatar
Marco Selig committed
527

Ultimanet's avatar
Ultimanet committed
528
529
            Parameters
            ----------
530
531
532
533
534
            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
535
536
537

            Returns
            -------
Ultimanet's avatar
Ultimanet committed
538
539
            Tx : numpy.ndarray
                Transformed array
540

Ultimanet's avatar
Ultimanet committed
541
542
543
544
            Other parameters
            ----------------
            iter : int, *optional*
                Number of iterations performed in specific transformations.
545
        """
546
547
        raise NotImplementedError(about._errors.cstring(
            "ERROR: no generic instance method 'calc_transform'."))
Marco Selig's avatar
Marco Selig committed
548

549
    def calc_smooth(self, x, sigma=0, **kwargs):
Marco Selig's avatar
Marco Selig committed
550
        """
Ultimanet's avatar
Ultimanet committed
551
552
            Smoothes an array of field values by convolution with a Gaussian
            kernel.
Marco Selig's avatar
Marco Selig committed
553
554
555

            Parameters
            ----------
Ultimanet's avatar
Ultimanet committed
556
557
558
559
560
            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
561
562
563

            Returns
            -------
Ultimanet's avatar
Ultimanet committed
564
565
            Gx : numpy.ndarray
                Smoothed array.
Marco Selig's avatar
Marco Selig committed
566

Ultimanet's avatar
Ultimanet committed
567
568
569
570
            Other parameters
            ----------------
            iter : int, *optional*
                Number of iterations (default: 0).
Marco Selig's avatar
Marco Selig committed
571
        """
572
573
        raise NotImplementedError(about._errors.cstring(
            "ERROR: no generic instance method 'calc_smooth'."))
Marco Selig's avatar
Marco Selig committed
574

575
    def calc_power(self, x, **kwargs):
Marco Selig's avatar
Marco Selig committed
576
        """
Ultimanet's avatar
Ultimanet committed
577
            Computes the power of an array of field values.
Marco Selig's avatar
Marco Selig committed
578
579
580

            Parameters
            ----------
Ultimanet's avatar
Ultimanet committed
581
582
583
            x : numpy.ndarray
                Array containing the field values of which the power is to be
                calculated.
Marco Selig's avatar
Marco Selig committed
584
585
586
587

            Returns
            -------
            spec : numpy.ndarray
Ultimanet's avatar
Ultimanet committed
588
                Power contained in the input array.
Marco Selig's avatar
Marco Selig committed
589
590
591

            Other parameters
            ----------------
Ultimanet's avatar
Ultimanet committed
592
593
594
            pindex : numpy.ndarray, *optional*
                Indexing array assigning the input array components to
                components of the power spectrum (default: None).
595
            kindex : numpy.ndarray, *optional*
Ultimanet's avatar
Ultimanet committed
596
597
598
599
                Scale corresponding to each band in the power spectrum
                (default: None).
            rho : numpy.ndarray, *optional*
                Number of degrees of freedom per band (default: None).
600
601
602
            codomain : nifty.space, *optional*
                A compatible codomain for power indexing (default: None).
            log : bool, *optional*
603
604
                Flag specifying if the spectral binning is performed on
                logarithmic
605
606
607
608
                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*
609
610
                Number of used spectral bins; if given `log` is set to
                ``False``;
611
612
613
614
615
                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
616
617
                (default: None).
            vmin : {scalar, list, ndarray, field}, *optional*
618
619
                Lower limit of the uniform distribution if ``random == "uni"``
                (default: 0).
620

Marco Selig's avatar
Marco Selig committed
621
        """
622
623
        raise NotImplementedError(about._errors.cstring(
            "ERROR: no generic instance method 'calc_power'."))
Marco Selig's avatar
Marco Selig committed
624

625
626
627
628
629
630
631
    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
632

633
    def get_plot(self, x, **kwargs):
Marco Selig's avatar
Marco Selig committed
634
        """
Ultimanet's avatar
Ultimanet committed
635
636
            Creates a plot of field values according to the specifications
            given by the parameters.
637
638
639

            Parameters
            ----------
Ultimanet's avatar
Ultimanet committed
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
            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*
685
686
                Flag specifying if the spectral binning is performed on
                logarithmic
687
688
689
                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
690
            nbin : integer, *optional*
691
692
                Number of used spectral bins; if given `log` is set to
                ``False``;
693
                integers below the minimum of 3 induce an automatic setting;
694
                by default no binning is done (default: None).
Ultimanet's avatar
Ultimanet committed
695
            binbounds : {list, array}, *optional*
696
697
                User specific inner boundaries of the bins, which are preferred
                over the above parameters; by default no binning is done
698
699
                (default: None).
            vmin : {scalar, list, ndarray, field}, *optional*
Ultimanet's avatar
Ultimanet committed
700
701
702
703
                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
704
705

        """
706
707
        raise NotImplementedError(about._errors.cstring(
            "ERROR: no generic instance method 'get_plot'."))
Marco Selig's avatar
Marco Selig committed
708

Ultimanet's avatar
Ultimanet committed
709
    def __repr__(self):
Ultima's avatar
Ultima committed
710
711
712
713
        string = ""
        string += str(type(self)) + "\n"
        string += "paradict: " + str(self.paradict) + "\n"
        return string
Marco Selig's avatar
Marco Selig committed
714

Ultimanet's avatar
Ultimanet committed
715
    def __str__(self):
Ultima's avatar
Ultima committed
716
        return self.__repr__()
Marco Selig's avatar
Marco Selig committed
717
718


Ultimanet's avatar
Ultimanet committed
719
class point_space(space):
Marco Selig's avatar
Marco Selig committed
720
    """
Ultimanet's avatar
Ultimanet committed
721
722
723
724
725
726
727
        ..                            __             __
        ..                          /__/           /  /_
        ..      ______    ______    __   __ ___   /   _/
        ..    /   _   | /   _   | /  / /   _   | /  /
        ..   /  /_/  / /  /_/  / /  / /  / /  / /  /_
        ..  /   ____/  \______/ /__/ /__/ /__/  \___/  space class
        .. /__/
Marco Selig's avatar
Marco Selig committed
728

Ultimanet's avatar
Ultimanet committed
729
        NIFTY subclass for unstructured spaces.
Marco Selig's avatar
Marco Selig committed
730

Ultimanet's avatar
Ultimanet committed
731
732
        Unstructured spaces are lists of values without any geometrical
        information.
Marco Selig's avatar
Marco Selig committed
733
734
735

        Parameters
        ----------
Ultimanet's avatar
Ultimanet committed
736
737
        num : int
            Number of points.
738
        dtype : numpy.dtype, *optional*
Ultimanet's avatar
Ultimanet committed
739
            Data type of the field values (default: None).
Marco Selig's avatar
Marco Selig committed
740

Ultimanet's avatar
Ultimanet committed
741
        Attributes
Marco Selig's avatar
Marco Selig committed
742
        ----------
Ultimanet's avatar
Ultimanet committed
743
744
        para : numpy.ndarray
            Array containing the number of points.
745
        dtype : numpy.dtype
Ultimanet's avatar
Ultimanet committed
746
747
748
749
750
751
            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
752
    """
753

csongor's avatar
csongor committed
754
    def __init__(self, num, dtype=np.dtype('float')):
Ultimanet's avatar
Ultimanet committed
755
756
        """
            Sets the attributes for a point_space class instance.
Marco Selig's avatar
Marco Selig committed
757

Ultimanet's avatar
Ultimanet committed
758
759
760
761
            Parameters
            ----------
            num : int
                Number of points.
762
            dtype : numpy.dtype, *optional*
Ultimanet's avatar
Ultimanet committed
763
                Data type of the field values (default: numpy.float64).
Marco Selig's avatar
Marco Selig committed
764

Ultimanet's avatar
Ultimanet committed
765
766
767
768
            Returns
            -------
            None.
        """
Ultima's avatar
Ultima committed
769
        self._cache_dict = {'check_codomain': {}}
770
771
        self.paradict = point_space_paradict(num=num)

772
773
        # parse dtype
        dtype = np.dtype(dtype)
Ultima's avatar
Ultima committed
774
775
776
777
778
779
780
781
782
        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(
783
                             "WARNING: incompatible dtype: " + str(dtype)))
Ultima's avatar
Ultima committed
784
        self.dtype = dtype
785

Ultimanet's avatar
Ultimanet committed
786
        self.discrete = True
Ultima's avatar
Ultima committed
787
#        self.harmonic = False
788
        self.distances = (np.float(1),)
Marco Selig's avatar
Marco Selig committed
789

Ultimanet's avatar
Ultimanet committed
790
791
792
793
    @property
    def para(self):
        temp = np.array([self.paradict['num']], dtype=int)
        return temp
794

Ultimanet's avatar
Ultimanet committed
795
796
    @para.setter
    def para(self, x):
Ultima's avatar
Ultima committed
797
        self.paradict['num'] = x[0]
798

Ultima's avatar
Ultima committed
799
800
801
802
    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
803
804
            if key in ['_cache_dict']:
                continue
Ultima's avatar
Ultima committed
805
806
807
            result_hash ^= item.__hash__() * hash(key)
        return result_hash

808
809
810
811
812
    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
813
                if ii[0] not in ['_cache_dict']
814
815
816
817
                ]
        # Return the sorted identifiers as a tuple.
        return tuple(sorted(temp))

818
    def copy(self):
819
        return point_space(num=self.paradict['num'],
csongor's avatar
csongor committed
820
                           dtype=self.dtype)
821

Ultimanet's avatar
Ultimanet committed
822
823
    def getitem(self, data, key):
        return data[key]
Marco Selig's avatar
Marco Selig committed
824

Ultimanet's avatar
Ultimanet committed
825
    def setitem(self, data, update, key):
826
        data[key] = update
Marco Selig's avatar
Marco Selig committed
827

Ultimanet's avatar
Ultimanet committed
828
    def apply_scalar_function(self, x, function, inplace=False):
829
        return x.apply_scalar_function(function, inplace=inplace)
830
831

    def get_shape(self):
832
        return (self.paradict['num'],)
Marco Selig's avatar
Marco Selig committed
833

Ultima's avatar
Ultima committed
834
    def get_dim(self):
Ultimanet's avatar
Ultimanet committed
835
836
        """
            Computes the dimension of the space, i.e.\  the number of points.
Marco Selig's avatar
Marco Selig committed
837

Ultimanet's avatar
Ultimanet committed
838
839
840
841
842
            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
843

Ultimanet's avatar
Ultimanet committed
844
845
846
847
848
            Returns
            -------
            dim : {int, numpy.ndarray}
                Dimension(s) of the space.
        """
Ultima's avatar
Ultima committed
849
        return np.prod(self.get_shape())
Marco Selig's avatar
Marco Selig committed
850

851
    def get_dof(self, split=False):
Ultimanet's avatar
Ultimanet committed
852
853
854
855
        """
            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
856

Ultimanet's avatar
Ultimanet committed
857
858
859
860
861
            Returns
            -------
            dof : int
                Number of degrees of freedom of the space.
        """
Ultima's avatar
Ultima committed
862
863
864
865
        if split:
            dof = self.get_shape()
            if issubclass(self.dtype.type, np.complexfloating):
                dof = tuple(np.array(dof)*2)
866
        else:
Ultima's avatar
Ultima committed
867
868
869
870
            dof = self.get_dim()
            if issubclass(self.dtype.type, np.complexfloating):
                dof = dof * 2
        return dof
871
872
873
874

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

878
    def get_meta_volume(self, split=False):
Marco Selig's avatar
Marco Selig committed
879
        """
880
            Calculates the meta volumes.
Ultimanet's avatar
Ultimanet committed
881

882
883
884
885
886
            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
887
888
889

            Parameters
            ----------
890
891
892
            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
893
894
895

            Returns
            -------
896
897
            mol : {numpy.ndarray, float}
                Meta volume of the pixels or the complete space.
Ultimanet's avatar
Ultimanet committed
898
        """
899
900
901
902
903
        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)
904

905
906
907
908
    def enforce_power(self, spec, **kwargs):
        """
            Raises an error since the power spectrum is ill-defined for point
            spaces.
Marco Selig's avatar
Marco Selig committed
909
        """
910
911
912
        raise AttributeError(about._errors.cstring(
            "ERROR: the definition of power spectra is ill-defined for " +
            "(unstructured) point spaces."))
Ultimanet's avatar
Ultimanet committed
913

914
    def _enforce_power_helper(self, spec, size, kindex):
915
916
917
918
        # TODO: Resolve this import by splitting nifty_core into nifty_space
        # and nifty_point_space
        from nifty_field import field

919
920
921
        # Now it's about to extract a powerspectrum from spec
        # First of all just extract a numpy array. The shape is cared about
        # later.
922
        dtype = np.dtype('float')
923
924
925
926
        # Case 1: spec is a function
        if callable(spec):
            # Try to plug in the kindex array in the function directly
            try:
927
                spec = np.array(spec(kindex), dtype=dtype)
928
929
930
931
932
            except:
                # Second try: Use a vectorized version of the function.
                # This is slower, but better than nothing
                try:
                    spec = np.array(np.vectorize(spec)(kindex),
933
                                    dtype=dtype)
934
935
936
937
938
939
940
941
942
943
                except:
                    raise TypeError(about._errors.cstring(
                        "ERROR: invalid power spectra function."))

        # Case 2: spec is a field:
        elif isinstance(spec, field):
            try:
                spec = spec.val.get_full_data()
            except AttributeError:
                spec = spec.val
944
            spec = spec.astype(dtype).flatten()
Marco Selig's avatar
Marco Selig committed
945

946
947
        # Case 3: spec is a scalar or something else:
        else:
948
            spec = np.array(spec, dtype=dtype).flatten()
949
950
951
952
953

        # Make some sanity checks
        # check finiteness
        if not np.all(np.isfinite(spec)):
            about.warnings.cprint("WARNING: infinite value(s).")
Marco Selig's avatar
Marco Selig committed
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
        # check positivity (excluding null)
        if np.any(spec < 0):
            raise ValueError(about._errors.cstring(
                "ERROR: nonpositive value(s)."))
        if np.any(spec == 0):
            about.warnings.cprint("WARNING: nonpositive value(s).")

        # Set the size parameter
        if size is None:
            size = len(kindex)

        # Fix the size of the spectrum
        # If spec is singlevalued, expand it
        if np.size(spec) == 1:
            spec = spec * np.ones(size, dtype=spec.dtype)
        # If the size does not fit at all, throw an exception
        elif np.size(spec) < size:
            raise ValueError(about._errors.cstring("ERROR: size mismatch ( " +
                                                   str(np.size(spec)) + " < " +
                                                   str(size) + " )."))
        elif np.size(spec) > size:
            about.warnings.cprint("WARNING: power spectrum cut to size ( == " +
                                  str(size) + " ).")
            spec = spec[:size]

        return spec
Ultimanet's avatar
Ultimanet committed
981

982
    def check_codomain(self, codomain):
Ultima's avatar
Ultima committed
983
984
985
986
987
988
989
990
991
992
        check_dict = self._cache_dict['check_codomain']
        temp_id = id(codomain)
        if temp_id in check_dict:
            return check_dict[temp_id]
        else:
            temp_result = self._check_codomain(codomain)
            check_dict[temp_id] = temp_result
            return temp_result

    def _check_codomain(self, codomain):
Marco Selig's avatar
Marco Selig committed
993
        """
994
            Checks whether a given codomain is compatible to the space or not.
Marco Selig's avatar
Marco Selig committed
995
996
997

            Parameters
            ----------
998
999
            codomain : nifty.space
                Space to be checked for compatibility.
Marco Selig's avatar
Marco Selig committed
1000
1001
1002

            Returns
            -------
1003
1004
            check : bool
                Whether or not the given codomain is compatible to the space.
Marco Selig's avatar
Marco Selig committed
1005
        """
1006
1007
        if codomain is None:
            return False
1008

1009
1010
        if not isinstance(codomain, space):
            raise TypeError(about._errors.cstring(
Ultima's avatar
Ultima committed
1011
                "ERROR: invalid input. The given input is not a nifty space."))
Ultimanet's avatar
Ultimanet committed
1012

1013
1014
1015
1016
        if codomain == self:
            return True
        else:
            return False
Ultimanet's avatar
Ultimanet committed
1017

1018
1019
1020
1021
1022
    def get_codomain(self, **kwargs):
        """
            Generates a compatible codomain to which transformations are
            reasonable, in this case another instance of
            :py:class:`point_space` with the same properties.
Marco Selig's avatar
Marco Selig committed
1023

1024
1025
1026
1027
1028
1029
            Returns
            -------
            codomain : nifty.point_space
                A compatible codomain.
        """
        return self.copy()
Marco Selig's avatar
Marco Selig committed
1030

1031
    def get_random_values(self, **kwargs):
Marco Selig's avatar
Marco Selig committed
1032
        """
Ultimanet's avatar
Ultimanet committed
1033
1034
            Generates random field values according to the specifications given
            by the parameters.
Marco Selig's avatar
Marco Selig committed
1035
1036
1037

            Returns
            -------
Ultimanet's avatar
Ultimanet committed
1038
1039
            x : numpy.ndarray
                Valid field values.
Marco Selig's avatar
Marco Selig committed
1040

Ultimanet's avatar
Ultimanet committed
1041
1042
1043
1044
1045
1046
            Other parameters
            ----------------
            random : string, *optional*
                Specifies the probability distribution from which the random
                numbers are to be drawn.
                Supported distributions are:
Marco Selig's avatar
Marco Selig committed
1047

Ultimanet's avatar
Ultimanet committed
1048
                - "pm1" (uniform distribution over {+1,-1} or {+1,+i,-1,-i}
1049
1050
                - "gau" (normal distribution with zero-mean and a given
                standard
Ultimanet's avatar
Ultimanet committed
1051
1052
1053
                    deviation or variance)
                - "syn" (synthesizes from a given power spectrum)
                - "uni" (uniform distribution over [vmin,vmax[)
Marco Selig's avatar
Marco Selig committed
1054

Ultimanet's avatar
Ultimanet committed
1055
1056
1057
1058
1059
1060
                (default: None).
            dev : float, *optional*
                Standard deviation (default: 1).
            var : float, *optional*
                Variance, overriding `dev` if both are specified
                (default: 1).
1061
1062
            spec : {scalar, list, numpy.ndarray, nifty.field, function},
            *optional*
Ultimanet's avatar
Ultimanet committed
1063
1064
1065
1066
1067
1068
1069
1070
1071
                Power spectrum (default: 1).
            pindex : numpy.ndarray, *optional*
                Indexing array giving the power spectrum index of each band
                (default: None).
            kindex : numpy.ndarray, *optional*
                Scale of each band (default: None).
            codomain : nifty.space, *optional*
                A compatible codomain with power indices (default: None).
            log : bool, *optional*
1072
1073
                Flag specifying if the spectral binning is performed on
                logarithmic
Ultimanet's avatar
Ultimanet committed
1074
1075
1076
1077
                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*
1078
1079
                Number of used spectral bins; if given `log` is set to
                ``False``;
Ultimanet's avatar
Ultimanet committed
1080
1081
1082
1083
1084
                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
1085
1086
                (default: None).
                vmin : {scalar, list, ndarray, field}, *optional*
Ultimanet's avatar
Ultimanet committed
1087
1088
1089
1090
1091
1092
1093
                Lower limit of the uniform distribution if ``random == "uni"``
                (default: 0).
            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
1094

1095
        arg = random.parse_arguments(self, **kwargs)
1096

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

1100
1101
1102
        # Prepare the empty distributed_data_object
        sample = distributed_data_object(
                                    global_shape=self.get_shape(),
csongor's avatar
csongor committed
1103
                                    dtype=self.dtype)
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115

        # 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
1116
            else:
1117
                try:
1118
1119
                    processed_std = sample.distributor. \
                        extract_local_data(std)
1120
1121
                except(AttributeError):
                    processed_std = std
Marco Selig's avatar
Marco Selig committed
1122

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

1128
1129
1130
1131
1132
1133
1134
        # 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
1135

1136
    def calc_weight(self, x, power=1):
Marco Selig's avatar
Marco Selig committed
1137
        """
Ultimanet's avatar
Ultimanet committed
1138
1139
            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
1140
1141
1142

            Parameters
            ----------
Ultimanet's avatar
Ultimanet committed
1143
1144
1145
1146
            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
1147
1148

            Returns
Ultimanet's avatar
Ultimanet committed
1149
1150
1151
            -------
            y : numpy.ndarray
                Weighted array.
Marco Selig's avatar
Marco Selig committed
1152
        """
1153
1154
1155
        # weight
        return x * self.get_weight(power=power)

1156
    def get_weight(self, power=1, split=False):
1157
1158
1159
1160
1161
        splitted_weight = tuple(np.array(self.distances)**np.array(power))
        if not split:
            return np.prod(splitted_weight)
        else:
            return splitted_weight
Marco Selig's avatar
Marco Selig committed
1162