core.py 102 KB
Newer Older
dboe's avatar
dboe committed
1
#!/usr/bin/env  # pylint: disable=too-many-lines,super-with-arguments
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
2
3
4
# encoding: utf-8
"""
Author:     Daniel Boeckenhoff
dboe's avatar
dboe committed
5
Mail:       dboe@ipp.mpg.de
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
6
7
8

core of tfields library
contains numpy ndarray derived bases of the tfields package
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
9
10

Notes:
dboe's avatar
dboe committed
11
12
13
14
15
16
    * It could be worthwhile concidering [np.li.mixins.NDArrayOperatorsMixin]<https://
docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.lib.mixins.NDArrayOperatorsMixin.html>

TODO:
    * lint the docstrings!!!
    * maybe switch to numpy style for documentation since this is numpy derived. Not yet decided
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
17
"""
dboe's avatar
dboe committed
18
# builtin
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
19
20
21
import warnings
from contextlib import contextmanager
from collections import Counter
dboe's avatar
dboe committed
22
from copy import deepcopy
dboe's avatar
dboe committed
23
import logging
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
24

dboe's avatar
dboe committed
25
# 3rd party
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
26
27
import numpy as np
import sympy
dboe's avatar
dboe committed
28
import scipy
dboe's avatar
dboe committed
29
import sortedcontainers
30
import rna
dboe's avatar
dboe committed
31

dboe's avatar
dboe committed
32
# 'local'
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
33
import tfields.bases
dboe's avatar
dboe committed
34
35

np.seterr(all="warn", over="raise")
dboe's avatar
dboe committed
36
LOGGER = logging.getLogger(__name__)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
37
38
39
40
41
42


def rank(tensor):
    """
    Tensor rank
    """
dboe's avatar
dboe committed
43
    tensor = np.asarray(tensor)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
44
45
46
47
48
49
50
    return len(tensor.shape) - 1


def dim(tensor):
    """
    Manifold dimension
    """
dboe's avatar
dboe committed
51
    tensor = np.asarray(tensor)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
52
53
54
55
56
    if rank(tensor) == 0:
        return 1
    return tensor.shape[1]


dboe's avatar
dboe committed
57
class AbstractObject(rna.polymorphism.Storable):
dboe's avatar
dboe committed
58
59
    """
    Abstract base class for all tfields objects implementing polymorphisms
dboe's avatar
dboe committed
60
61
62
63

    TODO:
        * Use abstract base class to define the polymorphism contract:
            see https://stackoverflow.com/questions/3570796/why-use-abstract-base-classes-in-python
dboe's avatar
dboe committed
64
65
66
    """

    def _save_npz(self, path):
dboe's avatar
dboe committed
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
        """
        Args:
            path (open file or str/unicode): destination to save file to.

        Examples:
            Build some dummies:
            >>> import tfields
            >>> from tempfile import NamedTemporaryFile
            >>> out_file = NamedTemporaryFile(suffix='.npz')
            >>> p = tfields.Points3D([[1., 2., 3.], [4., 5., 6.], [1, 2, -6]],
            ...                      name='my_points')
            >>> scalars = tfields.Tensors([0, 1, 2], name=42)
            >>> vectors = tfields.Tensors([[0, 0, 0], [0, 0, 1], [0, -1, 0]])
            >>> maps = [tfields.TensorFields([[0, 1, 2], [0, 1, 2]], [42, 21]),
            ...         tfields.TensorFields([[1], [2]], [-42, -21])]
            >>> m = tfields.TensorMaps(vectors, scalars,
            ...                        maps=maps)

            Simply give the file name to save
            >>> p.save(out_file.name)
            >>> _ = out_file.seek(0)  # this is only necessary in the test
            >>> p1 = tfields.Points3D.load(out_file.name)
            >>> assert p.equal(p1)
            >>> assert p.coord_sys == p1.coord_sys

            The fully nested structure of a TensorMaps object is reconstructed
            >>> out_file_maps = NamedTemporaryFile(suffix='.npz')
            >>> m.save(out_file_maps.name)
            >>> _ = out_file_maps.seek(0)
            >>> m1 = tfields.TensorMaps.load(out_file_maps.name,
            ...                              allow_pickle=True)
            >>> assert m.equal(m1)
dboe's avatar
dboe committed
99
            >>> assert m.maps[3].dtype == m1.maps[3].dtype
dboe's avatar
dboe committed
100
101
102
103
104
105
106

            Names are preserved
            >>> assert p.name == 'my_points'
            >>> m.names
            [42]

        """
dboe's avatar
dboe committed
107
        content_dict = self._as_dict()
108
        content_dict["tfields_version"] = tfields.__version__
dboe's avatar
dboe committed
109
110
111
112
113
114
115
116
        np.savez(path, **content_dict)

    @classmethod
    def _load_npz(cls, path, **load_kwargs):
        """
        Factory method
        Given a path to a npz file, construct the object
        """
dboe's avatar
dboe committed
117
        # Note: think about allow_pickle, wheter it really should be True or
dboe's avatar
dboe committed
118
        # wheter we could avoid pickling (potential security issue)
119
        load_kwargs.setdefault("allow_pickle", True)
dboe's avatar
dboe committed
120
        np_file = np.load(path, **load_kwargs)
dboe's avatar
dboe committed
121
122
123
        content = dict(np_file)
        content.pop("tfields_version", None)
        return cls._from_dict(content)
dboe's avatar
dboe committed
124

dboe's avatar
dboe committed
125
126
127
128
    def _args(self) -> tuple:  # pylint: disable=no-self-use
        """
        Used for allowing the polymorphic signature Class(obj) as a copy/casting constructor
        """
dboe's avatar
dboe committed
129
130
        return tuple()

dboe's avatar
dboe committed
131
132
133
134
    def _kwargs(self) -> dict:  # pylint: disable=no-self-use
        """
        Used for allowing the polymorphic signature Class(obj) as a copy/casting constructor
        """
dboe's avatar
dboe committed
135
136
        return dict()

