space.py 14.7 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

csongor's avatar
csongor committed
147
from nifty.config import about
148
from nifty_paradict import space_paradict
Marco Selig's avatar
Marco Selig committed
149

Ultimanet's avatar
Ultimanet committed
150

theos's avatar
theos committed
151
class Space(object):
Marco Selig's avatar
Marco Selig committed
152
    """
Ultimanet's avatar
Ultimanet committed
153
154
155
156
157
158
159
        ..                            __             __
        ..                          /__/           /  /_
        ..      ______    ______    __   __ ___   /   _/
        ..    /   _   | /   _   | /  / /   _   | /  /
        ..   /  /_/  / /  /_/  / /  / /  / /  / /  /_
        ..  /   ____/  \______/ /__/ /__/ /__/  \___/  space class
        .. /__/
Marco Selig's avatar
Marco Selig committed
160

Ultimanet's avatar
Ultimanet committed
161
        NIFTY subclass for unstructured spaces.
Marco Selig's avatar
Marco Selig committed
162

Ultimanet's avatar
Ultimanet committed
163
164
        Unstructured spaces are lists of values without any geometrical
        information.
Marco Selig's avatar
Marco Selig committed
165
166
167

        Parameters
        ----------
Ultimanet's avatar
Ultimanet committed
168
169
        num : int
            Number of points.
170
        dtype : numpy.dtype, *optional*
Ultimanet's avatar
Ultimanet committed
171
            Data type of the field values (default: None).
Marco Selig's avatar
Marco Selig committed
172

Ultimanet's avatar
Ultimanet committed
173
        Attributes
Marco Selig's avatar
Marco Selig committed
174
        ----------
Ultimanet's avatar
Ultimanet committed
175
176
        para : numpy.ndarray
            Array containing the number of points.
177
        dtype : numpy.dtype
Ultimanet's avatar
Ultimanet committed
178
179
180
181
182
183
            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
184
    """
185

186
    def __init__(self, dtype=np.dtype('float'), **kwargs):
Ultimanet's avatar
Ultimanet committed
187
188
        """
            Sets the attributes for a point_space class instance.
Marco Selig's avatar
Marco Selig committed
189

Ultimanet's avatar
Ultimanet committed
190
191
192
193
            Parameters
            ----------
            num : int
                Number of points.
194
            dtype : numpy.dtype, *optional*
Ultimanet's avatar
Ultimanet committed
195
                Data type of the field values (default: numpy.float64).
Marco Selig's avatar
Marco Selig committed
196

Ultimanet's avatar
Ultimanet committed
197
198
199
200
            Returns
            -------
            None.
        """
201
        self.paradict = space_paradict(**kwargs)
202

203
204
        # parse dtype
        dtype = np.dtype(dtype)
Ultima's avatar
Ultima committed
205
        self.dtype = dtype
206

207
        self.harmonic = None
208

Ultima's avatar
Ultima committed
209
210
211
212
    def __hash__(self):
        # Extract the identifying parts from the vars(self) dict.
        result_hash = 0
        for (key, item) in vars(self).items():
213
            if key in []:
Ultima's avatar
Ultima committed
214
                continue
215
            result_hash ^= item.__hash__() ^ 113*hash(key)
Ultima's avatar
Ultima committed
216
217
        return result_hash

218
219
220
221
222
    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()
223
                if ii[0] not in []
224
225
226
227
                ]
        # Return the sorted identifiers as a tuple.
        return tuple(sorted(temp))

228
    def copy(self):
229
        return Space(dtype=self.dtype, **self.paradict.parameters)
230

231
232
    @property
    def shape(self):
233
234
        raise NotImplementedError(about._errors.cstring(
            "ERROR: There is no generic shape for the Space base class."))
Marco Selig's avatar
Marco Selig committed
235

236
237
    @property
    def dim(self):
238
239
        raise NotImplementedError(about._errors.cstring(
            "ERROR: There is no generic dim for the Space base class."))
Marco Selig's avatar
Marco Selig committed
240

241
242
    @property
    def dof(self):
Ultimanet's avatar
Ultimanet committed
243
244
245
246
        """
            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
247

Ultimanet's avatar
Ultimanet committed
248
249
250
251
252
            Returns
            -------
            dof : int
                Number of degrees of freedom of the space.
        """
253
254
255
        dof = self.dim
        if issubclass(self.dtype.type, np.complexfloating):
            dof = dof * 2
Ultima's avatar
Ultima committed
256
        return dof
257

258
    @property
259
    def total_volume(self):
theos's avatar
theos committed
260
261
        raise NotImplementedError(about._errors.cstring(
            "ERROR: There is no generic volume for the Space base class."))
262

263
    def complement_cast(self, x, axes=None):
264
265
        return x

266
    def weight(self, x, power=1, axes=None):
Marco Selig's avatar
Marco Selig committed
267
        """
Ultimanet's avatar
Ultimanet committed
268
269
            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
270
271
272

            Parameters
            ----------
Ultimanet's avatar
Ultimanet committed
273
274
275
276
            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
277
278

            Returns
Ultimanet's avatar
Ultimanet committed
279
280
281
            -------
            y : numpy.ndarray
                Weighted array.
Marco Selig's avatar
Marco Selig committed
282
        """
283
        raise NotImplementedError
Ultima's avatar
Ultima committed
284

285
    def dot_contraction(self, x, axes):
Ultimanet's avatar
Ultimanet committed
286
287
288
        """
            Computes the discrete inner product of two given arrays of field
            values.
Marco Selig's avatar
Marco Selig committed
289

Ultimanet's avatar
Ultimanet committed
290
291
292
293
294
295
            Parameters
            ----------
            x : numpy.ndarray
                First array
            y : numpy.ndarray
                Second array
Marco Selig's avatar
Marco Selig committed
296

Ultimanet's avatar
Ultimanet committed
297
298
299
300
301
            Returns
            -------
            dot : scalar
                Inner product of the two arrays.
        """
