linearization.py 8.19 KB
Newer Older
Martin Reinecke's avatar
Martin Reinecke committed
1
2
3
4
import numpy as np

from .compat import *
from .field import Field
Martin Reinecke's avatar
Martin Reinecke committed
5
from .multi_field import MultiField
Martin Reinecke's avatar
Martin Reinecke committed
6
7
8
9
from .sugar import makeOp


class Linearization(object):
10
    def __init__(self, val, jac, metric=None, want_metric=False):
Martin Reinecke's avatar
Martin Reinecke committed
11
12
        self._val = val
        self._jac = jac
Martin Reinecke's avatar
Martin Reinecke committed
13
14
        if self._val.domain != self._jac.target:
            raise ValueError("domain mismatch")
15
        self._want_metric = want_metric
Martin Reinecke's avatar
Martin Reinecke committed
16
17
        self._metric = metric

18
19
20
    def new(self, val, jac, metric=None):
        return Linearization(val, jac, metric, self._want_metric)

Martin Reinecke's avatar
Martin Reinecke committed
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
    @property
    def domain(self):
        return self._jac.domain

    @property
    def target(self):
        return self._jac.target

    @property
    def val(self):
        return self._val

    @property
    def jac(self):
        return self._jac

Martin Reinecke's avatar
Martin Reinecke committed
37
38
39
    @property
    def gradient(self):
        """Only available if target is a scalar"""
Martin Reinecke's avatar
Martin Reinecke committed
40
        return self._jac.adjoint_times(Field.scalar(1.))
Martin Reinecke's avatar
Martin Reinecke committed
41

42
43
44
45
    @property
    def want_metric(self):
        return self._want_metric

Martin Reinecke's avatar
Martin Reinecke committed
46
47
    @property
    def metric(self):
Martin Reinecke's avatar
Martin Reinecke committed
48
        """Only available if target is a scalar"""
Martin Reinecke's avatar
Martin Reinecke committed
49
50
        return self._metric

Martin Reinecke's avatar
Martin Reinecke committed
51
    def __getitem__(self, name):
Martin Reinecke's avatar
Martin Reinecke committed
52
53
        from .operators.simple_linear_operators import ducktape
        return self.new(self._val[name], ducktape(None, self.domain, name))
Martin Reinecke's avatar
Martin Reinecke committed
54

Martin Reinecke's avatar
Martin Reinecke committed
55
    def __neg__(self):
56
57
        return self.new(-self._val, -self._jac,
                        None if self._metric is None else -self._metric)
Martin Reinecke's avatar
Martin Reinecke committed
58

Martin Reinecke's avatar
Martin Reinecke committed
59
    def conjugate(self):
60
        return self.new(
Martin Reinecke's avatar
Martin Reinecke committed
61
62
63
64
65
            self._val.conjugate(), self._jac.conjugate(),
            None if self._metric is None else self._metric.conjugate())

    @property
    def real(self):
66
        return self.new(self._val.real, self._jac.real)
Martin Reinecke's avatar
Martin Reinecke committed
67

Martin Reinecke's avatar
Martin Reinecke committed
68
    def _myadd(self, other, neg):
Martin Reinecke's avatar
Martin Reinecke committed
69
70
71
        if isinstance(other, Linearization):
            met = None
            if self._metric is not None and other._metric is not None:
Martin Reinecke's avatar
Martin Reinecke committed
72
                met = self._metric._myadd(other._metric, neg)
73
            return self.new(
Martin Reinecke's avatar
Martin Reinecke committed
74
75
                self._val.flexible_addsub(other._val, neg),
                self._jac._myadd(other._jac, neg), met)
Martin Reinecke's avatar
Martin Reinecke committed
76
        if isinstance(other, (int, float, complex, Field, MultiField)):
Martin Reinecke's avatar
Martin Reinecke committed
77
            if neg:
78
                return self.new(self._val-other, self._jac, self._metric)
Martin Reinecke's avatar
Martin Reinecke committed
79
            else:
80
                return self.new(self._val+other, self._jac, self._metric)
Martin Reinecke's avatar
Martin Reinecke committed
81
82
83

    def __add__(self, other):
        return self._myadd(other, False)
Martin Reinecke's avatar
Martin Reinecke committed
84
85

    def __radd__(self, other):
Martin Reinecke's avatar
Martin Reinecke committed
86
        return self._myadd(other, False)
Martin Reinecke's avatar
Martin Reinecke committed
87
88

    def __sub__(self, other):
