multi_field.py 8.99 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 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/>.
#
# Copyright(C) 2013-2018 Max-Planck-Society
#
# 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
22

import numpy as np

Martin Reinecke's avatar
Martin Reinecke committed
23
from ..compat import *
Martin Reinecke's avatar
Martin Reinecke committed
24
25
from ..field import Field
from .multi_domain import MultiDomain
Martin Reinecke's avatar
Martin Reinecke committed
26
from .. import utilities
Martin Reinecke's avatar
Martin Reinecke committed
27
28
29


class MultiField(object):
Martin Reinecke's avatar
Martin Reinecke committed
30
    def __init__(self, domain, val):
Martin Reinecke's avatar
Martin Reinecke committed
31
32
33
        """
        Parameters
        ----------
Martin Reinecke's avatar
Martin Reinecke committed
34
        domain: MultiDomain
Martin Reinecke's avatar
Martin Reinecke committed
35
        val: tuple containing Field or None entries
Martin Reinecke's avatar
Martin Reinecke committed
36
        """
Martin Reinecke's avatar
Martin Reinecke committed
37
38
39
40
41
42
        if not isinstance(domain, MultiDomain):
            raise TypeError("domain must be of type MultiDomain")
        if not isinstance(val, tuple):
            raise TypeError("val must be a tuple")
        if len(val) != len(domain):
            raise ValueError("length mismatch")
Martin Reinecke's avatar
Martin Reinecke committed
43
        for d, v in zip(domain._domains, val):
Martin Reinecke's avatar
Martin Reinecke committed
44
            if isinstance(v, Field):
Martin Reinecke's avatar
Martin Reinecke committed
45
                if v._domain is not d:
Martin Reinecke's avatar
Martin Reinecke committed
46
47
                    raise ValueError("domain mismatch")
            elif v is not None:
Martin Reinecke's avatar
Martin Reinecke committed
48
                raise TypeError("bad entry in val (must be Field or None)")
Martin Reinecke's avatar
Martin Reinecke committed
49
50
51
52
        self._domain = domain
        self._val = val

    @staticmethod
Martin Reinecke's avatar
Martin Reinecke committed
53
54
55
56
57
58
    def from_dict(dict, domain=None):
        if domain is None:
            domain = MultiDomain.make({key: v._domain
                                       for key, v in dict.items()})
        return MultiField(domain, tuple(dict[key] if key in dict else None
                                        for key in domain.keys()))
Martin Reinecke's avatar
Martin Reinecke committed
59
60

    def to_dict(self):
Martin Reinecke's avatar
Martin Reinecke committed
61
        return {key: val for key, val in zip(self._domain.keys(), self._val)}
Martin Reinecke's avatar
Martin Reinecke committed
62
63

    def __getitem__(self, key):
Martin Reinecke's avatar
Martin Reinecke committed
64
        return self._val[self._domain.idx[key]]
Martin Reinecke's avatar
Martin Reinecke committed
65
66

    def keys(self):
Martin Reinecke's avatar
Martin Reinecke committed
67
        return self._domain.keys()
Martin Reinecke's avatar
Martin Reinecke committed
68
69

    def items(self):
Martin Reinecke's avatar
Martin Reinecke committed
70
        return zip(self._domain.keys(), self._val)
Martin Reinecke's avatar
Martin Reinecke committed
71
72

    def values(self):
Martin Reinecke's avatar
Martin Reinecke committed
73
        return self._val
Martin Reinecke's avatar
Martin Reinecke committed
74
75
76

    @property
    def domain(self):
77
        return self._domain
Martin Reinecke's avatar
Martin Reinecke committed
78

Martin Reinecke's avatar
Martin Reinecke committed
79
80
81
82
83
84
85
86
#    @property
#    def dtype(self):
#        return {key: val.dtype for key, val in self._val.items()}

    def _transform(self, op):
        return MultiField(
            self._domain,
            tuple(op(v) if v is not None else None for v in self._val))
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
87

88
89
90
    @property
    def real(self):
        """MultiField : The real part of the multi field"""
Martin Reinecke's avatar
Martin Reinecke committed
91
        return self._transform(lambda x: x.real)
92
93
94
95

    @property
    def imag(self):
        """MultiField : The imaginary part of the multi field"""
Martin Reinecke's avatar
Martin Reinecke committed
96
        return self._transform(lambda x: x.imag)