137
    _HIERARCHY_SEPARATOR = "::"
dboe's avatar
dboe committed
138

dboe's avatar
dboe committed
139
140
141
142
143
144
145
146
147
    def _as_dict(self) -> dict:
        """
        Get an object represenation in a dict format. This is necessary e.g. for saving the full
        file uniquely in the npz format

        Returns:
            dict: object packed as nested dictionary
        """
        content = {}
dboe's avatar
dboe committed
148
149

        # type
dboe's avatar
dboe committed
150
        content["type"] = type(self).__name__
dboe's avatar
dboe committed
151
152
153

        # args and kwargs
        for base_attr, iterable in [
154
155
156
            ("args", ((str(i), arg) for i, arg in enumerate(self._args()))),
            ("kwargs", self._kwargs().items()),
        ]:
dboe's avatar
dboe committed
157
158
            for attr, value in iterable:
                attr = base_attr + self._HIERARCHY_SEPARATOR + attr
159
                if hasattr(value, "_as_dict"):
dboe's avatar
dboe committed
160
                    part_dict = value._as_dict()  # pylint: disable=protected-access
dboe's avatar
dboe committed
161
                    for part_attr, part_value in part_dict.items():
dboe's avatar
dboe committed
162
163
164
                        content[
                            attr + self._HIERARCHY_SEPARATOR + part_attr
                        ] = part_value
dboe's avatar
dboe committed
165
                else:
dboe's avatar
dboe committed
166
167
                    content[attr] = value
        return content
dboe's avatar
dboe committed
168
169

    @classmethod
dboe's avatar
dboe committed
170
    def _from_dict(cls, content: dict):
dboe's avatar
dboe committed
171
        try:
dboe's avatar
dboe committed
172
            content.pop("type")
dboe's avatar
dboe committed
173
174
        except KeyError:
            # legacy
dboe's avatar
dboe committed
175
            return cls._from_dict_legacy(**content)
dboe's avatar
dboe committed
176
177

        here = {}
dboe's avatar
dboe committed
178
179
        for string in content:  # TOO no sortelist
            value = content[string]
dboe's avatar
dboe committed
180
181
182
183
184
185
186
187
188

            attr, _, end = string.partition(cls._HIERARCHY_SEPARATOR)
            key, _, end = end.partition(cls._HIERARCHY_SEPARATOR)
            if attr not in here:
                here[attr] = {}
            if key not in here[attr]:
                here[attr][key] = {}
            here[attr][key][end] = value

dboe's avatar
dboe committed
189
        # Do the recursion
dboe's avatar
dboe committed
190
191
        for attr in here:
            for key in here[attr]:
192
                if "type" in here[attr][key]:
dboe's avatar
dboe committed
193
                    obj_type = here[attr][key].get("type")
dboe's avatar
dboe committed
194
195
                    if isinstance(obj_type, np.ndarray):  # happens on np.load
                        obj_type = obj_type.tolist()
dboe's avatar
dboe committed
196
197
198
199
200
                    if isinstance(obj_type, bytes):
                        # asthonishingly, this is not necessary under linux.
                        # Found under nt. ???
                        obj_type = obj_type.decode("UTF-8")
                    obj_type = getattr(tfields, obj_type)
dboe's avatar
dboe committed
201
202
203
204
205
                    attr_value = (
                        obj_type._from_dict(  # pylint: disable=protected-access
                            here[attr][key]
                        )
                    )
dboe's avatar
dboe committed
206
                else:  # if len(here[attr][key]) == 1:
207
                    attr_value = here[attr][key].pop("")
dboe's avatar
dboe committed
208
209
                here[attr][key] = attr_value

dboe's avatar
dboe committed
210
        # Build the generic way
211
        args = here.pop("args", tuple())
dboe's avatar
dboe committed
212
        args = tuple(args[key] for key in sorted(args))
213
        kwargs = here.pop("kwargs", {})
dboe's avatar
dboe committed
214
215
216
217
218
        assert len(here) == 0
        obj = cls(*args, **kwargs)
        return obj

    @classmethod
dboe's avatar
dboe committed
219
    def _from_dict_legacy(cls, **content):
dboe's avatar
dboe committed
220
        """
dboe's avatar
dboe committed
221
222
        legacy method of _from_dict - Opposite of old _as_dict method
        which is overridden in this version
dboe's avatar
dboe committed
223
224
225
        """
        list_dict = {}
        kwargs = {}
dboe's avatar
dboe committed
226
227
        # De-Flatten the first layer of lists
        for key in sorted(list(content)):
dboe's avatar
dboe committed
228
229
230
231
232
233
234
235
236
237
238
            if "::" in key:
                attr, _, end = key.partition("::")
                if attr not in list_dict:
                    list_dict[attr] = {}

                index, _, end = end.partition("::")
                if not index.isdigit():
                    raise ValueError("None digit index given")
                index = int(index)
                if index not in list_dict[attr]:
                    list_dict[attr][index] = {}
dboe's avatar
dboe committed
239
                list_dict[attr][index][end] = content[key]
dboe's avatar
dboe committed
240
            else:
dboe's avatar
dboe committed
241
                kwargs[key] = content[key]
dboe's avatar
dboe committed
242

dboe's avatar
dboe committed
243
        # Build the lists (recursively)
dboe's avatar
dboe committed
244
245
246
247
248
        for key in list(list_dict):
            sub_dict = list_dict[key]
            list_dict[key] = []
            for index in sorted(list(sub_dict)):
                bulk_type = sub_dict[index].get("bulk_type")
dboe's avatar
dboe committed
249
                bulk_type = bulk_type.tolist()
dboe's avatar
dboe committed
250
251
252
253
254
                if isinstance(bulk_type, bytes):
                    # asthonishingly, this is not necessary under linux.
                    # Found under nt. ???
                    bulk_type = bulk_type.decode("UTF-8")
                bulk_type = getattr(tfields, bulk_type)