Martin Reinecke's avatar
Martin Reinecke committed
89
        return self._myadd(other, True)
Martin Reinecke's avatar
Martin Reinecke committed
90
91
92
93

    def __rsub__(self, other):
        return (-self).__add__(other)

94
95
96
97
98
99
100
101
    def __truediv__(self, other):
        if isinstance(other, Linearization):
            return self.__mul__(other.inverse())
        return self.__mul__(1./other)

    def __rtruediv__(self, other):
        return self.inverse().__mul__(other)

Martin Reinecke's avatar
Martin Reinecke committed
102
103
104
    def __pow__(self, power):
        if not np.isscalar(power):
            return NotImplemented
Martin Reinecke's avatar
Martin Reinecke committed
105
106
        return self.new(self._val**power,
                        makeOp(self._val**(power-1)).scale(power)(self._jac))
Martin Reinecke's avatar
Martin Reinecke committed
107

108
109
110
    def inverse(self):
        return self.new(1./self._val, makeOp(-1./(self._val**2))(self._jac))

Martin Reinecke's avatar
Martin Reinecke committed
111
112
113
    def __mul__(self, other):
        from .sugar import makeOp
        if isinstance(other, Linearization):
Martin Reinecke's avatar
Martin Reinecke committed
114
115
            if self.target != other.target:
                raise ValueError("domain mismatch")
116
            return self.new(
Martin Reinecke's avatar
Martin Reinecke committed
117
                self._val*other._val,
Martin Reinecke's avatar
Martin Reinecke committed
118
119
                (makeOp(other._val)(self._jac))._myadd(
                 makeOp(self._val)(other._jac), False))
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
120
121
122
123
        if np.isscalar(other):
            if other == 1:
                return self
            met = None if self._metric is None else self._metric.scale(other)
124
            return self.new(self._val*other, self._jac.scale(other), met)
Martin Reinecke's avatar
Martin Reinecke committed
125
        if isinstance(other, (Field, MultiField)):
Martin Reinecke's avatar
Martin Reinecke committed
126
127
            if self.target != other.domain:
                raise ValueError("domain mismatch")
128
            return self.new(self._val*other, makeOp(other)(self._jac))
Martin Reinecke's avatar
Martin Reinecke committed
129
130

    def __rmul__(self, other):
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
131
        return self.__mul__(other)
Martin Reinecke's avatar
Martin Reinecke committed
132

133
134
135
136
    def outer(self, other):
        from .operators.outer_product_operator import OuterProduct
        if isinstance(other, Linearization):
            return self.new(
Sebastian Hutschenreuter's avatar
Sebastian Hutschenreuter committed
137
138
139
                OuterProduct(self._val, other.target)(other._val),
                OuterProduct(self._jac(self._val), other.target)._myadd(
                    OuterProduct(self._val, other.target)(other._jac), False))
140
        if np.isscalar(other):
Martin Reinecke's avatar
Martin Reinecke committed
141
            return self.__mul__(other)
142
        if isinstance(other, (Field, MultiField)):
Sebastian Hutschenreuter's avatar
Sebastian Hutschenreuter committed
143
144
            return self.new(OuterProduct(self._val, other.domain)(other),
                            OuterProduct(self._jac(self._val), other.domain))
145

Martin Reinecke's avatar
Martin Reinecke committed
146
    def vdot(self, other):
Martin Reinecke's avatar
Martin Reinecke committed
147
        from .operators.simple_linear_operators import VdotOperator
Martin Reinecke's avatar
Martin Reinecke committed
148
        if isinstance(other, (Field, MultiField)):
149
            return self.new(
Martin Reinecke's avatar
Martin Reinecke committed
150
                Field.scalar(self._val.vdot(other)),
Martin Reinecke's avatar
Martin Reinecke committed
151
                VdotOperator(other)(self._jac))
152
        return self.new(
Martin Reinecke's avatar
Martin Reinecke committed
153
            Field.scalar(self._val.vdot(other._val)),
Martin Reinecke's avatar
Martin Reinecke committed
154
155
            VdotOperator(self._val)(other._jac) +
            VdotOperator(other._val)(self._jac))
Martin Reinecke's avatar
Martin Reinecke committed
156

157
    def sum(self, spaces=None):
158
        from .operators.contraction_operator import ContractionOperator
159
160
161
        if spaces is None:
            return self.new(
                Field.scalar(self._val.sum()),
162
                ContractionOperator(self._jac.target, None)(self._jac))
