sum_operator.py 6.62 KB
Newer Older
Martin Reinecke's avatar
Martin Reinecke committed
1
2
3
4
5
6
7
8
9
10
11
12
13
# 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/>.
#
14
# Copyright(C) 2013-2018 Max-Planck-Society
Martin Reinecke's avatar
Martin Reinecke committed
15
16
17
18
19
#
# NIFTy is being developed at the Max-Planck-Institut fuer Astrophysik
# and financially supported by the Studienstiftung des deutschen Volkes.

from .linear_operator import LinearOperator
Martin Reinecke's avatar
Martin Reinecke committed
20
import numpy as np
Martin Reinecke's avatar
Martin Reinecke committed
21
22
23


class SumOperator(LinearOperator):
Martin Reinecke's avatar
Martin Reinecke committed
24
25
    """Class representing sums of operators."""

Martin Reinecke's avatar
Martin Reinecke committed
26
    def __init__(self, ops, neg, dom, tgt, _callingfrommake=False):
27
28
        if not _callingfrommake:
            raise NotImplementedError
Martin Reinecke's avatar
Martin Reinecke committed
29
        super(SumOperator, self).__init__()
30
31
        self._ops = ops
        self._neg = neg
Martin Reinecke's avatar
Martin Reinecke committed
32
33
        self._domain = dom
        self._target = tgt
34
35
36
37
38
39
40
41
42
        self._capability = self.TIMES | self.ADJOINT_TIMES
        for op in ops:
            self._capability &= op.capability

    @staticmethod
    def simplify(ops, neg):
        from .scaling_operator import ScalingOperator
        from .diagonal_operator import DiagonalOperator
        # Step 1: verify domains
Martin Reinecke's avatar
Martin Reinecke committed
43
44
        dom = ops[0].domain
        tgt = ops[0].target
45
        for op in ops[1:]:
Martin Reinecke's avatar
Martin Reinecke committed
46
47
48
            dom = dom.unitedWith(op.domain)
            tgt = tgt.unitedWith(op.target)

49
50
51
        # Step 2: unpack SumOperators
        opsnew = []
        negnew = []
52
        for op, ng in zip(ops, neg):
53
54
55
            if isinstance(op, SumOperator):
                opsnew += op._ops
                if ng:
Martin Reinecke's avatar
fixes  
Martin Reinecke committed
56
                    negnew += [not n for n in op._neg]
57
                else:
Martin Reinecke's avatar
fixes  
Martin Reinecke committed
58
                    negnew += list(op._neg)
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
            else:
                opsnew.append(op)
                negnew.append(ng)
        ops = opsnew
        neg = negnew
        # Step 3: collect ScalingOperators
        sum = 0.
        opsnew = []
        negnew = []
        lastdom = ops[-1].domain
        for op, ng in zip(ops, neg):
            if isinstance(op, ScalingOperator):
                sum += op._factor * (-1 if ng else 1)
            else:
                opsnew.append(op)
                negnew.append(ng)
        if sum != 0.:
            # try to absorb the factor into a DiagonalOperator
            for i in range(len(opsnew)):
                if isinstance(opsnew[i], DiagonalOperator):
                    sum *= (-1 if negnew[i] else 1)
Martin Reinecke's avatar
Martin Reinecke committed
80
                    opsnew[i] = opsnew[i]._add(sum)
81
82
83
84
85
                    sum = 0.
                    break
        if sum != 0:
            # have to add the scaling operator at the end
            opsnew.append(ScalingOperator(sum, lastdom))
86
            negnew.append(False)
87
88
89
        ops = opsnew
        neg = negnew
        # Step 4: combine DiagonalOperators where possible
90
91
92
93
94
95
        processed = [False] * len(ops)
        opsnew = []
        negnew = []
        for i in range(len(ops)):
            if not processed[i]:
                if isinstance(ops[i], DiagonalOperator):
Martin Reinecke's avatar
Martin Reinecke committed
96
97
                    op = ops[i]
                    opneg = neg[i]
98
                    for j in range(i+1, len(ops)):
Martin Reinecke's avatar
Martin Reinecke committed
99
100
101
                        if isinstance(ops[j], DiagonalOperator):
                            op = op._combine_sum(ops[j], opneg, neg[j])
                            opneg = False
