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

"""
from __future__ import division
144
145
146

import abc

Marco Selig's avatar
Marco Selig committed
147
148
import numpy as np

Theo Steininger's avatar
Theo Steininger committed
149
150
from keepers import Loggable,\
                    Versionable
Ultimanet's avatar
Ultimanet committed
151

152
from nifty.plotting import Plottable
153

154
class Space(Versionable, Loggable, Plottable, object):
Marco Selig's avatar
Marco Selig committed
155
    """
Ultimanet's avatar
Ultimanet committed
156
157
158
159
160
161
162
        ..                            __             __
        ..                          /__/           /  /_
        ..      ______    ______    __   __ ___   /   _/
        ..    /   _   | /   _   | /  / /   _   | /  /
        ..   /  /_/  / /  /_/  / /  / /  / /  / /  /_
        ..  /   ____/  \______/ /__/ /__/ /__/  \___/  space class
        .. /__/
Marco Selig's avatar
Marco Selig committed
163

Ultimanet's avatar
Ultimanet committed
164
        NIFTY subclass for unstructured spaces.
Marco Selig's avatar
Marco Selig committed
165

Ultimanet's avatar
Ultimanet committed
166
167
        Unstructured spaces are lists of values without any geometrical
        information.
Marco Selig's avatar
Marco Selig committed
168
169
170

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

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

189
190
191
    __metaclass__ = abc.ABCMeta

    def __init__(self, dtype=np.dtype('float')):
Ultimanet's avatar
Ultimanet committed
192
193
        """
            Sets the attributes for a point_space class instance.
Marco Selig's avatar
Marco Selig committed
194

Ultimanet's avatar
Ultimanet committed
195
196
197
198
            Parameters
            ----------
            num : int
                Number of points.
199
            dtype : numpy.dtype, *optional*
Ultimanet's avatar
Ultimanet committed
200
                Data type of the field values (default: numpy.float64).
Marco Selig's avatar
Marco Selig committed
201

Ultimanet's avatar
Ultimanet committed
202
203
204
205
            Returns
            -------
            None.
        """
206

207
        # parse dtype
208
209
210
211
        casted_dtype = np.result_type(dtype, np.float64)
        if casted_dtype != dtype:
            self.Logger.warning("Input dtype reset to: %s" % str(casted_dtype))
        self.dtype = casted_dtype
212

Theo Steininger's avatar
Theo Steininger committed
213
        self._ignore_for_hash = ['_global_id']
214

Ultima's avatar
Ultima committed
215
216
217
    def __hash__(self):
        # Extract the identifying parts from the vars(self) dict.
        result_hash = 0
Theo Steininger's avatar
Theo Steininger committed
218
219
        for key in sorted(vars(self).keys()):
            item = vars(self)[key]
220
            if key in self._ignore_for_hash or key == '_ignore_for_hash':
Ultima's avatar
Ultima committed
221
                continue
theos's avatar
theos committed
222
            result_hash ^= item.__hash__() ^ int(hash(key)/117)
Ultima's avatar
Ultima committed
223
224
        return result_hash

theos's avatar
theos committed
225
226
227
228
229
    def __eq__(self, x):
        if isinstance(x, type(self)):
            return hash(self) == hash(x)
        else:
            return False
230

theos's avatar
theos committed
231
232
233
    def __ne__(self, x):
        return not self.__eq__(x)

234
235
236
    @abc.abstractproperty
    def harmonic(self):
        raise NotImplementedError
237

238
    @abc.abstractproperty
239
    def shape(self):
240
241
        raise NotImplementedError(
            "There is no generic shape for the Space base class.")
Marco Selig's avatar
Marco Selig committed
242

243
    @abc.abstractproperty
244
    def dim(self):
245
246
        raise NotImplementedError(
            "There is no generic dim for the Space base class.")
Marco Selig's avatar
Marco Selig committed
247

248
    @abc.abstractproperty
249
    def total_volume(self):
250
251
        raise NotImplementedError(
            "There is no generic volume for the Space base class.")
252

253
254
255
    @abc.abstractmethod
    def copy(self):
        return self.__class__(dtype=self.dtype)
256

257
    @abc.abstractmethod
258
    def weight(self, x, power=1, axes=None, inplace=False):
Marco Selig's avatar
Marco Selig committed
259
        """
Ultimanet's avatar
Ultimanet committed
260
261
            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
262
263
264

            Parameters
            ----------
Ultimanet's avatar
Ultimanet committed
265
266
267
268
            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
269
270

            Returns
Ultimanet's avatar
Ultimanet committed
271
272
273
            -------
            y : numpy.ndarray
                Weighted array.
Marco Selig's avatar
Marco Selig committed
274
        """
275
        raise NotImplementedError
Ultima's avatar
Ultima committed
276

277
278
279
280
    def pre_cast(self, x, axes=None):
        return x

    def post_cast(self, x, axes=None):
281
282
        return x

283
    def get_distance_array(self, distribution_strategy):
284
        raise NotImplementedError(
285
286
            "There is no generic distance structure for Space base class.")

287
    def get_fft_smoothing_kernel_function(self, sigma):
288
289
        raise NotImplementedError(
            "There is no generic co-smoothing kernel for Space base class.")
290

291
292
293
    def hermitian_decomposition(self, x, axes=None):
        raise NotImplementedError

294
    def __repr__(self):
Ultima's avatar
Ultima committed
295
296
        string = ""
        string += str(type(self)) + "\n"
297
        string += "dtype: " + str(self.dtype) + "\n"
Ultima's avatar
Ultima committed
298
        return string
Theo Steininger's avatar
Theo Steininger committed
299
300
301
302
303
304
305
306
307
308
309
310

    # ---Serialization---

    def _to_hdf5(self, hdf5_group):
        hdf5_group.attrs['dtype'] = self.dtype.name

        return None

    @classmethod
    def _from_hdf5(cls, hdf5_group, repository):
        result = cls(dtype=np.dtype(hdf5_group.attrs['dtype']))
        return result