sum_operator.py 8.15 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-2019 Max-Planck-Society
Martin Reinecke's avatar
Martin Reinecke committed
15
#
16
# NIFTy is being developed at the Max-Planck-Institut fuer Astrophysik.
17

Philipp Arras's avatar
Philipp Arras committed
18 19
from collections import defaultdict

20 21
import numpy as np

Martin Reinecke's avatar
Martin Reinecke committed
22
from ..sugar import domain_union
Philipp Arras's avatar
Philipp Arras committed
23 24 25
from ..utilities import indent
from .block_diagonal_operator import BlockDiagonalOperator
from .linear_operator import LinearOperator
Martin Reinecke's avatar
Martin Reinecke committed
26 27 28


class SumOperator(LinearOperator):
29 30 31 32 33 34
    """Class representing sums of operators.

    Notes
    -----
    This operator has to be called using the `make` method.
    """
Martin Reinecke's avatar
Martin Reinecke committed
35

Martin Reinecke's avatar
Martin Reinecke committed
36
    def __init__(self, ops, neg, dom, tgt, _callingfrommake=False):
37 38 39 40
        if not _callingfrommake:
            raise NotImplementedError
        self._ops = ops
        self._neg = neg
Martin Reinecke's avatar
Martin Reinecke committed
41 42
        self._domain = dom
        self._target = tgt
43 44 45 46 47 48 49 50
        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
Martin Reinecke's avatar
Martin Reinecke committed
51 52

        # unpack SumOperators
53 54
        opsnew = []
        negnew = []
55
        for op, ng in zip(ops, neg):
56 57 58
            if isinstance(op, SumOperator):
                opsnew += op._ops
                if ng:
Martin Reinecke's avatar
fixes  
Martin Reinecke committed
59
                    negnew += [not n for n in op._neg]
60
                else:
Martin Reinecke's avatar
fixes  
Martin Reinecke committed
61
                    negnew += list(op._neg)
Martin Reinecke's avatar
Martin Reinecke committed
62 63 64
# FIXME: this needs some more work to keep the domain and target unchanged!
#            elif isinstance(op, NullOperator):
#                pass
65 66 67 68 69
            else:
                opsnew.append(op)
                negnew.append(ng)
        ops = opsnew
        neg = negnew
Martin Reinecke's avatar
Martin Reinecke committed
70 71 72

        # sort operators according to domains
        sorted = defaultdict(list)
73
        for op, ng in zip(ops, neg):
Martin Reinecke's avatar
Martin Reinecke committed
74 75 76 77 78 79 80 81 82 83 84 85 86
            sorted[(op.domain, op.target)].append((op, ng))

        xxops = []
        xxneg = []
        for opset in sorted.values():
            # collect ScalingOperators
            sum = 0.
            opsnew = []
            negnew = []

            for op, ng in opset:
                if isinstance(op, ScalingOperator):
                    sum += op._factor * (-1 if ng else 1)
87
                else:
Martin Reinecke's avatar
Martin Reinecke committed
88
                    opsnew.append(op)
Martin Reinecke's avatar
Martin Reinecke committed
89 90 91 92 93 94 95 96 97 98 99
                    negnew.append(ng)

            lastdom = opset[0][0].domain
            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)
                        opsnew[i] = opsnew[i]._add(sum)
                        sum = 0.
                        break
Martin Reinecke's avatar
fix  
Martin Reinecke committed
100
            if sum != 0 or len(opsnew) == 0:
Martin Reinecke's avatar
Martin Reinecke committed
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
                # have to add the scaling operator at the end
                opsnew.append(ScalingOperator(sum, lastdom))
                negnew.append(False)

            ops = opsnew
            neg = negnew
            # Step 4: combine DiagonalOperators where possible
            processed = [False] * len(ops)
            opsnew = []
            negnew = []
            for i in range(len(ops)):
                if not processed[i]:
                    if isinstance(ops[i], DiagonalOperator):
                        op = ops[i]
                        opneg = neg[i]
                        for j in range(i+1, len(ops)):
                            if isinstance(ops[j], DiagonalOperator):
                                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

            # combine BlockDiagonalOperators where possible
            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])
            xxops += opsnew
            xxneg += negnew

        dom = domain_union([op.domain for op in xxops])
        tgt = domain_union([op.target for op in xxops])
        return xxops, xxneg, dom, tgt