302
        return x.sum(axis=axes)
303

304
305
306
    def compute_k_array(self, distribution_strategy):
        raise NotImplementedError(about._errors.cstring(
            "ERROR: There is no generic k_array for Space base class."))
307

308
    def smooth(self, x, **kwargs):
309
310
311
312
313
314
315
316
317
        """
            Raises an error since smoothing is ill-defined on an unstructured
            space.
        """
        raise AttributeError(about._errors.cstring(
            "ERROR: smoothing ill-defined for (unstructured) point space."))

    def get_plot(self, x, title="", vmin=None, vmax=None, unit=None,
                 norm=None, other=None, legend=False, save=None, **kwargs):
Marco Selig's avatar
Marco Selig committed
318
        """
319
320
            Creates a plot of field values according to the specifications
            given by the parameters.
Marco Selig's avatar
Marco Selig committed
321
322
323

            Parameters
            ----------
Ultimanet's avatar
Ultimanet committed
324
            x : numpy.ndarray
325
                Array containing the field values.
Marco Selig's avatar
Marco Selig committed
326
327
328

            Returns
            -------
329
            None
330

Ultimanet's avatar
Ultimanet committed
331
            Other parameters
332
            ----------------
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
            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)``).
            unit : string, *optional*
                Unit of the field values (default: "").
            norm : string, *optional*
                Scaling of the field values before plotting (default: None).
            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).
            save : string, *optional*
                Valid file name where the figure is to be stored, by default
                the figure is not saved (default: False).

Ultimanet's avatar
Ultimanet committed
352
        """
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
        if not pl.isinteractive() and save is not None:
            about.warnings.cprint("WARNING: interactive mode off.")

        x = self.cast(x)

        fig = pl.figure(num=None,
                        figsize=(6.4, 4.8),
                        dpi=None,
                        facecolor="none",
                        edgecolor="none",
                        frameon=False,
                        FigureClass=pl.Figure)

        ax0 = fig.add_axes([0.12, 0.12, 0.82, 0.76])
        xaxes = np.arange(self.para[0], dtype=np.dtype('int'))

369
        if (norm == "log") and (vmin <= 0):
370
371
372
373
374
375
376
377
            raise ValueError(about._errors.cstring(
                "ERROR: nonpositive value(s)."))

        if issubclass(self.dtype.type, np.complexfloating):
            if vmin is None:
                vmin = min(x.real.min(), x.imag.min(), abs(x).min())
            if vmax is None:
                vmax = min(x.real.max(), x.imag.max(), abs(x).max())
Ultimanet's avatar
Ultimanet committed
378
        else:
379
380
381
382
            if vmin is None:
                vmin = x.min()
            if vmax is None:
                vmax = x.max()
Ultimanet's avatar
Ultimanet committed
383

384
385
386
        ax0.set_xlim(xaxes[0], xaxes[-1])
        ax0.set_xlabel("index")
        ax0.set_ylim(vmin, vmax)
387

388
389
        if(norm == "log"):
            ax0.set_yscale('log')
Marco Selig's avatar
Marco Selig committed
390

391
392
393
394
395
396
397
398
399
400
401
402
403
404
        if issubclass(self.dtype.type, np.complexfloating):
            ax0.scatter(xaxes, self.unary_operation(x, op='abs'),
                        color=[0.0, 0.5, 0.0], marker='o',
                        label="graph (absolute)", facecolor="none", zorder=1)
            ax0.scatter(xaxes, self.unary_operation(x, op='real'),
                        color=[0.0, 0.5, 0.0], marker='s',
                        label="graph (real part)", facecolor="none", zorder=1)
            ax0.scatter(xaxes, self.unary_operation(x, op='imag'),
                        color=[0.0, 0.5, 0.0], marker='D',
                        label="graph (imaginary part)", facecolor="none",
                        zorder=1)
        else:
            ax0.scatter(xaxes, x, color=[0.0, 0.5, 0.0], marker='o',
                        label="graph 0", zorder=1)
Marco Selig's avatar
Marco Selig committed
405

406
407
408
409
410
411
412
413
414
415
416
417
        if other is not None:
            if not isinstance(other, tuple):
                other = (other, )
            imax = max(1, len(other) - 1)
            for ii in xrange(len(other)):
                ax0.scatter(xaxes, self.dtype(other[ii]),
                            color=[max(0.0, 1.0 - (2 * ii / imax)**2),
                                   0.5 * ((2 * ii - imax) / imax)**2,
                                   max(0.0, 1.0 -
                                       (2 * (ii - imax) / imax)**2)],
                            marker='o', label="'other' graph " + str(ii),
                            zorder=-ii)
Ultimanet's avatar
Ultimanet committed
418

419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
        if legend:
            ax0.legend()

        if unit is not None:
            unit = " [" + unit + "]"
        else:
            unit = ""

        ax0.set_ylabel("values" + unit)
        ax0.set_title(title)

        if save is not None:
            fig.savefig(str(save), dpi=None,
                        facecolor="none", edgecolor="none")
            pl.close(fig)
        else:
            fig.canvas.draw()
Marco Selig's avatar
Marco Selig committed
436

437
    def __repr__(self):
Ultima's avatar
Ultima committed
438
439
        string = ""
        string += str(type(self)) + "\n"
Ultima's avatar
Ultima committed
440
        string += "paradict: " + str(self.paradict) + "\n"
441
442
        string += "dtype: " + str(self.dtype) + "\n"
        string += "harmonic: " + str(self.harmonic) + "\n"
Ultima's avatar
Ultima committed
443
        return string