102
                            processed[j] = True
Martin Reinecke's avatar
Martin Reinecke committed
103
104
                    opsnew.append(op)
                    negnew.append(opneg)
105
106
107
108
109
                else:
                    opsnew.append(ops[i])
                    negnew.append(neg[i])
        ops = opsnew
        neg = negnew
Martin Reinecke's avatar
Martin Reinecke committed
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
        # Step 5: combine BlockDiagonalOperators where possible
        from ..multi.block_diagonal_operator import BlockDiagonalOperator
        processed = [False] * len(ops)
        opsnew = []
        negnew = []
        for i in range(len(ops)):
            if not processed[i]:
                if isinstance(ops[i], BlockDiagonalOperator):
                    op = ops[i]
                    opneg = neg[i]
                    for j in range(i+1, len(ops)):
                        if isinstance(ops[j], BlockDiagonalOperator):
                            op = op._combine_sum(ops[j], opneg, neg[j])
                            opneg = False
                            processed[j] = True
                    opsnew.append(op)
                    negnew.append(opneg)
                else:
                    opsnew.append(ops[i])
                    negnew.append(neg[i])
        ops = opsnew
        neg = negnew
Martin Reinecke's avatar
Martin Reinecke committed
132
        return ops, neg, dom, tgt
133
134
135

    @staticmethod
    def make(ops, neg):
136
137
138
139
140
141
142
143
144
145
        """Build a SumOperator (or something simpler if possible)

        Parameters
        ----------
        ops: list of LinearOperator
            Individual operators of the sum.
        negs: list of bool
            Same length as ops.
            If True then the equivalent operator gets a minus in the sum. 
        """
146
147
        ops = tuple(ops)
        neg = tuple(neg)
Martin Reinecke's avatar
bug fix  
Martin Reinecke committed
148
149
        if len(ops) == 0:
            raise ValueError("ops is empty")
150
        if len(ops) != len(neg):
151
            raise ValueError("length mismatch between ops and neg")
Martin Reinecke's avatar
Martin Reinecke committed
152
        ops, neg, dom, tgt = SumOperator.simplify(ops, neg)
153
154
        if len(ops) == 1 and not neg[0]:
            return ops[0]
Martin Reinecke's avatar
Martin Reinecke committed
155
        return SumOperator(ops, neg, dom, tgt, _callingfrommake=True)
Martin Reinecke's avatar
Martin Reinecke committed
156
157
158

    @property
    def domain(self):
Martin Reinecke's avatar
Martin Reinecke committed
159
        return self._domain
Martin Reinecke's avatar
Martin Reinecke committed
160
161
162

    @property
    def target(self):
Martin Reinecke's avatar
Martin Reinecke committed
163
        return self._target
Martin Reinecke's avatar
Martin Reinecke committed
164

Martin Reinecke's avatar
Martin Reinecke committed
165
166
167
168
    @property
    def adjoint(self):
        return self.make([op.adjoint for op in self._ops], self._neg)

Martin Reinecke's avatar
Martin Reinecke committed
169
170
    @property
    def capability(self):
Martin Reinecke's avatar
Martin Reinecke committed
171
        return self._capability
Martin Reinecke's avatar
Martin Reinecke committed
172
173
174

    def apply(self, x, mode):
        self._check_mode(mode)
Martin Reinecke's avatar
Martin Reinecke committed
175
176
177
178
179
180
181
182
183
        for i, op in enumerate(self._ops):
            if i == 0:
                res = -op.apply(x, mode) if self._neg[i] else op.apply(x, mode)
            else:
                if self._neg[i]:
                    res -= op.apply(x, mode)
                else:
                    res += op.apply(x, mode)
        return res
Martin Reinecke's avatar
Martin Reinecke committed
184

185
186
    def draw_sample(self, from_inverse=False, dtype=np.float64):
        if from_inverse:
187
188
            raise NotImplementedError(
                "cannot draw from inverse of this operator")
189
        res = self._ops[0].draw_sample(from_inverse, dtype)
Martin Reinecke's avatar
Martin Reinecke committed
190
        for op in self._ops[1:]:
191
            res += op.draw_sample(from_inverse, dtype)
Martin Reinecke's avatar
Martin Reinecke committed
192
        return res