diagonal_operator.py 6.32 KB
Newer Older
1
2
3
4
5
6
7
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.
#
# 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/>.
Theo Steininger's avatar
Theo Steininger committed
13
#
Philipp Arras's avatar
Philipp Arras committed
14
# Copyright(C) 2013-2020 Max-Planck-Society
Theo Steininger's avatar
Theo Steininger committed
15
#
16
# NIFTy is being developed at the Max-Planck-Institut fuer Astrophysik.
17

18
import numpy as np
19

Martin Reinecke's avatar
stage 1    
Martin Reinecke committed
20
from .. import utilities
Martin Reinecke's avatar
Martin Reinecke committed
21
from ..domain_tuple import DomainTuple
22
from ..field import Field
Martin Reinecke's avatar
Martin Reinecke committed
23
from .endomorphic_operator import EndomorphicOperator
Martin Reinecke's avatar
Martin Reinecke committed
24

25
26

class DiagonalOperator(EndomorphicOperator):
27
    """Represents a :class:`LinearOperator` which is diagonal.
Theo Steininger's avatar
Theo Steininger committed
28

Martin Reinecke's avatar
Martin Reinecke committed
29
    The NIFTy DiagonalOperator class is a subclass derived from the
Philipp Arras's avatar
Docs    
Philipp Arras committed
30
31
    :class:`EndomorphicOperator`. It multiplies an input field pixel-wise with
    its diagonal.
32

33
34
    Parameters
    ----------
Martin Reinecke's avatar
Martin Reinecke committed
35
    diagonal : Field
Martin Reinecke's avatar
docs    
Martin Reinecke committed
36
37
        The diagonal entries of the operator.
    domain : Domain, tuple of Domain or DomainTuple, optional
Philipp Arras's avatar
Philipp Arras committed
38
        The domain on which the Operator's input Field is defined.
39
        If None, use the domain of "diagonal".
Martin Reinecke's avatar
docs    
Martin Reinecke committed
40
    spaces : int or tuple of int, optional
41
42
        The elements of "domain" on which the operator acts.
        If None, it acts on all elements.
Martin Reinecke's avatar
Martin Reinecke committed
43
44
45
46
47
48
49
50
51
52

    Notes
    -----
    Formally, this operator always supports all operation modes (times,
    adjoint_times, inverse_times and inverse_adjoint_times), even if there
    are diagonal elements with value 0 or infinity. It is the user's
    responsibility to apply the operator only in appropriate ways (e.g. call
    inverse_times only if there are no zeros on the diagonal).

    This shortcoming will hopefully be fixed in the future.
53
54
    """

Martin Reinecke's avatar
Martin Reinecke committed
55
    def __init__(self, diagonal, domain=None, spaces=None):
Martin Reinecke's avatar
Martin Reinecke committed
56
57
        if not isinstance(diagonal, Field):
            raise TypeError("Field object required")
58
59
60
61
62
63
        if domain is None:
            self._domain = diagonal.domain
        else:
            self._domain = DomainTuple.make(domain)
        if spaces is None:
            self._spaces = None
Martin Reinecke's avatar
Martin Reinecke committed
64
            if diagonal.domain != self._domain:
65
66
                raise ValueError("domain mismatch")
        else:
67
68
            self._spaces = utilities.parse_spaces(spaces, len(self._domain))
            if len(self._spaces) != len(diagonal.domain):
69
                raise ValueError("spaces and domain must have the same length")
Martin Reinecke's avatar
Martin Reinecke committed
70
            for i, j in enumerate(self._spaces):
71
72
                if diagonal.domain[i] != self._domain[j]:
                    raise ValueError("domain mismatch")
Martin Reinecke's avatar
Martin Reinecke committed
73
            if self._spaces == tuple(range(len(self._domain))):
Martin Reinecke's avatar
tweak    
Martin Reinecke committed
74
75
76
77
78
79
80
                self._spaces = None  # shortcut

        if self._spaces is not None:
            active_axes = []
            for space_index in self._spaces:
                active_axes += self._domain.axes[space_index]

Martin Reinecke's avatar
stage 1    
Martin Reinecke committed
81
            self._ldiag = diagonal.val
Martin Reinecke's avatar
tweak    
Martin Reinecke committed
82
            self._reshaper = [shp if i in active_axes else 1
Martin Reinecke's avatar
stage 1    
Martin Reinecke committed
83
                              for i, shp in enumerate(self._domain.shape)]
Martin Reinecke's avatar
Martin Reinecke committed
84
85
            self._ldiag = self._ldiag.reshape(self._reshaper)
        else:
Martin Reinecke's avatar
stage 1    
Martin Reinecke committed
86
            self._ldiag = diagonal.val
87
        self._fill_rest()
88

89
    def _fill_rest(self):