dboe's avatar
dboe committed
255
                list_dict[key].append(
dboe's avatar
dboe committed
256
                    bulk_type._from_dict_legacy(  # noqa: E501 pylint: disable=protected-access
dboe's avatar
dboe committed
257
                        **sub_dict[index]
dboe's avatar
dboe committed
258
                    )
dboe's avatar
dboe committed
259
                )
dboe's avatar
dboe committed
260

dboe's avatar
dboe committed
261
        with cls._bypass_setters(  # pylint: disable=protected-access,no-member
dboe's avatar
dboe committed
262
            "fields", demand_existence=False
dboe's avatar
dboe committed
263
        ):
dboe's avatar
dboe committed
264
            # Build the normal way
265
266
            bulk = kwargs.pop("bulk")
            bulk_type = kwargs.pop("bulk_type")
dboe's avatar
dboe committed
267
268
            obj = cls.__new__(cls, bulk, **kwargs)

dboe's avatar
dboe committed
269
            # Set list attributes
dboe's avatar
dboe committed
270
271
272
273
274
275
            for attr, list_value in list_dict.items():
                setattr(obj, attr, list_value)
        return obj


class AbstractNdarray(np.ndarray, AbstractObject):
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
276
277
278
279
    """
    All tensors and subclasses should derive from AbstractNdarray.
    AbstractNdarray implements all the inheritance specifics for np.ndarray
    Whene inheriting, three attributes are of interest:
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
280
281

    Attributes:
282
        __slots__ (List(str)): If you want to add attributes to
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
283
284
285
286
287
            your AbstractNdarray subclass, add the attribute name to __slots__
        __slot_defaults__ (list): if __slot_defaults__ is None, the
            defaults for the attributes in __slots__ will be None
            other values will be treaded as defaults to the corresponding
            arg at the same position in the __slots__ list.
288
        __slot_dtype__ (List(dtypes)): for the conversion of the
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
289
290
            args in __slots__ to numpy arrays. None values mean no
            conversion.
291
292
293
        __slot_setters__ (List(callable)): Because __slots__ and properties are
            mutually exclusive this is a possibility to take care of proper
            attribute handling. None will be passed for 'not set'.
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
294
295
296
297

    Args:
        array (array-like): input array
        **kwargs: arguments corresponding to __slots__
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
298

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
299
    TODO:
dboe's avatar
linting    
dboe committed
300
301
        * equality check
        * plot
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
302

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
303
    """
dboe's avatar
dboe committed
304

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
305
306
    __slots__ = []
    __slot_defaults__ = []
307
    __slot_dtypes__ = []
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
308
309
310
    __slot_setters__ = []

    def __new__(cls, array, **kwargs):  # pragma: no cover
dboe's avatar
dboe committed
311
312
313
        raise NotImplementedError(
            "{clsType} type must implement '__new__'".format(clsType=type(cls))
        )
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
314
315
316
317
318
319
320

    def __array_finalize__(self, obj):
        if obj is None:
            return
        for attr in self._iter_slots():
            setattr(self, attr, getattr(obj, attr, None))

dboe's avatar
dboe committed
321
    def __array_wrap__(self, out_arr, context=None):  # pylint: disable=arguments-differ
dboe's avatar
dboe committed
322
        return np.ndarray.__array_wrap__(  # pylint: disable=too-many-function-args
dboe's avatar
dboe committed
323
            self, out_arr, context
dboe's avatar
dboe committed
324
        )
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
325
326
327

    @classmethod
    def _iter_slots(cls):
dboe's avatar
dboe committed
328
        return [att for att in cls.__slots__ if att != "_cache"]
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
329
330
331
332
333

    @classmethod
    def _update_slot_kwargs(cls, kwargs):
        """
        set the defaults in kwargs according to __slot_defaults__
334
        and convert the kwargs according to __slot_dtypes__
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
335
        """
336
        slot_defaults = cls.__slot_defaults__ + [None] * (
dboe's avatar
dboe committed
337
338
            len(cls.__slots__) - len(cls.__slot_defaults__)
        )
339
340
        slot_dtypes = cls.__slot_dtypes__ + [None] * (
            len(cls.__slots__) - len(cls.__slot_dtypes__)
dboe's avatar
dboe committed
341
        )
342
        for attr, default, dtype in zip(cls.__slots__, slot_defaults, slot_dtypes):
dboe's avatar
dboe committed
343
            if attr == "_cache":
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
344
345
346
347
348
349
350
                continue
            if attr not in kwargs:
                kwargs[attr] = default
            if dtype is not None:
                try:
                    kwargs[attr] = np.array(kwargs[attr], dtype=dtype)
                except Exception as err:
dboe's avatar
dboe committed
351
352
                    raise ValueError(
                        str(attr) + str(dtype) + str(kwargs[attr]) + str(err)
dboe's avatar
dboe committed
353
                    ) from err
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
354
355
356
357
358
359
360
361

    def __setattr__(self, name, value):
        if name in self.__slots__:
            index = self.__slots__.index(name)
            try:
                setter = self.__slot_setters__[index]
            except IndexError:
                setter = None
362
363
            if isinstance(setter, str):
                setter = getattr(self, setter)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
364
365
366
367
            if setter is not None:
                value = setter(value)
        super(AbstractNdarray, self).__setattr__(name, value)