163
164
165
        else:
            return self.new(
                self._val.sum(spaces),
166
                ContractionOperator(self._jac.target, spaces)(self._jac))
167
168

    def integrate(self, spaces=None):
169
        from .operators.contraction_operator import ContractionOperator
170
171
172
        if spaces is None:
            return self.new(
                Field.scalar(self._val.integrate()),
173
                ContractionOperator(self._jac.target, None, 1)(self._jac))
174
175
176
        else:
            return self.new(
                self._val.integrate(spaces),
177
                ContractionOperator(self._jac.target, spaces, 1)(self._jac))
Martin Reinecke's avatar
Martin Reinecke committed
178
179
180

    def exp(self):
        tmp = self._val.exp()
181
        return self.new(tmp, makeOp(tmp)(self._jac))
Philipp Arras's avatar
Philipp Arras committed
182
183
184
185

    def clipped_exp(self):
        tmp = self._val.clipped_exp()
        return self.new(tmp, makeOp(tmp)(self._jac))
Martin Reinecke's avatar
Martin Reinecke committed
186
187
188

    def log(self):
        tmp = self._val.log()
189
        return self.new(tmp, makeOp(1./self._val)(self._jac))
Martin Reinecke's avatar
Martin Reinecke committed
190

Martin Reinecke's avatar
Martin Reinecke committed
191
192
    def tanh(self):
        tmp = self._val.tanh()
193
        return self.new(tmp, makeOp(1.-tmp**2)(self._jac))
Martin Reinecke's avatar
Martin Reinecke committed
194
195
196
197

    def positive_tanh(self):
        tmp = self._val.tanh()
        tmp2 = 0.5*(1.+tmp)
198
        return self.new(tmp2, makeOp(0.5*(1.-tmp**2))(self._jac))
Martin Reinecke's avatar
Martin Reinecke committed
199

Martin Reinecke's avatar
Martin Reinecke committed
200
    def add_metric(self, metric):
201
        return self.new(self._val, self._jac, metric)
Martin Reinecke's avatar
Martin Reinecke committed
202

Martin Reinecke's avatar
Martin Reinecke committed
203
204
205
    def with_want_metric(self):
        return Linearization(self._val, self._jac, self._metric, True)

Martin Reinecke's avatar
Martin Reinecke committed
206
    @staticmethod
207
    def make_var(field, want_metric=False):
Martin Reinecke's avatar
Martin Reinecke committed
208
        from .operators.scaling_operator import ScalingOperator
209
210
        return Linearization(field, ScalingOperator(1., field.domain),
                             want_metric=want_metric)
Martin Reinecke's avatar
Martin Reinecke committed
211
212

    @staticmethod
213
    def make_const(field, want_metric=False):
Martin Reinecke's avatar
Martin Reinecke committed
214
        from .operators.simple_linear_operators import NullOperator
215
216
        return Linearization(field, NullOperator(field.domain, field.domain),
                             want_metric=want_metric)
Martin Reinecke's avatar
Martin Reinecke committed
217

Martin Reinecke's avatar
Martin Reinecke committed
218
219
220
221
    @staticmethod
    def make_const_empty_input(field, want_metric=False):
        from .operators.simple_linear_operators import NullOperator
        from .multi_domain import MultiDomain
Martin Reinecke's avatar
Martin Reinecke committed
222
223
224
        return Linearization(
            field, NullOperator(MultiDomain.make({}), field.domain),
            want_metric=want_metric)
Martin Reinecke's avatar
Martin Reinecke committed
225

Martin Reinecke's avatar
Martin Reinecke committed
226
227
228
    @staticmethod
    def make_partial_var(field, constants, want_metric=False):
        from .operators.scaling_operator import ScalingOperator
Philipp Arras's avatar
Typo    
Philipp Arras committed
229
        from .operators.block_diagonal_operator import BlockDiagonalOperator
Martin Reinecke's avatar
Martin Reinecke committed
230
231
232
233
234
        if len(constants) == 0:
            return Linearization.make_var(field, want_metric)
        else:
            ops = [ScalingOperator(0. if key in constants else 1., dom)
                   for key, dom in field.domain.items()]
Philipp Arras's avatar
Typo    
Philipp Arras committed
235
            bdop = BlockDiagonalOperator(field.domain, tuple(ops))
Martin Reinecke's avatar
Martin Reinecke committed
236
            return Linearization(field, bdop, want_metric=want_metric)