linear_operator.py 10.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# NIFTy
# Copyright (C) 2017  Theo Steininger
#
# Author: Theo Steininger
#
# 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.
#
# 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.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
18

19
import abc
20
from nifty.nifty_meta import NiftyMeta
21

22
from keepers import Loggable
23
24
25
26
from nifty.field import Field
import nifty.nifty_utilities as utilities


theos's avatar
theos committed
27
class LinearOperator(Loggable, object):
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59

    """NIFTY base class for linear operators.
    The base NIFTY operator class is an abstract class from which
    other specific operator subclasses, including those preimplemented
    in NIFTY (e.g. the EndomorphicOperator, ProjectionOperator,
    DiagonalOperator, SmoothingOperator, ResponseOperator,
    PropagatorOperator, ComposedOperator) must be derived.

    Parameters
    ----------


    Attributes
    ----------
    domain : NIFTy.space
        The NIFTy.space in which the operator is defined.
    target : NIFTy.space
        The NIFTy.space in which the outcome of the operator lives
    unitary : boolean
        Indicates whether the operator is unitary or not


    Raises
    ------
    NotImplementedError
        Raised if
            * domain is not defined
            * target is not defined
            * unitary is not set to (True/False)

    Notes
    -----
60
    All Operators wihtin NIFTy are linear and must therefore be a subclasses of the
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
    LinearOperator. A LinearOperator must have the attributes domain, target
    and unitary to be properly defined.

    Examples
    --------


    See Also
    --------
    EndomorphicOperator, ProjectionOperator,
    DiagonalOperator, SmoothingOperator, ResponseOperator,
    PropagatorOperator, ComposedOperator

    """

76
    __metaclass__ = NiftyMeta
77

78
79
    def __init__(self, default_spaces=None):
        self.default_spaces = default_spaces
80
81

    def _parse_domain(self, domain):
82
        return utilities.parse_domain(domain)
83

84
    @abc.abstractproperty
85
    def domain(self):
86
87
88
89
90
91
92
93
94
95
        """
        domain : NIFTy.space
            The NIFTy.space in which the operator is defined.
            Every operator which inherits from the abstract LinearOperator
            base class must have this attribute.

        Notes :
             is an abstractbaseclass.abstractproperty
             (https://docs.python.org/2/library/abc.html)
        """
96
        raise NotImplementedError
97
98
99

    @abc.abstractproperty
    def target(self):
100
101
102
103
104
105
106
107
108
109
        """
        target : NIFTy.space
            The NIFTy.space on which the processed (output) Field lives.
            Every operator which inherits from the abstract LinearOperator
            base class must have this attribute.

        Notes :
             is an abstractbaseclass.abstractproperty
             (https://docs.python.org/2/library/abc.html)
        """
110
111
        raise NotImplementedError

112
113
    @abc.abstractproperty
    def unitary(self):
114
115
116
117
118
119
120
121
122
123
124
        """
        unitary : boolean
            States whether the Operator is unitary or not.
            Every Operator which inherits from the abstract LinearOperator
            base class must have this attribute.

        Notes :
             is an abstractbaseclass.abstractproperty
             (https://docs.python.org/2/library/abc.html)

        """
125
126
        raise NotImplementedError

127
128
129
130
131
132
133
134
    @property
    def default_spaces(self):
        return self._default_spaces

    @default_spaces.setter
    def default_spaces(self, spaces):
        self._default_spaces = utilities.cast_axis_to_tuple(spaces)

135
136
137
    def __call__(self, *args, **kwargs):
        return self.times(*args, **kwargs)

138
    def times(self, x, spaces=None, **kwargs):
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
        """ Applies the Operator to a given Field.

        Operator and Field have to live over the same domain.

        Parameters
        ----------
        x : NIFTY.Field
            applies the Operator to the given Field
        spaces : integer (default: None)
            defines on which space of the given Field the Operator acts
        **kwargs
           Additional keyword arguments get passed to the used copy_empty
           routine.

        Returns
        -------
        out : NIFTy.Field
            the processed Field living on the target space

        See Also
       --------

        """

163
        spaces = self._check_input_compatibility(x, spaces)
164

165
        y = self._times(x, spaces, **kwargs)
166
167
        return y

168
    def inverse_times(self, x, spaces=None, **kwargs):
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
        """ Applies the inverse-Operator to a given Field.

        Operator and Field have to live over the same domain.

        Parameters
        ----------
        x : NIFTY.Field
            applies the Operator to the given Field
        spaces : integer (default: None)
            defines on which space of the given Field the Operator acts
        **kwargs
           Additional keyword arguments get passed to the used copy_empty
           routine.

        Returns
        -------
        out : NIFTy.Field
            the processed Field living on the target space

        See Also
       --------

        """