dboe's avatar
dboe committed
368
369
370
371
372
373
    def _args(self):
        return (np.array(self),)

    def _kwargs(self):
        return dict((attr, getattr(self, attr)) for attr in self._iter_slots())

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
374
375
    def __reduce__(self):
        """
dboe's avatar
dboe committed
376
377
        important for pickling (see `here <https://stackoverflow.com/questions/\
26598109/preserve-custom-attributes-when-pickling-subclass-of-numpy-array>`_)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
378

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
379
380
381
382
383
384
        Examples:
            >>> from tempfile import NamedTemporaryFile
            >>> import pickle
            >>> import tfields

            Build a dummy scalar field
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
385

dboe's avatar
dboe committed
386
387
388
389
390
391
            >>> scalars = tfields.Tensors([0, 1, 2])
            >>> vectors = tfields.Tensors([[0, 0, 0], [0, 0, 1], [0, -1, 0]])
            >>> scalar_field = tfields.TensorFields(
            ...     vectors,
            ...     scalars,
            ...     coord_sys='cylinder')
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
392
393

            Save it and restore it
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
394

395
            >>> out_file = NamedTemporaryFile(suffix='.pickle')
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
396

397
            >>> pickle.dump(scalar_field,
398
399
            ...             out_file)
            >>> _ = out_file.seek(0)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
400

401
            >>> sf = pickle.load(out_file)
402
            >>> sf.coord_sys == 'cylinder'
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
403
404
405
406
407
408
409
410
411
            True
            >>> sf.fields[0][2] == 2.
            True

        """
        # Get the parent's __reduce__ tuple
        pickled_state = super(AbstractNdarray, self).__reduce__()

        # Create our own tuple to pass to __setstate__
dboe's avatar
dboe committed
412
413
414
        new_state = pickled_state[2] + tuple(
            [getattr(self, slot) for slot in self._iter_slots()]
        )
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
415

dboe's avatar
dboe committed
416
417
        # Return a tuple that replaces the parent's __setstate__
        # tuple with our own
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
418
419
420
421
        return (pickled_state[0], pickled_state[1], new_state)

    def __setstate__(self, state):
        """
422
        Counterpart to __reduce__. Important for unpickling.
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
423
424
        """
        # Call the parent's __setstate__ with the other tuple elements.
425
        super(AbstractNdarray, self).__setstate__(state[0 : -len(self._iter_slots())])
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
426
427

        # set the __slot__ attributes
428
        valid_slot_attrs = list(self._iter_slots())
dboe's avatar
dboe committed
429
430
431
        # attributes that have been added later have not been pickled with the full information
        # and thus need to be excluded from the __setstate__ need to be in the same order as they
        # have been added to __slots__
432
        added_slot_attrs = ["name"]
dboe's avatar
dboe committed
433
434
        n_np = 5  # number of numpy array states
        n_old = len(valid_slot_attrs) - len(state[n_np:])
435
436
437
        if n_old > 0:
            for latest_index in range(n_old):
                new_slot = added_slot_attrs[-latest_index]
438
439
440
441
442
443
                warnings.warn(
                    "Slots with names '{new_slot}' appears to have "
                    "been added after the creation of the reduced "
                    "state. No corresponding state found in "
                    "__setstate__.".format(**locals())
                )
444
445
446
447
                valid_slot_attrs.pop(valid_slot_attrs.index(new_slot))
                setattr(self, new_slot, None)

        for slot_index, slot in enumerate(valid_slot_attrs):
dboe's avatar
dboe committed
448
            state_index = n_np + slot_index
449
            setattr(self, slot, state[state_index])
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
450

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
451
452
453
454
455
456
457
458
    @property
    def bulk(self):
        """
        The pure ndarray version of the actual state
            -> nothing attached
        """
        return np.array(self)

459
460
    @classmethod
    @contextmanager
461
    def _bypass_setters(cls, *slots, empty_means_all=True, demand_existence=False):
462
463
464
        """
        Temporarily remove the setter in __slot_setters__ corresponding to slot
        position in __slot__. You should know what you do, when using this.
465
466
467
468
469

        Args:
            *slots (str): attribute names in __slots__
            empty_means_all (bool): defines behaviour when slots is empty.
                When True: if slots is empty mute all slots in __slots__
dboe's avatar
dboe committed
470
471
            demand_existence (bool): if false do not check the existence of the
                slot in __slots__ - do nothing for that slot. Handle with care!
472
473
474
475
476
477
        """
        if not slots and empty_means_all:
            slots = cls.__slots__
        slot_indices = []
        setters = []
        for slot in slots:
478
            slot_index = cls.__slots__.index(slot) if slot in cls.__slots__ else None
dboe's avatar
dboe committed
479
480
481
            if slot_index is None:
                # slot not in cls.__slots__.
                if demand_existence:
482
                    raise ValueError("Slot {slot} not existing".format(**locals()))
dboe's avatar
dboe committed
483
                continue
484
485
486
487
488
489
490
            if len(cls.__slot_setters__) < slot_index + 1:
                # no setter to be found
                continue
            slot_indices.append(slot_index)
            setter = cls.__slot_setters__[slot_index]
            setters.append(setter)
            cls.__slot_setters__[slot_index] = None
491
        yield
492
493
        for slot_index, setter in zip(slot_indices, setters):
            cls.__slot_setters__[slot_index] = setter
494

dboe's avatar
dboe committed
495
    def copy(self, **kwargs):  # pylint: disable=arguments-differ
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
496
497
        """
        The standard ndarray copy does not copy slots. Correct for this.
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
498

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
499
500
        Examples:
            >>> import tfields
dboe's avatar
dboe committed
501
502
            >>> m = tfields.TensorMaps(
            ...     [[1,2,3], [3,3,3], [0,0,0], [5,6,7]],
dboe's avatar
dboe committed
503
            ...     [[1], [3], [0], [5]],
504
505
            ...     maps=[
            ...         ([[0, 1, 2], [1, 2, 3]], [21, 42]),
dboe's avatar
dboe committed
506
507
            ...         [[1]],
            ...         [[0, 1, 2, 3]]
508
            ...     ])
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
509
            >>> mc = m.copy()
dboe's avatar
dboe committed
510
511
            >>> mc.equal(m)
            True
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
512
513
            >>> mc is m
            False
dboe's avatar
dboe committed
514
515
516
517
            >>> mc.fields is m.fields
            False
            >>> mc.fields[0] is m.fields[0]
            False
dboe's avatar
dboe committed
518
            >>> mc.maps[3].fields[0] is m.maps[3].fields[0]
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
519
520
521
            False

        """
dboe's avatar
dboe committed
522
523
524
525
        if kwargs:
            raise NotImplementedError(
                "Copying with arguments {kwargs} not yet supported"
            )