97

98
99
    @staticmethod
    def from_random(random_type, domain, dtype=np.float64, **kwargs):
Martin Reinecke's avatar
Martin Reinecke committed
100
101
102
103
        domain = MultiDomain.make(domain)
#        dtype = MultiField.build_dtype(dtype, domain)
        return MultiField(
            domain, tuple(Field.from_random(random_type, dom, dtype, **kwargs)
Martin Reinecke's avatar
Martin Reinecke committed
104
                          for dom in domain._domains))
105

Martin Reinecke's avatar
Martin Reinecke committed
106
    def _check_domain(self, other):
Martin Reinecke's avatar
Martin Reinecke committed
107
        if other._domain is not self._domain:
Martin Reinecke's avatar
Martin Reinecke committed
108
109
110
111
112
            raise ValueError("domains are incompatible.")

    def vdot(self, x):
        result = 0.
        self._check_domain(x)
Martin Reinecke's avatar
Martin Reinecke committed
113
114
115
        for v1, v2 in zip(self._val, x._val):
            if v1 is not None and v2 is not None:
                result += v1.vdot(v2)
Martin Reinecke's avatar
Martin Reinecke committed
116
117
        return result

Martin Reinecke's avatar
Martin Reinecke committed
118
119
120
121
122
123
124
#    @staticmethod
#    def build_dtype(dtype, domain):
#        if isinstance(dtype, dict):
#            return dtype
#        if dtype is None:
#            dtype = np.float64
#        return {key: dtype for key in domain.keys()}
Martin Reinecke's avatar
Martin Reinecke committed
125

Martin Reinecke's avatar
Martin Reinecke committed
126
    @staticmethod
Martin Reinecke's avatar
step 1    
Martin Reinecke committed
127
    def full(domain, val):
Martin Reinecke's avatar
Martin Reinecke committed
128
129
        return MultiField(domain, tuple(Field.full(dom, val)
                          for dom in domain._domains))
Martin Reinecke's avatar
Martin Reinecke committed
130

Martin Reinecke's avatar
fixes    
Martin Reinecke committed
131
    def to_global_data(self):
Martin Reinecke's avatar
Martin Reinecke committed
132
133
        return {key: val.to_global_data()
                for key, val in zip(self._domain.keys(), self._val)}
Martin Reinecke's avatar
fixes    
Martin Reinecke committed
134
135
136

    @staticmethod
    def from_global_data(domain, arr, sum_up=False):
Martin Reinecke's avatar
Martin Reinecke committed
137
138
        return MultiField(
            domain, tuple(Field.from_global_data(domain[key], arr[key], sum_up)
Martin Reinecke's avatar
Martin Reinecke committed
139
                          for key in domain.keys()))
Martin Reinecke's avatar
fixes    
Martin Reinecke committed
140

Martin Reinecke's avatar
Martin Reinecke committed
141
142
143
144
145
146
147
148
149
150
    def norm(self):
        """ Computes the L2-norm of the field values.

        Returns
        -------
        norm : float
            The L2-norm of the field values.
        """
        return np.sqrt(np.abs(self.vdot(x=self)))

151
152
153
154
155
156
157
158
    def sum(self):
        """ Computes the sum all field values.

        Returns
        -------
        norm : float
            The sum of the field values.
        """
Martin Reinecke's avatar
Martin Reinecke committed
159
        return utilities.my_sum(map(lambda v: v.sum(), self._val))
160
161
162
163
164
165
166
167
168
169

    @property
    def size(self):
        """ Computes the overall degrees of freedom.

        Returns
        -------
        size : int
            The sum of the size of the individual fields
        """
Martin Reinecke's avatar
Martin Reinecke committed
170
        return utilities.my_sum(map(lambda d: d.size, self._domain.domains()))
171

172
173
174
175
176
177
178
179
180
181
    def squared_norm(self):
        """ Computes the square of the L2-norm of the field values.

        Returns
        -------
        float
            The square of the L2-norm of the field values.
        """
        return abs(self.vdot(x=self))

Martin Reinecke's avatar
Martin Reinecke committed
182
    def __neg__(self):
Martin Reinecke's avatar
Martin Reinecke committed
183
        return self._transform(lambda x: -x)
Martin Reinecke's avatar
Martin Reinecke committed
184

185
    def __abs__(self):