154 155 156

    @staticmethod
    def make(ops, neg):
157 158 159 160 161 162
        """Build a SumOperator (or something simpler if possible)

        Parameters
        ----------
        ops: list of LinearOperator
            Individual operators of the sum.
Martin Reinecke's avatar
typo  
Martin Reinecke committed
163
        neg: list of bool
164
            Same length as ops.
Martin Reinecke's avatar
typo  
Martin Reinecke committed
165
            If True then the equivalent operator gets a minus in the sum.
166
        """
167 168
        ops = tuple(ops)
        neg = tuple(neg)
Martin Reinecke's avatar
bug fix  
Martin Reinecke committed
169 170
        if len(ops) == 0:
            raise ValueError("ops is empty")
171
        if len(ops) != len(neg):
172
            raise ValueError("length mismatch between ops and neg")
Martin Reinecke's avatar
Martin Reinecke committed
173
        ops, neg, dom, tgt = SumOperator.simplify(ops, neg)
Martin Reinecke's avatar
Martin Reinecke committed
174 175
        if len(ops) == 1:
            return -ops[0] if neg[0] else ops[0]
Martin Reinecke's avatar
Martin Reinecke committed
176
        return SumOperator(ops, neg, dom, tgt, _callingfrommake=True)
Martin Reinecke's avatar
Martin Reinecke committed
177

Martin Reinecke's avatar
Martin Reinecke committed
178 179 180 181
    @property
    def adjoint(self):
        return self.make([op.adjoint for op in self._ops], self._neg)

Martin Reinecke's avatar
Martin Reinecke committed
182 183
    def apply(self, x, mode):
        self._check_mode(mode)
184 185
        res = None
        for op, neg in zip(self._ops, self._neg):
Martin Reinecke's avatar
Martin Reinecke committed
186
            tmp = op.apply(x.extract(op._dom(mode)), mode)
187
            if res is None:
Martin Reinecke's avatar
Martin Reinecke committed
188
                res = -tmp if neg else tmp
Martin Reinecke's avatar
Martin Reinecke committed
189
            else:
Martin Reinecke's avatar
Martin Reinecke committed
190
                res = res.flexible_addsub(tmp, neg)
Martin Reinecke's avatar
Martin Reinecke committed
191
        return res
Martin Reinecke's avatar
Martin Reinecke committed
192

193 194
    def draw_sample(self, from_inverse=False, dtype=np.float64):
        if from_inverse:
195 196
            raise NotImplementedError(
                "cannot draw from inverse of this operator")
Martin Reinecke's avatar
Martin Reinecke committed
197 198
        res = None
        for op in self._ops:
199 200 201
            from .simple_linear_operators import NullOperator
            if isinstance(op, NullOperator):
                continue
Martin Reinecke's avatar
Martin Reinecke committed
202 203 204
            tmp = op.draw_sample(from_inverse, dtype)
            res = tmp if res is None else res.unite(tmp)
        return res
Martin Reinecke's avatar
Martin Reinecke committed
205 206 207 208

    def __repr__(self):
        subs = "\n".join(sub.__repr__() for sub in self._ops)
        return "SumOperator:\n"+indent(subs)
209

Martin Reinecke's avatar
cleanup  
Martin Reinecke committed
210
    def _simplify_for_constant_input_nontrivial(self, c_inp):
Martin Reinecke's avatar
Martin Reinecke committed
211 212
        f = []
        o = []
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
        for op in self._ops:
            tf, to = op.simplify_for_constant_input(
                c_inp.extract_part(op.domain))
            f.append(tf)
            o.append(to)

        from ..multi_domain import MultiDomain
        if not isinstance(self._target, MultiDomain):
            fullop = None
            for to, n in zip(o, self._neg):
                op = to if not n else -to
                fullop = op if fullop is None else fullop + op
            return None, fullop

        from .operator import _ConstCollector
        cc = _ConstCollector()
        fullop = None
        for tf, to, n in zip(f, o, self._neg):
            cc.add(tf, to.target)
            op = to if not n else -to
            fullop = op if fullop is None else fullop + op
        return cc.constfield, fullop