dboe's avatar
dboe committed
526
527
        # works with __reduce__ / __setstate__
        return deepcopy(self)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
528
529


dboe's avatar
dboe committed
530
class Tensors(AbstractNdarray):  # pylint: disable=too-many-public-methods
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
531
532
    """
    Set of tensors with the same basis.
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
533

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
534
    TODO:
dboe's avatar
dboe committed
535
536
537
        * implement units, one unit for each dimension
        * implement automatic jacobian for metric calculation
        * implement multidimensional cross product
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
538

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
539
540
    Args:
        tensors: np.ndarray or AbstractNdarray subclass
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
541
542
        **kwargs:
            name: optional - custom name, can be anything
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
543

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
544
545
    Examples:
        >>> import numpy as np
546
        >>> import tfields
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
547
548

        Initialize a scalar range
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
549

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
550
551
552
553
554
        >>> scalars = tfields.Tensors([0, 1, 2])
        >>> scalars.rank == 0
        True

        Initialize vectors
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
555

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
556
557
558
559
560
        >>> vectors = tfields.Tensors([[0, 0, 0], [0, 0, 1], [0, -1, 0]])
        >>> vectors.rank == 1
        True
        >>> vectors.dim == 3
        True
561
        >>> assert vectors.coord_sys == 'cartesian'
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
562
563

        Initialize the Levi-Zivita Tensor
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
564

dboe's avatar
dboe committed
565
566
567
        >>> matrices = tfields.Tensors([[[0, 0, 0], [0, 0, 1], [0, -1, 0]],
        ...                             [[0, 0, -1], [0, 0, 0], [1, 0, 0]],
        ...                             [[0, 1, 0], [-1, 0, 0], [0, 0, 0]]])
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
568
569
570
571
572
573
574
575
        >>> matrices.shape == (3, 3, 3)
        True
        >>> matrices.rank == 2
        True
        >>> matrices.dim == 3
        True

        Initializing in different start coordinate system
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
576

dboe's avatar
dboe committed
577
578
        >>> cyl = tfields.Tensors([[5, np.arctan(4. / 3.), 42]],
        ...                       coord_sys='cylinder')
579
        >>> assert cyl.coord_sys == 'cylinder'
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
580
        >>> cyl.transform('cartesian')
581
        >>> assert cyl.coord_sys == 'cartesian'
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
582
583
584
585
586
587
        >>> cart = cyl
        >>> assert round(cart[0, 0], 10) == 3.
        >>> assert round(cart[0, 1], 10) == 4.
        >>> assert cart[0, 2] == 42

        Initialize with copy constructor keeps the coordinate system
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
588

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
589
590
        >>> with vectors.tmp_transform('cylinder'):
        ...     vect_cyl = tfields.Tensors(vectors)
591
592
        ...     assert vect_cyl.coord_sys == vectors.coord_sys
        >>> assert vect_cyl.coord_sys == 'cylinder'
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
593
594

        You can demand a special dimension.
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
595

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
596
597
598
599
600
601
602
603
        >>> _ = tfields.Tensors([[1, 2, 3]], dim=3)
        >>> _ = tfields.Tensors([[1, 2, 3]], dim=2)  # doctest: +ELLIPSIS
        Traceback (most recent call last):
            ...
        ValueError: Incorrect dimension: 3 given, 2 demanded.

        The dimension argument (dim) becomes necessary if you want to initialize
        an empty array
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
604

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
605
606
607
608
609
610
611
612
        >>> _ = tfields.Tensors([])  # doctest: +ELLIPSIS
        Traceback (most recent call last):
            ...
        ValueError: Empty tensors need dimension parameter 'dim'.
        >>> tfields.Tensors([], dim=7)
        Tensors([], shape=(0, 7), dtype=float64)

    """
613
614
615

    __slots__ = ["coord_sys", "name"]
    __slot_defaults__ = ["cartesian"]
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
616
617
    __slot_setters__ = [tfields.bases.get_coord_system_name]

dboe's avatar
dboe committed
618
    def __new__(cls, tensors, **kwargs):  # pylint: disable=too-many-branches
dboe's avatar
dboe committed
619
620
        dtype = kwargs.pop("dtype", None)
        order = kwargs.pop("order", None)
dboe's avatar
linting    
dboe committed
621
        dim_ = kwargs.pop("dim", None)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
622

dboe's avatar
dboe committed
623
        # copy constructor extracts the kwargs from tensors
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
624
        if issubclass(type(tensors), Tensors):
dboe's avatar
linting    
dboe committed
625
626
            if dim_ is not None:
                dim_ = tensors.dim
dboe's avatar
dboe committed
627
            coord_sys = kwargs.pop("coord_sys", tensors.coord_sys)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
628
            tensors = tensors.copy()
629
            tensors.transform(coord_sys)
630
631
            kwargs["coord_sys"] = coord_sys
            kwargs["name"] = kwargs.pop("name", tensors.name)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
632
633
634
635
            if dtype is None:
                dtype = tensors.dtype
        else:
            if dtype is None:
dboe's avatar
dboe committed
636
                if hasattr(tensors, "dtype"):
637
638
639
                    dtype = tensors.dtype
                else:
                    dtype = np.float64
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
640

dboe's avatar
dboe committed
641
        # demand iterable structure
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
642
643
        try:
            len(tensors)
dboe's avatar
dboe committed
644
        except TypeError as err:
dboe's avatar
dboe committed
645
            raise TypeError(
646
                "Iterable structure necessary." " Got {tensors}".format(**locals())
dboe's avatar
dboe committed
647
            ) from err
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
648

dboe's avatar
dboe committed
649
        # process empty inputs
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
650
651
652
        if len(tensors) == 0:
            if issubclass(type(tensors), tfields.Tensors):
                tensors = np.empty(tensors.shape, dtype=tensors.dtype)
dboe's avatar
linting    
dboe committed
653
654
            elif dim_ is not None:
                tensors = np.empty((0, dim_))
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
655
656
657
            if issubclass(type(tensors), np.ndarray):
                # np.empty
                pass