193
        spaces = self._check_input_compatibility(x, spaces, inverse=True)
194

195
196
197
198
199
200
201
        try:
            y = self._inverse_times(x, spaces, **kwargs)
        except(NotImplementedError):
            if (self.unitary):
                y = self._adjoint_times(x, spaces, **kwargs)
            else:
                raise
202
203
        return y

204
    def adjoint_times(self, x, spaces=None, **kwargs):
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
        """ Applies the adjoint-Operator to a given Field.

        Operator and Field have to live over the same domain.

        Parameters
        ----------
        x : NIFTY.Field
            applies the Operator to the given Field
        spaces : integer (default: None)
            defines on which space of the given Field the Operator acts
        **kwargs
           Additional keyword arguments get passed to the used copy_empty
           routine.

        Returns
        -------
        out : NIFTy.Field
            the processed Field living on the target space

        See Also
       --------

        """
228
        if self.unitary:
229
            return self.inverse_times(x, spaces)
230

231
        spaces = self._check_input_compatibility(x, spaces, inverse=True)
232

233
234
235
236
237
238
239
        try:
            y = self._adjoint_times(x, spaces, **kwargs)
        except(NotImplementedError):
            if (self.unitary):
                y = self._inverse_times(x, spaces, **kwargs)
            else:
                raise
240
241
        return y

242
243
    # If the operator supports inverse() then the inverse adjoint is identical
    # to the adjoint inverse. We provide both names for convenience.
244
    def adjoint_inverse_times(self, x, spaces=None, **kwargs):
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
        """ Applies the adjoint-inverse Operator to a given Field.

        Operator and Field have to live over the same domain.

        Parameters
        ----------
        x : NIFTY.Field
            applies the Operator to the given Field
        spaces : integer (default: None)
            defines on which space of the given Field the Operator acts
        **kwargs
           Additional keyword arguments get passed to the used copy_empty
           routine.

        Returns
        -------
        out : NIFTy.Field
            the processed Field living on the target space

        See Also
       --------

        """
268
        if self.unitary:
269
            return self.times(x, spaces)
270

271
        spaces = self._check_input_compatibility(x, spaces)
272

273
274
275
276
277
278
279
        try:
            y = self._adjoint_inverse_times(x, spaces, **kwargs)
        except(NotImplementedError):
            if self.unitary:
                y = self._times(x, spaces, **kwargs)
            else:
                raise
280
281
        return y

282
    def inverse_adjoint_times(self, x, spaces=None, **kwargs):
283
        return self.adjoint_inverse_times(x, spaces, **kwargs)
284

285
    def _times(self, x, spaces):
286
287
        raise NotImplementedError(
            "no generic instance method 'times'.")
288

289
    def _adjoint_times(self, x, spaces):
290
291
        raise NotImplementedError(
            "no generic instance method 'adjoint_times'.")
292

293
    def _inverse_times(self, x, spaces):
294
295
        raise NotImplementedError(
            "no generic instance method 'inverse_times'.")
296

297
    def _adjoint_inverse_times(self, x, spaces):
298
299
        raise NotImplementedError(
            "no generic instance method 'adjoint_inverse_times'.")
300

301
    def _inverse_adjoint_times(self, x, spaces):
302
303
        raise NotImplementedError(
            "no generic instance method 'inverse_adjoint_times'.")
304

305
    def _check_input_compatibility(self, x, spaces, inverse=False):
306
        if not isinstance(x, Field):
307
308
            raise ValueError(
                "supplied object is not a `nifty.Field`.")
309

310
311
312
        if spaces is None:
            spaces = self.default_spaces

313
314
315
316
317
318
319
        # sanitize the `spaces` and `types` input
        spaces = utilities.cast_axis_to_tuple(spaces, len(x.domain))

        # if the operator's domain is set to something, there are two valid
        # cases:
        # 1. Case:
        #   The user specifies with `spaces` that the operators domain should
320
        #   be applied to certain spaces in the domain-tuple of x.
321
322
323
        # 2. Case:
        #   The domains of self and x match completely.

324
325
326
327
328
        if not inverse:
            self_domain = self.domain
        else:
            self_domain = self.target

329
        if spaces is None:
330
            if self_domain != x.domain:
331
332
333
                raise ValueError(
                    "The operator's and and field's domains don't "
                    "match.")
334
        else:
335
336
            for i, space_index in enumerate(spaces):
                if x.domain[space_index] != self_domain[i]:
337
338
339
                    raise ValueError(
                        "The operator's and and field's domains don't "
                        "match.")
340

341
        return spaces
342
343
344

    def __repr__(self):
        return str(self.__class__)