multi_field.py 11 KB
Newer Older
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
15
#
16
# NIFTy is being developed at the Max-Planck-Institut fuer Astrophysik.
17
18
19

import numpy as np

Philipp Arras's avatar
Philipp Arras committed
20
from . import utilities
Martin Reinecke's avatar
Martin Reinecke committed
21
from .field import Field
Martin Reinecke's avatar
Martin Reinecke committed
22
from .multi_domain import MultiDomain
23
from .domain_tuple import DomainTuple
Martin Reinecke's avatar
Martin Reinecke committed
24
25
26


class MultiField(object):
Martin Reinecke's avatar
Martin Reinecke committed
27
    def __init__(self, domain, val):
28
29
        """The discrete representation of a continuous field over a sum space.

Martin Reinecke's avatar
Martin Reinecke committed
30
31
        Parameters
        ----------
Martin Reinecke's avatar
Martin Reinecke committed
32
        domain: MultiDomain
Martin Reinecke's avatar
Martin Reinecke committed
33
        val: tuple containing Field entries
Martin Reinecke's avatar
Martin Reinecke committed
34
        """
Martin Reinecke's avatar
Martin Reinecke committed
35
36
37
38
39
40
        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
41
        for d, v in zip(domain._domains, val):
Martin Reinecke's avatar
Martin Reinecke committed
42
            if isinstance(v, Field):
Martin Reinecke's avatar
Martin Reinecke committed
43
                if v._domain != d:
Martin Reinecke's avatar
Martin Reinecke committed
44
                    raise ValueError("domain mismatch")
Martin Reinecke's avatar
Martin Reinecke committed
45
46
            else:
                raise TypeError("bad entry in val (must be Field)")
Martin Reinecke's avatar
Martin Reinecke committed
47
48
49
50
        self._domain = domain
        self._val = val

    @staticmethod
Martin Reinecke's avatar
Martin Reinecke committed
51
52
    def from_dict(dict, domain=None):
        if domain is None:
53
54
            for dd in dict.values():
                if not isinstance(dd.domain, DomainTuple):
Martin Reinecke's avatar
Martin Reinecke committed
55
56
                    raise TypeError('Values of dictionary need to be Fields '
                                    'defined on DomainTuples.')
Martin Reinecke's avatar
Martin Reinecke committed
57
58
            domain = MultiDomain.make({key: v._domain
                                       for key, v in dict.items()})
Martin Reinecke's avatar
fixes    
Martin Reinecke committed
59
        res = tuple(dict[key] if key in dict else Field(dom, 0.)
Martin Reinecke's avatar
tweak    
Martin Reinecke committed
60
61
                    for key, dom in zip(domain.keys(), domain.domains()))
        return MultiField(domain, res)
Martin Reinecke's avatar
Martin Reinecke committed
62
63

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

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

Martin Reinecke's avatar
fix #72    
Martin Reinecke committed
69
    def __contains__(self, key):
Martin Reinecke's avatar
Martin Reinecke committed
70
        return key in self._domain.idx
Martin Reinecke's avatar
fix #72    
Martin Reinecke committed
71

Martin Reinecke's avatar
Martin Reinecke committed
72
    def keys(self):
Martin Reinecke's avatar
Martin Reinecke committed
73
        return self._domain.keys()
Martin Reinecke's avatar
Martin Reinecke committed
74
75

    def items(self):
Martin Reinecke's avatar
Martin Reinecke committed
76
        return zip(self._domain.keys(), self._val)
Martin Reinecke's avatar
Martin Reinecke committed
77
78

    def values(self):
Martin Reinecke's avatar
Martin Reinecke committed
79
        return self._val
Martin Reinecke's avatar
Martin Reinecke committed
80
81
82

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

Martin Reinecke's avatar
Martin Reinecke committed
85
86
87
88
89
#    @property
#    def dtype(self):
#        return {key: val.dtype for key, val in self._val.items()}

    def _transform(self, op):
Martin Reinecke's avatar
Martin Reinecke committed
90
        return MultiField(self._domain, tuple(op(v) for v in self._val))
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
91

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

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

102
103
    @staticmethod
    def from_random(random_type, domain, dtype=np.float64, **kwargs):
Martin Reinecke's avatar
Martin Reinecke committed
104
105
106
107
        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
108
                          for dom in domain._domains))
109

Martin Reinecke's avatar
Martin Reinecke committed
110
    def _check_domain(self, other):
Martin Reinecke's avatar
Martin Reinecke committed
111
        if other._domain != self._domain:
Martin Reinecke's avatar
Martin Reinecke committed
112
113
114
115
116
            raise ValueError("domains are incompatible.")

    def vdot(self, x):
        result = 0.
        self._check_domain(x)
Martin Reinecke's avatar
Martin Reinecke committed
117
        for v1, v2 in zip(self._val, x._val):
Martin Reinecke's avatar
Martin Reinecke committed
118
            result += v1.vdot(v2)
Martin Reinecke's avatar
Martin Reinecke committed
119
120
        return result

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

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

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

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

Martin Reinecke's avatar
Martin Reinecke committed
145
    def norm(self, ord=2):
146
        """Computes the norm of the field values.
Martin Reinecke's avatar
Martin Reinecke committed
147
148
149
150
151

        Parameters
        ----------
        ord : int, default=2
            accepted values: 1, 2, ..., np.inf
Martin Reinecke's avatar
Martin Reinecke committed
152
153
154
155

        Returns
        -------
        norm : float
Martin Reinecke's avatar
Martin Reinecke committed
156
            The norm of the field values.
Martin Reinecke's avatar
Martin Reinecke committed
157
        """
Martin Reinecke's avatar
Martin Reinecke committed
158
159
160
161
162
        nrm = np.asarray([f.norm(ord) for f in self._val])
        if ord == np.inf:
            return nrm.max()
        return (nrm ** ord).sum() ** (1./ord)
#        return np.sqrt(np.abs(self.vdot(x=self)))
Martin Reinecke's avatar
Martin Reinecke committed
163

164
    def sum(self):
165
        """Computes the sum all field values.
166
167
168
169
170
171

        Returns
        -------
        norm : float
            The sum of the field values.
        """
Martin Reinecke's avatar
Martin Reinecke committed
172
        return utilities.my_sum(map(lambda v: v.sum(), self._val))
173
174
175

    @property
    def size(self):
176
        """Computes the overall degrees of freedom.
177
178
179
180
181
182

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

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

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

Martin Reinecke's avatar
Martin Reinecke committed
191
    def conjugate(self):
Martin Reinecke's avatar
Martin Reinecke committed
192
        return self._transform(lambda x: x.conjugate())
Martin Reinecke's avatar
Martin Reinecke committed
193

Martin Reinecke's avatar
Martin Reinecke committed
194
    def clip(self, min=None, max=None):
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
195
196
197
198
199
200
        ncomp = len(self._val)
        lmin = min._val if isinstance(min, MultiField) else (min,)*ncomp
        lmax = max._val if isinstance(max, MultiField) else (max,)*ncomp
        return MultiField(
            self._domain,
            tuple(self._val[i].clip(lmin[i], lmax[i]) for i in range(ncomp)))
Martin Reinecke's avatar
Martin Reinecke committed
201

202
    def all(self):
Martin Reinecke's avatar
Martin Reinecke committed
203
        for v in self._val:
Martin Reinecke's avatar
Martin Reinecke committed
204
            if not v.all():
205
206
207
208
                return False
        return True

    def any(self):
Martin Reinecke's avatar
Martin Reinecke committed
209
        for v in self._val:
Martin Reinecke's avatar
Martin Reinecke committed
210
            if v.any():
211
212
213
                return True
        return False

Martin Reinecke's avatar
Martin Reinecke committed
214
    def extract(self, subset):
Martin Reinecke's avatar
Martin Reinecke committed
215
216
217
218
        if subset is self._domain:
            return self
        return MultiField(subset,
                          tuple(self[key] for key in subset.keys()))
Martin Reinecke's avatar
Martin Reinecke committed
219

220
221
222
223
224
    def extract_part(self, subset):
        if subset is self._domain:
            return self
        return MultiField.from_dict({key: self[key] for key in subset.keys()
                                     if key in self})
Philipp Arras's avatar
Philipp Arras committed
225

Martin Reinecke's avatar
more    
Martin Reinecke committed
226
    def unite(self, other):
Martin Reinecke's avatar
Martin Reinecke committed
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
        """Merges two MultiFields on potentially different MultiDomains.

        Parameters
        ----------
        other : MultiField
            the partner Field

        Returns
        -------
        MultiField
            This MultiField's domain is the union of the input fields'
            domains. The values are the sum of the fields in self and other.
            If a field is not present, it is assumed to have an uniform value
            of zero.
        """
Martin Reinecke's avatar
Martin Reinecke committed
242
243
        if self._domain is other._domain:
            return self + other
Martin Reinecke's avatar
Martin Reinecke committed
244
245
246
        res = self.to_dict()
        for key, val in other.items():
            res[key] = res[key]+val if key in res else val
Martin Reinecke's avatar
Martin Reinecke committed
247
        return MultiField.from_dict(res)
Martin Reinecke's avatar
Martin Reinecke committed
248

249
250
    @staticmethod
    def union(fields, domain=None):
251
        """Returns the union of its input fields.