658
            elif hasattr(tensors, "shape"):
dboe's avatar
linting    
dboe committed
659
                dim_ = dim_(tensors)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
660
            else:
661
                raise ValueError("Empty tensors need dimension parameter 'dim'.")
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
662
663
664
665

        tensors = np.asarray(tensors, dtype=dtype, order=order)
        obj = tensors.view(cls)

dboe's avatar
linting    
dboe committed
666
667
        if dim_ is not None:
            if dim_ != obj.dim:
dboe's avatar
dboe committed
668
669
                raise ValueError(
                    "Incorrect dimension: {obj.dim} given,"
dboe's avatar
linting    
dboe committed
670
                    " {dim_} demanded.".format(**locals())
dboe's avatar
dboe committed
671
                )
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
672

dboe's avatar
dboe committed
673
        # update kwargs with defaults from slots
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
674
675
        cls._update_slot_kwargs(kwargs)

dboe's avatar
dboe committed
676
        # set kwargs to slots attributes
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
677
678
        for attr in kwargs:
            if attr not in cls._iter_slots():
dboe's avatar
dboe committed
679
680
681
682
                raise AttributeError(
                    "Keyword argument {attr} not accepted "
                    "for class {cls}".format(**locals())
                )
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
683
684
685
686
            setattr(obj, attr, kwargs[attr])

        return obj

687
688
689
690
    def __iter__(self):
        """
        Forwarding iterations to the bulk array. Otherwise __getitem__ would
        kick in and slow down imensely.
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
691

692
693
694
        Examples:
            >>> import tfields
            >>> vectors = tfields.Tensors([[0, 0, 0], [0, 0, 1], [0, -1, 0]])
dboe's avatar
dboe committed
695
696
            >>> scalar_field = tfields.TensorFields(
            ...     vectors, [42, 21, 10.5], [1, 2, 3])
697
698
699
700
701
702
703
            >>> [(point.rank, point.dim) for point in scalar_field]
            [(0, 1), (0, 1), (0, 1)]

        """
        for index in range(len(self)):
            yield super(Tensors, self).__getitem__(index).view(Tensors)

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
704
705
706
707
    @classmethod
    def merged(cls, *objects, **kwargs):
        """
        Factory method
dboe's avatar
dboe committed
708
        Merges all input arguments to one object
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
709

710
711
712
        Args:
            return_templates (bool): return the templates which can be used
                together with cut to retrieve the original objects
dboe's avatar
dboe committed
713
714
            dim (int):
            **kwargs: passed to cls
715

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
716
717
718
719
720
        Examples:
            >>> import numpy as np
            >>> import tfields
            >>> import tfields.bases

721
722
            The new object with turn out in the most frequent coordinate
            system if not specified explicitly
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
723

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
724
            >>> vec_a = tfields.Tensors([[0, 0, 0], [0, 0, 1], [0, -1, 0]])
dboe's avatar
dboe committed
725
726
727
728
729
730
            >>> vec_b = tfields.Tensors([[5, 4, 1]],
            ...     coord_sys=tfields.bases.cylinder)
            >>> vec_c = tfields.Tensors([[4, 2, 3]],
            ...     coord_sys=tfields.bases.cylinder)
            >>> merge = tfields.Tensors.merged(
            ...     vec_a, vec_b, vec_c, [[2, 0, 1]])
731
            >>> assert merge.coord_sys == 'cylinder'
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
732
733
734
735
736
737
738
739
            >>> assert merge.equal([[0, 0, 0],
            ...                     [0, 0, 1],
            ...                     [1, -np.pi / 2, 0],
            ...                     [5, 4, 1],
            ...                     [4, 2, 3],
            ...                     [2, 0, 1]])

            Merge also shifts the maps to still refer to the same tensors
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
740

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
741
742
            >>> tm_a = tfields.TensorMaps(merge, maps=[[[0, 1, 2]]])
            >>> tm_b = tm_a.copy()
743
            >>> assert tm_a.coord_sys == 'cylinder'
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
744
            >>> tm_merge = tfields.TensorMaps.merged(tm_a, tm_b)
745
            >>> assert tm_merge.coord_sys == 'cylinder'
dboe's avatar
dboe committed
746
            >>> assert tm_merge.maps[3].equal([[0, 1, 2],
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
747
748
749
            ...                               list(range(len(merge),
            ...                                          len(merge) + 3,
            ...                                          1))])
dboe's avatar
dboe committed
750

751
752
            >>> obj_list = [tfields.Tensors([[1, 2, 3]],
            ...             coord_sys=tfields.bases.CYLINDER),
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
753
754
            ...             tfields.Tensors([[3] * 3]),
            ...             tfields.Tensors([[5, 1, 3]])]
755
756
            >>> merge2 = tfields.Tensors.merged(
            ...     *obj_list, coord_sys=tfields.bases.CARTESIAN)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
757
758
            >>> assert merge2.equal([[-0.41614684, 0.90929743, 3.],
            ...                      [3, 3, 3], [5, 1, 3]], atol=1e-8)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
759

760
761
762
763
764
765
766
767
768
            The return_templates argument allows to retrieve a template which
            can be used with the cut method.

            >>> merge, templates = tfields.Tensors.merged(
            ...     vec_a, vec_b, vec_c, return_templates=True)
            >>> assert merge.cut(templates[0]).equal(vec_a)
            >>> assert merge.cut(templates[1]).equal(vec_b)
            >>> assert merge.cut(templates[2]).equal(vec_c)

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
769
770
        """

dboe's avatar
dboe committed
771
        # get most frequent coord_sys or predefined coord_sys
dboe's avatar
dboe committed
772
        coord_sys = kwargs.get("coord_sys", None)
773
        return_templates = kwargs.pop("return_templates", False)
774
        if coord_sys is None:
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
775
            bases = []
dboe's avatar
dboe committed
776
            for tensors in objects:
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
777
                try:
dboe's avatar
dboe committed
778
                    bases.append(tensors.coord_sys)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