Martin Reinecke's avatar
Martin Reinecke committed
186
        return self._transform(lambda x: abs(x))
187

Martin Reinecke's avatar
Martin Reinecke committed
188
    def conjugate(self):
Martin Reinecke's avatar
Martin Reinecke committed
189
        return self._transform(lambda x: x.conjugate())
Martin Reinecke's avatar
Martin Reinecke committed
190

191
    def all(self):
Martin Reinecke's avatar
Martin Reinecke committed
192
193
        for v in self._val:
            if v is None or not v.all():
194
195
196
197
                return False
        return True

    def any(self):
Martin Reinecke's avatar
Martin Reinecke committed
198
199
        for v in self._val:
            if v is not None and v.any():
200
201
202
                return True
        return False

203
204
205
    def isEquivalentTo(self, other):
        """Determines (as quickly as possible) whether `self`'s content is
        identical to `other`'s content."""
206
207
208
209
        if self is other:
            return True
        if not isinstance(other, MultiField):
            return False
Martin Reinecke's avatar
Martin Reinecke committed
210
        if self._domain is not other._domain:
211
            return False
Martin Reinecke's avatar
Martin Reinecke committed
212
213
        for v1, v2 in zip(self._val, other._val):
            if not v1.isEquivalentTo(v2):
214
215
                return False
        return True
Martin Reinecke's avatar
Martin Reinecke committed
216

Martin Reinecke's avatar
Martin Reinecke committed
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236

for op in ["__add__", "__radd__"]:
    def func(op):
        def func2(self, other):
            if isinstance(other, MultiField):
                if self._domain is not other._domain:
                    raise ValueError("domain mismatch")
                val = []
                for v1, v2 in zip(self._val, other._val):
                    if v1 is not None:
                        val.append(v1 if v2 is None else (v1+v2))
                    else:
                        val.append(None if v2 is None else v2)
                val = tuple(val)
            else:
                val = tuple(other if v1 is None else (v1+other)
                            for v1 in self._val)
            return MultiField(self._domain, val)
        return func2
    setattr(MultiField, op, func(op))
237

238

Martin Reinecke's avatar
Martin Reinecke committed
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
for op in ["__mul__", "__rmul__"]:
    def func(op):
        def func2(self, other):
            if isinstance(other, MultiField):
                if self._domain is not other._domain:
                    raise ValueError("domain mismatch")
                val = tuple(None if v1 is None or v2 is None else v1*v2
                            for v1, v2 in zip(self._val, other._val))
            else:
                val = tuple(None if v1 is None else (v1*other)
                            for v1 in self._val)
            return MultiField(self._domain, val)
        return func2
    setattr(MultiField, op, func(op))


for op in ["__sub__", "__rsub__",
Martin Reinecke's avatar
Martin Reinecke committed
256
257
258
259
           "__div__", "__rdiv__",
           "__truediv__", "__rtruediv__",
           "__floordiv__", "__rfloordiv__",
           "__pow__", "__rpow__",
Martin Reinecke's avatar
Martin Reinecke committed
260
261
262
           "__lt__", "__le__", "__gt__", "__ge__", "__eq__", "__ne__"]:
    def func(op):
        def func2(self, other):
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
263
            if isinstance(other, MultiField):
Martin Reinecke's avatar
Martin Reinecke committed
264
265
                if self._domain is not other._domain:
                    raise ValueError("domain mismatch")
Martin Reinecke's avatar
Martin Reinecke committed
266
                val = tuple(getattr(v1, op)(v2)
Martin Reinecke's avatar
Martin Reinecke committed
267
                            for v1, v2 in zip(self._val, other._val))
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
268
            else:
Martin Reinecke's avatar
Martin Reinecke committed
269
270
                val = tuple(getattr(v1, op)(other) for v1 in self._val)
            return MultiField(self._domain, val)
Martin Reinecke's avatar
Martin Reinecke committed
271
272
        return func2
    setattr(MultiField, op, func(op))
273

Martin Reinecke's avatar
Martin Reinecke committed
274

275
276
277
278
279
280
281
282
for op in ["__iadd__", "__isub__", "__imul__", "__idiv__",
           "__itruediv__", "__ifloordiv__", "__ipow__"]:
    def func(op):
        def func2(self, other):
            raise TypeError(
                "In-place operations are deliberately not supported")
        return func2
    setattr(MultiField, op, func(op))