diagonal_operator.py 12.1 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
20
21
22
23

import numpy as np

from d2o import distributed_data_object,\
                STRATEGIES as DISTRIBUTION_STRATEGIES

24
from nifty.basic_arithmetics import log as nifty_log
25
from nifty.config import nifty_configuration as gc
26
27
28
29
30
31
from nifty.field import Field
from nifty.operators.endomorphic_operator import EndomorphicOperator


class DiagonalOperator(EndomorphicOperator):

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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
    """NIFTY class for diagonal operators.
    The  NIFTY DiagonalOperator class is a subclass derived from the
    EndomorphicOperator.

    Parameters
    ----------

    domain : NIFTy.Space
        The Space on which the operator acts
    diagonal : {scalar, list, array, NIFTy.Field, d2o-object}
        The diagonal entries of the operator.
    bare : boolean
        Indicates whether the diagonal entries are bare or not
        (default: False)
    copy : boolean
        Internal copy of the diagonal (default: True)
    distribution_strategy : string
        setting the prober distribution_strategy of the
        diagonal (default : None). In case diagonal is d2o-object or Field,
        their distribution_strategy is reused.

    Attributes
    ----------
    distribution_strategy : string
        Defines the diagonal is distributed among the nodes.

    Raises
    ------

    Notes
    -----
    The ambiguity of bare or non-bare diagonal entries is based on the choice
    of a matrix representation of the operator in question. The naive choice
    of absorbing the volume weights into the matrix leads to a matrix-vector
    calculus with the non-bare entries which seems intuitive, though.
    The choice of keeping matrix entries and volume weights separate
    deals with the bare entries that allow for correct interpretation
    of the matrix entries; e.g., as variance in case of an covariance operator.

    Examples
    --------
    >>> x_space = RGSpace(5)
    >>> D = DiagonalOperator(x_space, diagonal=2.)
    >>> f = Field(x_space, val=1.)
    >>> res = D.times(f)
    >>> res.val
    <distributed_data_object>
    array([ 2.,  2.,  2.,  2.,  2.])

    See Also
    --------
    EndomorphicOperator

    """

87
88
    # ---Overwritten properties and methods---

89
90
91
92
    def __init__(self, domain=(), diagonal=None, bare=False, copy=True,
                 distribution_strategy=None, default_spaces=None):
        super(DiagonalOperator, self).__init__(default_spaces)

93
        self._domain = self._parse_domain(domain)
94

95
        if distribution_strategy is None:
96
            if isinstance(diagonal, distributed_data_object):
97
                distribution_strategy = diagonal.distribution_strategy
98
            elif isinstance(diagonal, Field):
99
                distribution_strategy = diagonal.distribution_strategy
100

101
        self._distribution_strategy = self._parse_distribution_strategy(
102
103
                               distribution_strategy=distribution_strategy,
                               val=diagonal)
104
105
106

        self.set_diagonal(diagonal=diagonal, bare=bare, copy=copy)

107
108
    def _times(self, x, spaces):
        return self._times_helper(x, spaces, operation=lambda z: z.__mul__)
109

110
111
    def _adjoint_times(self, x, spaces):
        return self._times_helper(x, spaces,
112
                                  operation=lambda z: z.adjoint().__mul__)
113

114
115
    def _inverse_times(self, x, spaces):
        return self._times_helper(x, spaces, operation=lambda z: z.__rdiv__)
116

117
118
    def _adjoint_inverse_times(self, x, spaces):
        return self._times_helper(x, spaces,
119
                                  operation=lambda z: z.adjoint().__rdiv__)
120
121

    def diagonal(self, bare=False, copy=True):
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
        """ Returns the diagonal of the operator.

        Parameters
        ----------
        bare : boolean
            Whether the returned Field values should be bare or not.
        copy : boolean
            Whether the returned Field should be copied or not.

        Returns
        -------
        out : NIFTy.Field
            the diagonal of the Operator

        See Also
        --------
        """
139
140
141
142
143
144
145
146
147
        if bare:
            diagonal = self._diagonal.weight(power=-1)
        elif copy:
            diagonal = self._diagonal.copy()
        else:
            diagonal = self._diagonal
        return diagonal

    def inverse_diagonal(self, bare=False):
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
        """ Returns the inverse-diagonal of the operator.

        Parameters
        ----------
        bare : boolean
            Whether the returned Field values should be bare or not.

        Returns
        -------
        out : NIFTy.Field
            the inverse-diagonal of the Operator

        See Also
        --------
        """
163
        return 1./self.diagonal(bare=bare, copy=False)
164
165

    def trace(self, bare=False):
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
        """ Returns the trace the operator.

        Parameters
        ----------
        bare : boolean
            Whether the returned Field values should be bare or not.

        Returns
        -------
        out : scalar
            the trace of the Operator

        See Also
        --------
        """
181
182
183
        return self.diagonal(bare=bare, copy=False).sum()

    def inverse_trace(self, bare=False):
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
        """ Returns the inverse-trace of the operator.

        Parameters
        ----------
        bare : boolean
            Whether the returned Field values should be bare or not.

        Returns
        -------
        out : scalar
            the inverse-trace of the Operator

        See Also
        --------
        """
199
        return self.inverse_diagonal(bare=bare).sum()
200
201

    def trace_log(self):
202
203
204
205
206
207
208
209
210
211
212
213
        """ Returns the trave-log of the operator.

        Parameters
        ----------
        Returns
        -------
        out : scalar
            the trace-log of the Operator

        See Also
        --------
        """
214
        log_diagonal = nifty_log(self.diagonal(copy=False))