779
780
781
                except AttributeError:
                    pass
            if bases:
782
                # get most frequent coord_sys
783
                coord_sys = sorted(bases, key=Counter(bases).get, reverse=True)[0]
dboe's avatar
dboe committed
784
                kwargs["coord_sys"] = coord_sys
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
785
            else:
786
                default = cls.__slot_defaults__[cls.__slots__.index("coord_sys")]
dboe's avatar
dboe committed
787
                kwargs["coord_sys"] = default
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
788

dboe's avatar
dboe committed
789
790
791
        # transform all raw inputs to cls type with correct coord_sys. Also
        # automatically make a copy of those instances that are of the correct
        # type already.
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
792
        objects = [cls.__new__(cls, t, **kwargs) for t in objects]
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
793

dboe's avatar
dboe committed
794
795
        # check rank and dimension equality
        if not len(set(t.rank for t in objects)) == 1:
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
796
            raise TypeError("Tensors must have the same rank for merging.")
dboe's avatar
dboe committed
797
        if not len(set(t.dim for t in objects)) == 1:
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
798
799
            raise TypeError("Tensors must have the same dimension for merging.")

dboe's avatar
dboe committed
800
801
        # merge all objects
        remaining_objects = objects[1:] or []
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
802
803
        tensors = objects[0]

dboe's avatar
dboe committed
804
        for i, obj in enumerate(remaining_objects):
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
805
806
            tensors = np.append(tensors, obj, axis=0)

807
        if len(tensors) == 0 and not kwargs.get("dim", None):
808
809
            # if you can not determine the tensor dimension, search for the
            # first object with some entries
810
            kwargs["dim"] = dim(objects[0])
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
811

812
        inst = cls.__new__(cls, tensors, **kwargs)
dboe's avatar
dboe committed
813
        if not return_templates:  # pylint: disable=no-else-return
814
            return inst
815
816
        else:
            tensor_lengths = [len(o) for o in objects]
817
            cum_tensor_lengths = [sum(tensor_lengths[:i]) for i in range(len(objects))]
818
819
            templates = [
                tfields.TensorFields(
820
                    np.empty((len(obj), 0)),
821
822
823
824
                    np.arange(tensor_lengths[i]) + cum_tensor_lengths[i],
                )
                for i, obj in enumerate(objects)
            ]
825
            return inst, templates
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
826
827
828
829
830

    @classmethod
    def grid(cls, *base_vectors, **kwargs):
        """
        Args:
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
831
832
833
834
835
836
837
            *base_vectors (Iterable): base coordinates. The amount of base
                vectors defines the dimension

            **kwargs:
                iter_order (list): order in which the iteration will be done.
                    Frequency rises with position in list. default is [0, 1, 2]
                    iteration will be done like::
dboe's avatar
dboe committed
838

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
839
840
841
842
843
844
                    for v0 in base_vectors[iter_order[0]]:
                        for v1 in base_vectors[iter_order[1]]:
                            for v2 in base_vectors[iter_order[2]]:
                                coords0.append(locals()['v%i' % iter_order[0]])
                                coords1.append(locals()['v%i' % iter_order[1]])
                                coords2.append(locals()['v%i' % iter_order[2]])
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
845
846
847

        Examples:
            Initilaize using the mgrid notation
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
848

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
849
850
851
852
853
854
855
856
857
858
859
            >>> import tfields
            >>> mgrid = tfields.Tensors.grid((0, 1, 2j), (3, 4, 2j), (6, 7, 2j))
            >>> mgrid.equal([[0, 3, 6],
            ...              [0, 3, 7],
            ...              [0, 4, 6],
            ...              [0, 4, 7],
            ...              [1, 3, 6],
            ...              [1, 3, 7],
            ...              [1, 4, 6],
            ...              [1, 4, 7]])
            True
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
860
861
862

            Lists or arrays are accepted also.
            Furthermore, the iteration order can be changed
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
863

dboe's avatar
dboe committed
864
865
866
            >>> lins = tfields.Tensors.grid(
            ...     np.linspace(3, 4, 2), np.linspace(0, 1, 2),
            ...     np.linspace(6, 7, 2), iter_order=[1, 0, 2])
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
            >>> lins.equal([[3, 0, 6],
            ...             [3, 0, 7],
            ...             [4, 0, 6],
            ...             [4, 0, 7],
            ...             [3, 1, 6],
            ...             [3, 1, 7],
            ...             [4, 1, 6],
            ...             [4, 1, 7]])
            True
            >>> lins2 = tfields.Tensors.grid(np.linspace(0, 1, 2),
            ...                              np.linspace(3, 4, 2),
            ...                              np.linspace(6, 7, 2),
            ...                              iter_order=[2, 0, 1])
            >>> lins2.equal([[0, 3, 6],
            ...              [0, 4, 6],
            ...              [1, 3, 6],
            ...              [1, 4, 6],
            ...              [0, 3, 7],
            ...              [0, 4, 7],
            ...              [1, 3, 7],
            ...              [1, 4, 7]])
            True

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
890
891
            When given the coord_sys argument, the grid is performed in the
            given coorinate system:
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
892

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
893
894
895
896
897
898
899
900
901
            >>> lins3 = tfields.Tensors.grid(np.linspace(4, 9, 2),
            ...                              np.linspace(np.pi/2, np.pi/2, 1),
            ...                              np.linspace(4, 4, 1),
            ...                              iter_order=[2, 0, 1],
            ...                              coord_sys=tfields.bases.CYLINDER)
            >>> assert lins3.coord_sys == 'cylinder'
            >>> lins3.transform('cartesian')
            >>> assert np.array_equal(lins3[:, 1], [4, 9])

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
902
        """
dboe's avatar
dboe committed
903
        cls_kwargs = {
904
            attr: kwargs.pop(attr) for attr in list(kwargs) if attr in cls.__slots__
dboe's avatar
dboe committed
905
906
907
908
        }
        inst = cls.__new__(
            cls, tfields.lib.grid.igrid(*base_vectors, **kwargs), **cls_kwargs
        )
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
        return inst

    @property
    def rank(self):
        """
        Tensor rank
        """
        return rank(self)

    @property
    def dim(self):
        """
        Manifold dimension
        """
        return dim(self)

