chain_operator.py 5.24 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
from .. import utilities
19
from ..compat import *
Philipp Arras's avatar
Philipp Arras committed
20
from .diagonal_operator import DiagonalOperator
Martin Reinecke's avatar
Martin Reinecke committed
21
from .linear_operator import LinearOperator
Martin Reinecke's avatar
Martin Reinecke committed
22
from .scaling_operator import ScalingOperator
Martin Reinecke's avatar
Martin Reinecke committed
23
from .simple_linear_operators import NullOperator
Martin Reinecke's avatar
Martin Reinecke committed
24
25
26


class ChainOperator(LinearOperator):
Martin Reinecke's avatar
Martin Reinecke committed
27
28
    """Class representing chains of operators."""

Martin Reinecke's avatar
Martin Reinecke committed
29
30
31
32
33
34
35
    def __init__(self, ops, _callingfrommake=False):
        if not _callingfrommake:
            raise NotImplementedError
        self._ops = ops
        self._capability = self._all_ops
        for op in ops:
            self._capability &= op.capability
Martin Reinecke's avatar
Martin Reinecke committed
36
37
        self._domain = self._ops[-1].domain
        self._target = self._ops[0].target
Martin Reinecke's avatar
Martin Reinecke committed
38
39
40

    @staticmethod
    def simplify(ops):
Martin Reinecke's avatar
Martin Reinecke committed
41
        # verify domains
Philipp Arras's avatar
Philipp Arras committed
42
43
        for i in range(len(ops) - 1):
            if ops[i + 1].target != ops[i].domain:
Martin Reinecke's avatar
Martin Reinecke committed
44
                raise ValueError("domain mismatch")
Martin Reinecke's avatar
Martin Reinecke committed
45
        # unpack ChainOperators
Martin Reinecke's avatar
Martin Reinecke committed
46
47
        opsnew = []
        for op in ops:
Martin Reinecke's avatar
Martin Reinecke committed
48
            opsnew += op._ops if isinstance(op, ChainOperator) else [op]
Martin Reinecke's avatar
Martin Reinecke committed
49
        ops = opsnew
Martin Reinecke's avatar
Martin Reinecke committed
50
        # check for NullOperators
Martin Reinecke's avatar
Martin Reinecke committed
51
52
        if any(isinstance(op, NullOperator) for op in ops):
            ops = (NullOperator(ops[-1].domain, ops[0].target),)
Martin Reinecke's avatar
Martin Reinecke committed
53
        # collect ScalingOperators
Martin Reinecke's avatar
Martin Reinecke committed
54
55
56
57
        fct = 1.
        opsnew = []
        lastdom = ops[-1].domain
        for op in ops:
Martin Reinecke's avatar
Martin Reinecke committed
58
59
            if (isinstance(op, ScalingOperator) and op._factor.imag == 0):
                fct *= op._factor.real
Martin Reinecke's avatar
Martin Reinecke committed
60
61
62
63
64
65
            else:
                opsnew.append(op)
        if fct != 1.:
            # try to absorb the factor into a DiagonalOperator
            for i in range(len(opsnew)):
                if isinstance(opsnew[i], DiagonalOperator):
Martin Reinecke's avatar
Martin Reinecke committed
66
                    opsnew[i] = opsnew[i]._scale(fct)
Martin Reinecke's avatar
Martin Reinecke committed
67
68
                    fct = 1.
                    break
Martin Reinecke's avatar
bug fix  
Martin Reinecke committed
69
        if fct != 1 or len(opsnew) == 0:
Martin Reinecke's avatar
Martin Reinecke committed
70
71
72
            # have to add the scaling operator at the end
            opsnew.append(ScalingOperator(fct, lastdom))
        ops = opsnew
Martin Reinecke's avatar
Martin Reinecke committed
73
        # combine DiagonalOperators where possible
Martin Reinecke's avatar
Martin Reinecke committed
74
75
        opsnew = []
        for op in ops:
Philipp Arras's avatar
Philipp Arras committed
76
77
            if (len(opsnew) > 0 and isinstance(opsnew[-1], DiagonalOperator)
                    and isinstance(op, DiagonalOperator)):
Martin Reinecke's avatar
Martin Reinecke committed
78
                opsnew[-1] = opsnew[-1]._combine_prod(op)
Martin Reinecke's avatar
Martin Reinecke committed
79
80
81
            else:
                opsnew.append(op)
        ops = opsnew
Martin Reinecke's avatar
Martin Reinecke committed
82
        # combine BlockDiagonalOperators where possible
Martin Reinecke's avatar
Martin Reinecke committed
83
        from .block_diagonal_operator import BlockDiagonalOperator
Martin Reinecke's avatar
Martin Reinecke committed
84
85
        opsnew = []
        for op in ops:
Philipp Arras's avatar
Philipp Arras committed
86
87
88
            if (len(opsnew) > 0
                    and isinstance(opsnew[-1], BlockDiagonalOperator)
                    and isinstance(op, BlockDiagonalOperator)):
Martin Reinecke's avatar
Martin Reinecke committed
89
90
91
92
                opsnew[-1] = opsnew[-1]._combine_chain(op)
            else:
                opsnew.append(op)
        ops = opsnew
Martin Reinecke's avatar
Martin Reinecke committed
93
94
95
96
        return ops

    @staticmethod
    def make(ops):
Martin Reinecke's avatar
Martin Reinecke committed
97
        """Build a ChainOperator (or something simpler if possible),
98
99
100
101
102
103
104
        a sequence of concatenated LinearOperators.

        Parameters
        ----------
        ops: list of LinearOperator
            Individual operators of the chain.
        """
Martin Reinecke's avatar
Martin Reinecke committed
105
        ops = tuple(ops)
Martin Reinecke's avatar
bug fix  
Martin Reinecke committed
106
107
        if len(ops) == 0:
            raise ValueError("ops is empty")
Martin Reinecke's avatar
Martin Reinecke committed
108
109
110
111
        ops = ChainOperator.simplify(ops)
        if len(ops) == 1:
            return ops[0]
        return ChainOperator(ops, _callingfrommake=True)
Martin Reinecke's avatar
Martin Reinecke committed
112

113
114
115
116
117
    def _flip_modes(self, trafo):
        ADJ = self.ADJOINT_BIT
        INV = self.INVERSE_BIT

        if trafo == 0:
Martin Reinecke's avatar
Martin Reinecke committed
118
            return self
119
        if trafo == ADJ or trafo == INV:
Philipp Arras's avatar
Philipp Arras committed
120
121
            return self.make(
                [op._flip_modes(trafo) for op in reversed(self._ops)])
122
123
124
        if trafo == ADJ | INV:
            return self.make([op._flip_modes(trafo) for op in self._ops])
        raise ValueError("invalid operator transformation")
Martin Reinecke's avatar
Martin Reinecke committed
125

Martin Reinecke's avatar
Martin Reinecke committed
126
127
    def apply(self, x, mode):
        self._check_mode(mode)
Martin Reinecke's avatar
Martin Reinecke committed
128
129
130
131
        t_ops = self._ops if mode & self._backwards else reversed(self._ops)
        for op in t_ops:
            x = op.apply(x, mode)
        return x
Martin Reinecke's avatar
Martin Reinecke committed
132

133
134
135
    def __repr__(self):
        subs = "\n".join(sub.__repr__() for sub in self._ops)
        return "ChainOperator:\n" + utilities.indent(subs)
Philipp Arras's avatar
Philipp Arras committed
136

Martin Reinecke's avatar
Martin Reinecke committed
137
138
139
140
141
142
143
144
145
146
#     def draw_sample(self, from_inverse=False, dtype=np.float64):
#         from ..sugar import from_random
#         if len(self._ops) == 1:
#             return self._ops[0].draw_sample(from_inverse, dtype)
#
#         samp = from_random(random_type="normal", domain=self._domain,
#                            dtype=dtype)
#         for op in self._ops:
#             samp = op.process_sample(samp, from_inverse)
#         return samp