chain_operator.py 5.12 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
#
# NIFTy is being developed at the Max-Planck-Institut fuer Astrophysik
# and financially supported by the Studienstiftung des deutschen Volkes.

Martin Reinecke's avatar
Martin Reinecke committed
19
from __future__ import absolute_import, division, print_function
20

21
import numpy as np
22
23

from ..compat import *
Martin Reinecke's avatar
Martin Reinecke committed
24
from .linear_operator import LinearOperator
Martin Reinecke's avatar
Martin Reinecke committed
25
from .simple_linear_operators import NullOperator
Martin Reinecke's avatar
Martin Reinecke committed
26
27
28


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

Martin Reinecke's avatar
Martin Reinecke committed
31
32
33
    def __init__(self, ops, _callingfrommake=False):
        if not _callingfrommake:
            raise NotImplementedError
Martin Reinecke's avatar
Martin Reinecke committed
34
        super(ChainOperator, self).__init__()
Martin Reinecke's avatar
Martin Reinecke committed
35
36
37
38
39
40
41
42
43
44
45
        self._ops = ops
        self._capability = self._all_ops
        for op in ops:
            self._capability &= op.capability

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

    @staticmethod
    def make(ops):
Martin Reinecke's avatar
Martin Reinecke committed
104
        """Build a ChainOperator (or something simpler if possible),
105
106
107
108
109
110
111
        a sequence of concatenated LinearOperators.

        Parameters
        ----------
        ops: list of LinearOperator
            Individual operators of the chain.
        """
Martin Reinecke's avatar
Martin Reinecke committed
112
        ops = tuple(ops)
Martin Reinecke's avatar
bug fix    
Martin Reinecke committed
113
114
        if len(ops) == 0:
            raise ValueError("ops is empty")
Martin Reinecke's avatar
Martin Reinecke committed
115
116
117
118
        ops = ChainOperator.simplify(ops)
        if len(ops) == 1:
            return ops[0]
        return ChainOperator(ops, _callingfrommake=True)
Martin Reinecke's avatar
Martin Reinecke committed
119
120
121

    @property
    def domain(self):
Martin Reinecke's avatar
Martin Reinecke committed
122
        return self._ops[-1].domain
Martin Reinecke's avatar
Martin Reinecke committed
123
124
125

    @property
    def target(self):
Martin Reinecke's avatar
Martin Reinecke committed
126
        return self._ops[0].target
Martin Reinecke's avatar
Martin Reinecke committed
127

128
129
130
131
132
    def _flip_modes(self, trafo):
        ADJ = self.ADJOINT_BIT
        INV = self.INVERSE_BIT

        if trafo == 0:
Martin Reinecke's avatar
Martin Reinecke committed
133
            return self
134
135
        if trafo == ADJ or trafo == INV:
            return self.make([op._flip_modes(trafo)
Martin Reinecke's avatar
Martin Reinecke committed
136
                              for op in reversed(self._ops)])
137
138
139
        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
140

Martin Reinecke's avatar
Martin Reinecke committed
141
142
    @property
    def capability(self):
Martin Reinecke's avatar
Martin Reinecke committed
143
        return self._capability
Martin Reinecke's avatar
Martin Reinecke committed
144
145
146

    def apply(self, x, mode):
        self._check_mode(mode)
Martin Reinecke's avatar
Martin Reinecke committed
147
148
149
150
        t_ops = self._ops if mode & self._backwards else reversed(self._ops)
        for op in t_ops:
            x = op.apply(x, mode)
        return x