925
    def transform(self, coord_sys):
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
926
927
        """
        Args:
928
            coord_sys (str)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
929
930
931
932
933
934

        Examples:
            >>> import numpy as np
            >>> import tfields

            CARTESIAN to SPHERICAL
dboe's avatar
dboe committed
935
936
            >>> t = tfields.Tensors([[1, 2, 2], [1, 0, 0], [0, 0, -1],
            ...                      [0, 0, 1], [0, 0, 0]])
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
937
938
939
            >>> t.transform('spherical')

            r
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
940

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
941
942
943
            >>> assert t[0, 0] == 3

            phi
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
944

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
945
946
947
948
            >>> assert t[1, 1] == 0.
            >>> assert t[2, 1] == 0.

            theta is 0 at (0, 0, 1) and pi / 2 at (0, 0, -1)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
949

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
950
951
952
953
954
            >>> assert round(t[1, 2], 10) == round(0, 10)
            >>> assert t[2, 2] == -np.pi / 2
            >>> assert t[3, 2] == np.pi / 2

            theta is defined 0 for R == 0
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
955

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
956
957
958
959
960
            >>> assert t[4, 0] == 0.
            >>> assert t[4, 2] == 0.


            CARTESIAN to CYLINDER
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
961

dboe's avatar
dboe committed
962
963
            >>> tCart = tfields.Tensors([[3, 4, 42], [1, 0, 0], [0, 1, -1],
            ...                          [-1, 0, 1], [0, 0, 0]])
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
964
965
            >>> t_cyl = tCart.copy()
            >>> t_cyl.transform('cylinder')
966
            >>> assert t_cyl.coord_sys == 'cylinder'
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
967
968

            R
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
969

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
970
971
972
973
974
975
            >>> assert t_cyl[0, 0] == 5
            >>> assert t_cyl[1, 0] == 1
            >>> assert t_cyl[2, 0] == 1
            >>> assert t_cyl[4, 0] == 0

            Phi
dboe's avatar
dboe committed
976

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
977
978
979
980
981
982
            >>> assert round(t_cyl[0, 1], 10) == round(np.arctan(4. / 3), 10)
            >>> assert t_cyl[1, 1] == 0
            >>> assert round(t_cyl[2, 1], 10) == round(np.pi / 2, 10)
            >>> assert t_cyl[1, 1] == 0

            Z
dboe's avatar
dboe committed
983

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
984
985
986
987
            >>> assert t_cyl[0, 2] == 42
            >>> assert t_cyl[2, 2] == -1

            >>> t_cyl.transform('cartesian')
988
            >>> assert t_cyl.coord_sys == 'cartesian'
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
989
990
991
            >>> assert t_cyl[0, 0] == 3

        """
dboe's avatar
dboe committed
992
        if self.rank == 0 or any(s == 0 for s in self.shape):
dboe's avatar
dboe committed
993
            # scalar or empty
dboe's avatar
dboe committed
994
            self.coord_sys = coord_sys  # pylint: disable=attribute-defined-outside-init
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
995
            return
dboe's avatar
dboe committed
996
997
998
        if self.coord_sys == coord_sys:
            # already correct
            return
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
999

1000
1001
        tfields.bases.transform(self, self.coord_sys, coord_sys)
        # self[:] = tfields.bases.transform(self, self.coord_sys, coord_sys)
dboe's avatar
dboe committed
1002
        self.coord_sys = coord_sys  # pylint: disable=attribute-defined-outside-init
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1003
1004

    @contextmanager
1005
    def tmp_transform(self, coord_sys):
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1006
        """
1007
        Temporarily change the coord_sys to another coord_sys and change it back at exit
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1008
1009
        This method is for cleaner code only.
        No speed improvements go with this.
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1010

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1011
1012
        Args:
            see transform
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1013

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1014
1015
        Examples:
            >>> import tfields
1016
            >>> p = tfields.Tensors([[1,2,3]], coord_sys=tfields.bases.SPHERICAL)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1017
            >>> with p.tmp_transform(tfields.bases.CYLINDER):
1018
1019
            ...     assert p.coord_sys == tfields.bases.CYLINDER
            >>> assert p.coord_sys == tfields.bases.SPHERICAL
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1020
1021

        """
dboe's avatar
dboe committed
1022
1023
        base_before = self.coord_sys
        if base_before == coord_sys:
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1024
1025
            yield
        else:
1026
            self.transform(coord_sys)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1027
1028
1029

            yield

dboe's avatar
dboe committed
1030
            self.transform(base_before)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1031
1032
1033
1034

    def mirror(self, coordinate, condition=None):
        """
        Reflect/Mirror the entries meeting <condition> at <coordinate> = 0
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1035

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1036
1037
        Args:
            coordinate (int): coordinate index
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1038

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1039
1040
1041
1042
1043
1044
        Examples:
            >>> import tfields
            >>> p = tfields.Tensors([[1., 2., 3.], [4., 5., 6.], [1, 2, -6]])
            >>> p.mirror(1)
            >>> assert p.equal([[1, -2, 3], [4, -5,  6], [1, -2, -6]])

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1045
1046
            multiple coordinates can be mirrored at the same time
            i.e. a point mirrorion would be
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1047

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1048
1049
1050
1051
1052
            >>> p = tfields.Tensors([[1., 2., 3.], [4., 5., 6.], [1, 2, -6]])
            >>> p.mirror([0,2])
            >>> assert p.equal([[-1, 2, -3], [-4, 5, -6], [-1, 2., 6.]])

            You can give a condition as mask or as str.
dboe's avatar
dboe committed
1053
1054
            The mirroring will only be applied to the points meeting the
            condition.
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1055

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1056
1057
            >>> import sympy
            >>> x, y, z = sympy.symbols('x y z')