Martin Reinecke's avatar
doc fix    
Martin Reinecke committed
252

253
254
        Parameters
        ----------
Martin Reinecke's avatar
doc fix    
Martin Reinecke committed
255
        fields : iterable of MultiFields
Martin Reinecke's avatar
doc fix    
Martin Reinecke committed
256
            The set of input fields. Their domains need not be identical.
Martin Reinecke's avatar
doc fix    
Martin Reinecke committed
257
        domain : MultiDomain or None
Martin Reinecke's avatar
doc fix    
Martin Reinecke committed
258
            If supplied, this will be the domain of the resulting field.
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
            Providing this domain will accelerate the function.

        Returns
        -------
        MultiField
            The union of the input fields

        Notes
        -----
        If the same key occurs more than once in the input fields, the value
        associated with the last occurrence will be put into the output.
        No summation is performed!
        """
        res = {}
        for field in fields:
            res.update(field.to_dict())
        return MultiField.from_dict(res, domain)

Martin Reinecke's avatar
Martin Reinecke committed
277
    def flexible_addsub(self, other, neg):
Martin Reinecke's avatar
Martin Reinecke committed
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
        """Merges two MultiFields on potentially different MultiDomains.

        Parameters
        ----------
        other : MultiField
            the partner Field
        neg : bool
            if True, the partner field is subtracted, otherwise added

        Returns
        -------
        MultiField
            This MultiField's domain is the union of the input fields'
            domains. The values are the sum (or difference, if neg==True) of
            the fields in self and other. If a field is not present, it is
            assumed to have an uniform value of zero.
        """
Martin Reinecke's avatar
Martin Reinecke committed
295
296
297
298
299
300
301
302
303
304
        if self._domain is other._domain:
            return self-other if neg else self+other
        res = self.to_dict()
        for key, val in other.items():
            if key in res:
                res[key] = res[key]-val if neg else res[key]+val
            else:
                res[key] = -val if neg else val
        return MultiField.from_dict(res)

Martin Reinecke's avatar
Martin Reinecke committed
305
306
307
    def _binary_op(self, other, op):
        f = getattr(Field, op)
        if isinstance(other, MultiField):
Martin Reinecke's avatar
Martin Reinecke committed
308
            if self._domain != other._domain:
Martin Reinecke's avatar
Martin Reinecke committed
309
310
311
312
313
314
315
                raise ValueError("domain mismatch")
            val = tuple(f(v1, v2)
                        for v1, v2 in zip(self._val, other._val))
        else:
            val = tuple(f(v1, other) for v1 in self._val)
        return MultiField(self._domain, val)

Martin Reinecke's avatar
more    
Martin Reinecke committed
316

Martin Reinecke's avatar
Martin Reinecke committed
317
318
319
for op in ["__add__", "__radd__",
           "__sub__", "__rsub__",
           "__mul__", "__rmul__",
Martin Reinecke's avatar
Martin Reinecke committed
320
321
322
           "__truediv__", "__rtruediv__",
           "__floordiv__", "__rfloordiv__",
           "__pow__", "__rpow__",
Martin Reinecke's avatar
Martin Reinecke committed
323
324
325
           "__lt__", "__le__", "__gt__", "__ge__", "__eq__", "__ne__"]:
    def func(op):
        def func2(self, other):
Martin Reinecke's avatar
Martin Reinecke committed
326
            return self._binary_op(other, op)
Martin Reinecke's avatar
Martin Reinecke committed
327
328
        return func2
    setattr(MultiField, op, func(op))
329

Martin Reinecke's avatar
Martin Reinecke committed
330

331
332
333
334
335
336
337
338
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))
Martin Reinecke's avatar
Martin Reinecke committed
339
340


Martin Reinecke's avatar
Martin Reinecke committed
341
for f in ["sqrt", "exp", "log", "tanh"]:
Martin Reinecke's avatar
Martin Reinecke committed
342
343
    def func(f):
        def func2(self):
Martin Reinecke's avatar
bug fix    
Martin Reinecke committed
344
            fu = getattr(Field, f)
Martin Reinecke's avatar
Martin Reinecke committed
345
            return MultiField(self.domain,
Martin Reinecke's avatar
bug fix    
Martin Reinecke committed
346
                              tuple(fu(val) for val in self.values()))
Martin Reinecke's avatar
Martin Reinecke committed
347
348
        return func2
    setattr(MultiField, f, func(f))