multi_field.py 8.06 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
20
21
from ..field import Field
import numpy as np
from .multi_domain import MultiDomain
22
from ..utilities import frozendict
Martin Reinecke's avatar
Martin Reinecke committed
23
24


Martin Reinecke's avatar
Martin Reinecke committed
25
26
27
28
29
30
31
32
33
# ways of creating MultiFields:
# - (Field)
# - (Field, name)
# - (dict {string, Field})
# - MultiDomain, dict(string, Field)

# new methods
# .field(name)
# .domain(name)
Martin Reinecke's avatar
Martin Reinecke committed
34
class MultiField(object):
Martin Reinecke's avatar
Martin Reinecke committed
35
    def __init__(self, domain, val):
Martin Reinecke's avatar
Martin Reinecke committed
36
37
38
        """
        Parameters
        ----------
Martin Reinecke's avatar
Martin Reinecke committed
39
40
        domain: MultiDomain
        val: tuple of Fields
Martin Reinecke's avatar
Martin Reinecke committed
41
        """
Martin Reinecke's avatar
Martin Reinecke committed
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
        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")
        for i, v in enumerate(val):
            if isinstance(v, Field):
                if v._domain is not domain._domains[i]:
                    raise ValueError("domain mismatch")
            elif v is not None:
                raise TypeError("bad entry in val")
        self._domain = domain
        self._val = val

    @staticmethod
    def from_dict(dict):
        domain = MultiDomain.make({key: v._domain for key, v in dict.items()})
        return MultiField(domain, tuple(dict[key] for key in domain._keys))

    def to_dict(self):
        return {key: val for key, val in zip(self._domain._keys, self._val)}
Martin Reinecke's avatar
Martin Reinecke committed
64
65

    def __getitem__(self, key):
Martin Reinecke's avatar
Martin Reinecke committed
66
        return self._val[self._domain._dict[key]]
Martin Reinecke's avatar
Martin Reinecke committed
67
68

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

    def items(self):
Martin Reinecke's avatar
Martin Reinecke committed
72
        return zip(self._domain._keys, self._val)
Martin Reinecke's avatar
Martin Reinecke committed
73
74

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

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

Martin Reinecke's avatar
Martin Reinecke committed
81
82
83
84
85
86
87
88
#    @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
89

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

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

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

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

    def vdot(self, x):
        result = 0.
        self._check_domain(x)
Martin Reinecke's avatar
Martin Reinecke committed
115
116
117
        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
118
119
        return result

Martin Reinecke's avatar
Martin Reinecke committed
120
121
122
123
124
125
126
#    @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
127

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

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

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

Martin Reinecke's avatar
Martin Reinecke committed
142
143
144
145
146
147
148
149
150
151
    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)))

152
153
154
155
156
157
158
159
160
161
    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
162
    def __neg__(self):
Martin Reinecke's avatar
Martin Reinecke committed
163
        return self._transform(lambda x: -x)
Martin Reinecke's avatar
Martin Reinecke committed
164

165
    def __abs__(self):
Martin Reinecke's avatar
Martin Reinecke committed
166
        return self._transform(lambda x: abs(x))
167

Martin Reinecke's avatar
Martin Reinecke committed
168
    def conjugate(self):
Martin Reinecke's avatar
Martin Reinecke committed
169
        return self._transform(lambda x: x.conjugate())
Martin Reinecke's avatar
Martin Reinecke committed
170

171
    def all(self):
Martin Reinecke's avatar
Martin Reinecke committed
172
173
        for v in self._val:
            if v is None or not v.all():
174
175
176
177
                return False
        return True

    def any(self):
Martin Reinecke's avatar
Martin Reinecke committed
178
179
        for v in self._val:
            if v is not None and v.any():
180
181
182
                return True
        return False

183
184
185
    def isEquivalentTo(self, other):
        """Determines (as quickly as possible) whether `self`'s content is
        identical to `other`'s content."""
186
187
188
189
        if self is other:
            return True
        if not isinstance(other, MultiField):
            return False
Martin Reinecke's avatar
Martin Reinecke committed
190
        if self._domain is not other._domain:
191
            return False
Martin Reinecke's avatar
Martin Reinecke committed
192
193
        for v1, v2 in zip(self._val, other._val):
            if not v1.isEquivalentTo(v2):
194
195
                return False
        return True
Martin Reinecke's avatar
Martin Reinecke committed
196

197
198
199
200
201
202
203
    def isSubsetOf(self, other):
        """Determines (as quickly as possible) whether `self`'s content is
        a subset of `other`'s content."""
        if self is other:
            return True
        if not isinstance(other, MultiField):
            return False
Martin Reinecke's avatar
Martin Reinecke committed
204
205
206
        if len(set(self._domain.keys()) - set(other._domain.keys())) > 0:
            return False
        for key in self._domain.keys():
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
207
            if other._domain[key] is not self._domain[key]:
208
                return False
Martin Reinecke's avatar
Martin Reinecke committed
209
            if not other[key].isSubsetOf(self[key]):
210
211
                return False
        return True
212

213

Martin Reinecke's avatar
Martin Reinecke committed
214
215
216
217
218
219
220
for op in ["__add__", "__radd__",
           "__sub__", "__rsub__",
           "__mul__", "__rmul__",
           "__div__", "__rdiv__",
           "__truediv__", "__rtruediv__",
           "__floordiv__", "__rfloordiv__",
           "__pow__", "__rpow__",
Martin Reinecke's avatar
Martin Reinecke committed
221
222
223
           "__lt__", "__le__", "__gt__", "__ge__", "__eq__", "__ne__"]:
    def func(op):
        def func2(self, other):
Martin Reinecke's avatar
Martin Reinecke committed
224
            res = []
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
225
            if isinstance(other, MultiField):
Martin Reinecke's avatar
Martin Reinecke committed
226
227
228
229
230
231
232
233
                if self._domain is not other._domain:
                    raise ValueError("domain mismatch")
                for v1, v2 in zip(self._val, other._val):
                    if v1 is not None:
                        if v2 is None:
                            res.append(getattr(v1, op)(v1*0))
                        else:
                            res.append(getattr(v1, op)(v2))
Philipp Arras's avatar
Philipp Arras committed
234
                    else:
Martin Reinecke's avatar
Martin Reinecke committed
235
236
237
238
239
                        if v2 is None:
                            res.append(None)
                        else:
                            res.append(getattr(v2*0, op)(v2))
                return MultiField(self._domain, tuple(res))
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
240
            else:
Martin Reinecke's avatar
Martin Reinecke committed
241
                return self._transform(lambda x: getattr(x, op)(other))
Martin Reinecke's avatar
Martin Reinecke committed
242
243
        return func2
    setattr(MultiField, op, func(op))
244
245
246
247
248
249
250
251
252

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))