215
216
217
        return log_diagonal.sum()

    def determinant(self):
218
219
220
221
222
223
224
225
226
227
228
229
        """ Returns the determinant of the operator.

        Parameters
        ----------
        Returns
        -------
        out : scalar
            the determinant of the Operator

        See Also
        --------
        """
230
231
232
        return self.diagonal(copy=False).val.prod()

    def inverse_determinant(self):
233
234
235
236
237
238
239
240
241
242
243
244
        """ Returns the inverse-determinant of the operator.

        Parameters
        ----------
        Returns
        -------
        out : scalar
            the inverse-determinant of the Operator

        See Also
        --------
        """
245
246
247
        return 1/self.determinant()

    def log_determinant(self):
248
249
250
251
252
253
254
255
256
257
258
259
        """ Returns the log-eterminant of the operator.

        Parameters
        ----------
        Returns
        -------
        out : scalar
            the log-determinant of the Operator

        See Also
        --------
        """
260
261
262
263
        return np.log(self.determinant())

    # ---Mandatory properties and methods---

264
265
266
267
    @property
    def domain(self):
        return self._domain

268
    @property
Martin Reinecke's avatar
Martin Reinecke committed
269
270
271
272
    def self_adjoint(self):
        if self._self_adjoint is None:
            self._self_adjoint = (self._diagonal.val.imag == 0).all()
        return self._self_adjoint
273
274
275

    @property
    def unitary(self):
276
277
278
        if self._unitary is None:
            self._unitary = (self._diagonal.val *
                             self._diagonal.val.conjugate() == 1).all()
279
280
281
282
283
        return self._unitary

    # ---Added properties and methods---

    @property
284
    def distribution_strategy(self):
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
        """
        distribution_strategy : string
            Defines the way how the diagonal operator is distributed
            among the nodes.
            Popoular ones are:
                'fftw'
                'all'
                'local'
                'slicing'
                'not'
                'hdf5'

        Notes :
            https://arxiv.org/abs/1606.05385
        """
300
        return self._distribution_strategy
301

302
303
    def _parse_distribution_strategy(self, distribution_strategy, val):
        if distribution_strategy is None:
304
            if isinstance(val, distributed_data_object):
305
                distribution_strategy = val.distribution_strategy
306
            elif isinstance(val, Field):
307
                distribution_strategy = val.distribution_strategy
308
            else:
309
                self.logger.info("Datamodel set to default!")
310
311
                distribution_strategy = gc['default_distribution_strategy']
        elif distribution_strategy not in DISTRIBUTION_STRATEGIES['all']:
312
313
            raise ValueError(
                    "Invalid distribution_strategy!")
314
        return distribution_strategy
315
316

    def set_diagonal(self, diagonal, bare=False, copy=True):
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
        """ Sets the diagonal of the Operator.

        Parameters
        ----------
        diagonal : {scalar, list, array, NIFTy.Field, d2o-object}
            The diagonal entries of the operator.
        bare : boolean
            Indicates whether the diagonal entries are bare or not
            (default: False)
        copy : boolean
            Internal copy of the diagonal (default: True)

        Returns
        -------

        See Also
        --------
        """


337
338
339
        # use the casting functionality from Field to process `diagonal`
        f = Field(domain=self.domain,
                  val=diagonal,
340
                  distribution_strategy=self.distribution_strategy,
341
342
                  copy=copy)

343
        # weight if the given values were `bare` is True
344
        # do inverse weightening if the other way around
345
        if bare:
346
347
348
            # If `copy` is True, we won't change external data by weightening
            # Otherwise, inplace weightening would change the external field
            f.weight(inplace=copy)
349

Martin Reinecke's avatar
Martin Reinecke committed
350
351
        # Reset the self_adjoint property:
        self._self_adjoint = None
352

353
354
        # Reset the unitarity property
        self._unitary = None
355
356
357

        # store the diagonal-field
        self._diagonal = f
358

359
360
    def _times_helper(self, x, spaces, operation):
        # if the domain matches directly
361
        # -> multiply the fields directly
362
        if x.domain == self.domain:
363
364
365
366
367
368
369
            # here the actual multiplication takes place
            return operation(self.diagonal(copy=False))(x)

        # if the distribution_strategy of self is sub-slice compatible to
        # the one of x, reshape the local data of self and apply it directly
        active_axes = []
        if spaces is None:
370
            active_axes = range(len(x.shape))
371
372
373
374
375
376
377
378
379
380
        else:
            for space_index in spaces:
                active_axes += x.domain_axes[space_index]

        axes_local_distribution_strategy = \
            x.val.get_axes_local_distribution_strategy(active_axes)
        if axes_local_distribution_strategy == self.distribution_strategy:
            local_diagonal = self._diagonal.val.get_local_data(copy=False)
        else:
            # create an array that is sub-slice compatible
381
382
            self.logger.warn("The input field is not sub-slice compatible to "
                             "the distribution strategy of the operator.")
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
            redistr_diagonal_val = self._diagonal.val.copy(
                distribution_strategy=axes_local_distribution_strategy)
            local_diagonal = redistr_diagonal_val.get_local_data(copy=False)

        reshaper = [x.shape[i] if i in active_axes else 1
                    for i in xrange(len(x.shape))]
        reshaped_local_diagonal = np.reshape(local_diagonal, reshaper)

        # here the actual multiplication takes place
        local_result = operation(reshaped_local_diagonal)(
                           x.val.get_local_data(copy=False))

        result_field = x.copy_empty(dtype=local_result.dtype)
        result_field.val.set_local_data(local_result, copy=False)
        return result_field