Martin Reinecke's avatar
Martin Reinecke committed
90
        self._ldiag.flags.writeable = False
Martin Reinecke's avatar
Martin Reinecke committed
91
        self._complex = utilities.iscomplextype(self._ldiag.dtype)
Martin Reinecke's avatar
Martin Reinecke committed
92
        self._capability = self._all_ops
93
        if not self._complex:
Martin Reinecke's avatar
stage 1    
Martin Reinecke committed
94
            self._diagmin = self._ldiag.min()
Martin Reinecke's avatar
Martin Reinecke committed
95

96
    def _from_ldiag(self, spc, ldiag):
Martin Reinecke's avatar
Martin Reinecke committed
97
98
99
100
101
102
        res = DiagonalOperator.__new__(DiagonalOperator)
        res._domain = self._domain
        if self._spaces is None or spc is None:
            res._spaces = None
        else:
            res._spaces = tuple(set(self._spaces) | set(spc))
Martin Reinecke's avatar
Martin Reinecke committed
103
        res._ldiag = np.array(ldiag)
104
        res._fill_rest()
Martin Reinecke's avatar
Martin Reinecke committed
105
106
107
108
109
        return res

    def _scale(self, fct):
        if not np.isscalar(fct):
            raise TypeError("scalar value required")
110
        return self._from_ldiag((), self._ldiag*fct)
Martin Reinecke's avatar
Martin Reinecke committed
111
112
113
114

    def _add(self, sum):
        if not np.isscalar(sum):
            raise TypeError("scalar value required")
115
        return self._from_ldiag((), self._ldiag+sum)
Martin Reinecke's avatar
Martin Reinecke committed
116
117
118
119

    def _combine_prod(self, op):
        if not isinstance(op, DiagonalOperator):
            raise TypeError("DiagonalOperator required")
120
        return self._from_ldiag(op._spaces, self._ldiag*op._ldiag)
Martin Reinecke's avatar
Martin Reinecke committed
121
122
123
124

    def _combine_sum(self, op, selfneg, opneg):
        if not isinstance(op, DiagonalOperator):
            raise TypeError("DiagonalOperator required")
125
126
127
        tdiag = (self._ldiag * (-1 if selfneg else 1) +
                 op._ldiag * (-1 if opneg else 1))
        return self._from_ldiag(op._spaces, tdiag)
128

Martin Reinecke's avatar
Martin Reinecke committed
129
130
    def apply(self, x, mode):
        self._check_input(x, mode)
131
132
        # shortcut for most common cases
        if mode == 1 or (not self._complex and mode == 2):
Martin Reinecke's avatar
stage2    
Martin Reinecke committed
133
            return Field(x.domain, x.val*self._ldiag)
134
135
136
137
138
139

        xdiag = self._ldiag
        if self._complex and (mode & 10):  # adjoint or inverse adjoint
            xdiag = xdiag.conj()

        if mode & 3:
Martin Reinecke's avatar
stage2    
Martin Reinecke committed
140
141
            return Field(x.domain, x.val*xdiag)
        return Field(x.domain, x.val/xdiag)
142

143
    def _flip_modes(self, trafo):
Martin Reinecke's avatar
Martin Reinecke committed
144
145
        if trafo == self.ADJOINT_BIT and not self._complex:  # shortcut
            return self
146
147
148
149
150
151
        xdiag = self._ldiag
        if self._complex and (trafo & self.ADJOINT_BIT):
            xdiag = xdiag.conj()
        if trafo & self.INVERSE_BIT:
            xdiag = 1./xdiag
        return self._from_ldiag((), xdiag)
152

Martin Reinecke's avatar
Martin Reinecke committed
153
154
    def process_sample(self, samp, from_inverse):
        if (self._complex or (self._diagmin < 0.) or
155
                (self._diagmin == 0. and from_inverse)):
Martin Reinecke's avatar
Martin Reinecke committed
156
            raise ValueError("operator not positive definite")
157
        if from_inverse:
Martin Reinecke's avatar
stage 1    
Martin Reinecke committed
158
            res = samp.val/np.sqrt(self._ldiag)
159
        else:
Martin Reinecke's avatar
stage 1    
Martin Reinecke committed
160
161
            res = samp.val*np.sqrt(self._ldiag)
        return Field(self._domain, res)
Martin Reinecke's avatar
Martin Reinecke committed
162

Philipp Arras's avatar
Philipp Arras committed
163
    def draw_sample_with_dtype(self, dtype, from_inverse=False):
164
        res = Field.from_random(domain=self._domain, random_type="normal", dtype=dtype)
Martin Reinecke's avatar
Martin Reinecke committed
165
166
167
        return self.process_sample(res, from_inverse)

    def __repr__(self):
Martin Reinecke's avatar
Martin Reinecke committed
168
        return "DiagonalOperator"