core.py 96.8 KB
Newer Older
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1
2
3
4
5
6
7
8
#!/usr/bin/env
# encoding: utf-8
"""
Author:     Daniel Boeckenhoff
Mail:       daniel.boeckenhoff@ipp.mpg.de

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
    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>`_
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
14
"""
dboe's avatar
dboe committed
15
# builtin
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
16
17
18
19
20
import warnings
import pathlib
from six import string_types
from contextlib import contextmanager
from collections import Counter
dboe's avatar
dboe committed
21
from copy import deepcopy
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
22

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

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
30
import tfields.bases
dboe's avatar
dboe committed
31
32

np.seterr(all="warn", over="raise")
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
33
34
35
36
37
38


def rank(tensor):
    """
    Tensor rank
    """
dboe's avatar
dboe committed
39
    tensor = np.asarray(tensor)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
40
41
42
43
44
45
46
    return len(tensor.shape) - 1


def dim(tensor):
    """
    Manifold dimension
    """
dboe's avatar
dboe committed
47
    tensor = np.asarray(tensor)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
48
49
50
51
52
    if rank(tensor) == 0:
        return 1
    return tensor.shape[1]


dboe's avatar
dboe committed
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
class AbstractObject(object):
    def save(self, path, *args, **kwargs):
        """
        Saving by redirecting to the correct save method depending on path

        Args:
            path (str or buffer)
            *args:
                forwarded to extension specific method
            **kwargs:
                extension (str): only needed if path is buffer
                ... remaining:forwarded to extension specific method
        """
        # get the extension
        if isinstance(path, (string_types, pathlib.Path)):
            extension = pathlib.Path(path).suffix.lstrip(".")
        else:
            raise ValueError("Wrong path type {0}".format(type(path)))
        path = str(path)

        # get the save method
        try:
            save_method = getattr(self, "_save_{extension}".format(**locals()))
dboe's avatar
dboe committed
76
        except AttributeError:
dboe's avatar
dboe committed
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
            raise NotImplementedError(
                "Can not find save method for extension: "
                "{extension}.".format(**locals())
            )

        path = rna.path.resolve(path)
        return save_method(path, **kwargs)

    @classmethod
    def load(cls, path, *args, **kwargs):
        """
        load a file as a tensors object.

        Args:
            path (str or buffer)
            *args:
                forwarded to extension specific method
            **kwargs:
                extension (str): only needed if path is buffer
                ... remaining:forwarded to extension specific method
        """
        if isinstance(path, (string_types, pathlib.Path)):
            extension = pathlib.Path(path).suffix.lstrip(".")
            path = str(path)
            path = rna.path.resolve(path)
        else:
            extension = kwargs.pop("extension", "npz")

        try:
            load_method = getattr(cls, "_load_{e}".format(e=extension))
dboe's avatar
dboe committed
107
        except AttributeError:
dboe's avatar
dboe committed
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
            raise NotImplementedError(
                "Can not find load method for extension: "
                "{extension}.".format(**locals())
            )
        return load_method(path, *args, **kwargs)

    def _save_npz(self, path, **kwargs):
        """
        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
147
            >>> assert m.maps[3].dtype == m1.maps[3].dtype
dboe's avatar
dboe committed
148
149
150
151
152
153
154

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

        """
dboe's avatar
dboe committed
155
        content_dict = self._as_dict()
dboe's avatar
dboe committed
156
        content_dict['tfields_version'] = tfields.__version__
dboe's avatar
dboe committed
157
158
159
160
161
162
163
164
165
166
167
168
        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
        """
        # TODO: think about allow_pickle, wheter it really should be True or
        # wheter we could avoid pickling (potential security issue)
        load_kwargs.setdefault('allow_pickle', True)
        np_file = np.load(path, **load_kwargs)
dboe's avatar
dboe committed
169
170
171
        d = dict(np_file)
        d.pop('tfields_version', None)
        return cls._from_dict(d)
dboe's avatar
dboe committed
172
173
174
175
176
177
178
179
180

    def _args(self) -> tuple:
        return tuple()

    def _kwargs(self) -> dict:
        return dict()

    _HIERARCHY_SEPARATOR = '::'

dboe's avatar
dboe committed
181
    def _as_dict(self):
dboe's avatar
dboe committed
182
183
184
185
186
187
188
189
190
191
192
193
        d = {}

        # type
        d["type"] = type(self).__name__

        # args and kwargs
        for base_attr, iterable in [
                ('args', ((str(i), arg)
                          for i, arg in enumerate(self._args()))),
                ('kwargs', self._kwargs().items())]:
            for attr, value in iterable:
                attr = base_attr + self._HIERARCHY_SEPARATOR + attr
dboe's avatar
dboe committed
194
195
                if hasattr(value, '_as_dict'):
                    part_dict = value._as_dict()
dboe's avatar
dboe committed
196
197
198
199
200
201
202
203
204
                    for part_attr, part_value in part_dict.items():
                        d[
                            attr + self._HIERARCHY_SEPARATOR + part_attr
                        ] = part_value
                else:
                    d[attr] = value
        return d

    @classmethod
dboe's avatar
dboe committed
205
206
207
208
209
210
    def _from_dict(cls, d: dict):
        try:
            d.pop('type')
        except KeyError:
            # legacy
            return cls._from_dict_legacy(**d)
dboe's avatar
dboe committed
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228

        here = {}
        for string in d:  # TOO no sortelist
            value = d[string]

            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

        """
        Do the recursion
        """
        for attr in here:
            for key in here[attr]:
dboe's avatar
dboe committed
229
                if 'type' in here[attr][key]:
dboe's avatar
dboe committed
230
                    obj_type = here[attr][key].get("type")
dboe's avatar
dboe committed
231
232
                    if isinstance(obj_type, np.ndarray):  # happens on np.load
                        obj_type = obj_type.tolist()
dboe's avatar
dboe committed
233
234
235
236
237
                    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
238
                    attr_value = obj_type._from_dict(here[attr][key])
dboe's avatar
dboe committed
239
                else:  # if len(here[attr][key]) == 1:
dboe's avatar
dboe committed
240
                    attr_value = here[attr][key].pop('')
dboe's avatar
dboe committed
241
242
243
244
245
246
247
248
249
250
251
252
253
                here[attr][key] = attr_value

        '''
        Build the generic way
        '''
        args = here.pop('args', tuple())
        args = tuple(args[key] for key in sorted(args))
        kwargs = here.pop('kwargs', {})
        assert len(here) == 0
        obj = cls(*args, **kwargs)
        return obj

    @classmethod
dboe's avatar
dboe committed
254
    def _from_dict_legacy(cls, **d):
dboe's avatar
dboe committed
255
        """
dboe's avatar
dboe committed
256
257
        legacy method of _from_dict - Opposite of old _as_dict method
        which is overridden in this version
dboe's avatar
dboe committed
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
        """
        list_dict = {}
        kwargs = {}
        """
        De-Flatten the first layer of lists
        """
        for key in sorted(list(d)):
            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] = {}
                list_dict[attr][index][end] = d[key]
            else:
                kwargs[key] = d[key]

        """
        Build the lists (recursively)
        """
        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
288
                bulk_type = bulk_type.tolist()
dboe's avatar
dboe committed
289
290
291
292
293
                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
294
                list_dict[key].append(bulk_type._from_dict_legacy(**sub_dict[index]))
dboe's avatar
dboe committed
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312

        with cls._bypass_setters('fields', demand_existence=False):
            '''
            Build the normal way
            '''
            bulk = kwargs.pop('bulk')
            bulk_type = kwargs.pop('bulk_type')
            obj = cls.__new__(cls, bulk, **kwargs)

            '''
            Set list attributes
            '''
            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
313
314
315
316
    """
    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
317
318

    Attributes:
319
        __slots__ (List(str)): If you want to add attributes to
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
320
321
322
323
324
            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.
325
        __slot_dtype__ (List(dtypes)): for the conversion of the
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
326
327
            args in __slots__ to numpy arrays. None values mean no
            conversion.
328
329
330
        __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
331
332
333
334

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

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
336
337
    TODO:
        equality check
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
338

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
339
    """
dboe's avatar
dboe committed
340

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
341
342
    __slots__ = []
    __slot_defaults__ = []
343
    __slot_dtypes__ = []
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
344
345
346
    __slot_setters__ = []

    def __new__(cls, array, **kwargs):  # pragma: no cover
dboe's avatar
dboe committed
347
348
349
        raise NotImplementedError(
            "{clsType} type must implement '__new__'".format(clsType=type(cls))
        )
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
350
351
352
353
354
355
356
357
358
359
360
361

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

    def __array_wrap__(self, out_arr, context=None):
        return np.ndarray.__array_wrap__(self, out_arr, context)

    @classmethod
    def _iter_slots(cls):
dboe's avatar
dboe committed
362
        return [att for att in cls.__slots__ if att != "_cache"]
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
363
364
365
366
367

    @classmethod
    def _update_slot_kwargs(cls, kwargs):
        """
        set the defaults in kwargs according to __slot_defaults__
368
        and convert the kwargs according to __slot_dtypes__
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
369
        """
370
        slot_defaults = cls.__slot_defaults__ + [None] * (
dboe's avatar
dboe committed
371
372
            len(cls.__slots__) - len(cls.__slot_defaults__)
        )
373
374
        slot_dtypes = cls.__slot_dtypes__ + [None] * (
            len(cls.__slots__) - len(cls.__slot_dtypes__)
dboe's avatar
dboe committed
375
376
        )
        for attr, default, dtype in zip(
377
            cls.__slots__, slot_defaults, slot_dtypes
dboe's avatar
dboe committed
378
379
        ):
            if attr == "_cache":
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
380
381
382
383
384
385
386
                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
387
388
389
                    raise ValueError(
                        str(attr) + str(dtype) + str(kwargs[attr]) + str(err)
                    )
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
390
391
392
393
394
395
396
397

    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
398
399
            if isinstance(setter, str):
                setter = getattr(self, setter)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
400
401
402
403
            if setter is not None:
                value = setter(value)
        super(AbstractNdarray, self).__setattr__(name, value)

dboe's avatar
dboe committed
404
405
406
407
408
409
    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
410
411
    def __reduce__(self):
        """
dboe's avatar
dboe committed
412
413
        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
414

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
415
416
417
418
419
420
        Examples:
            >>> from tempfile import NamedTemporaryFile
            >>> import pickle
            >>> import tfields

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

dboe's avatar
dboe committed
422
423
424
425
426
427
            >>> 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
428
429

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

431
            >>> out_file = NamedTemporaryFile(suffix='.pickle')
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
432

433
            >>> pickle.dump(scalar_field,
434
435
            ...             out_file)
            >>> _ = out_file.seek(0)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
436

437
            >>> sf = pickle.load(out_file)
438
            >>> sf.coord_sys == 'cylinder'
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
439
440
441
442
443
444
445
446
447
            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
448
449
450
        new_state = pickled_state[2] + tuple(
            [getattr(self, slot) for slot in self._iter_slots()]
        )
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
451

dboe's avatar
dboe committed
452
453
        # Return a tuple that replaces the parent's __setstate__
        # tuple with our own
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
454
455
456
457
        return (pickled_state[0], pickled_state[1], new_state)

    def __setstate__(self, state):
        """
458
        Counterpart to __reduce__. Important for unpickling.
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
459
460
        """
        # Call the parent's __setstate__ with the other tuple elements.
dboe's avatar
dboe committed
461
        super(AbstractNdarray, self).__setstate__(
dboe's avatar
dboe committed
462
            state[0:-len(self._iter_slots())]
dboe's avatar
dboe committed
463
        )
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
464
465

        # set the __slot__ attributes
466
        valid_slot_attrs = list(self._iter_slots())
dboe's avatar
dboe committed
467
468
469
470
471
472
        """
        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__
        """
        added_slot_attrs = ['name']
dboe's avatar
dboe committed
473
474
        n_np = 5  # number of numpy array states
        n_old = len(valid_slot_attrs) - len(state[n_np:])
475
476
477
        if n_old > 0:
            for latest_index in range(n_old):
                new_slot = added_slot_attrs[-latest_index]
dboe's avatar
dboe committed
478
479
480
481
                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__."
482
483
484
485
486
                              .format(**locals()))
                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
487
            state_index = n_np + slot_index
488
            setattr(self, slot, state[state_index])
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
489

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
490
491
492
493
494
495
496
497
    @property
    def bulk(self):
        """
        The pure ndarray version of the actual state
            -> nothing attached
        """
        return np.array(self)

498
499
    @classmethod
    @contextmanager
dboe's avatar
dboe committed
500
501
502
    def _bypass_setters(cls, *slots,
                        empty_means_all=True,
                        demand_existence=False):
503
504
505
        """
        Temporarily remove the setter in __slot_setters__ corresponding to slot
        position in __slot__. You should know what you do, when using this.
506
507
508
509
510

        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
511
512
            demand_existence (bool): if false do not check the existence of the
                slot in __slots__ - do nothing for that slot. Handle with care!
513
514
515
516
517
518
        """
        if not slots and empty_means_all:
            slots = cls.__slots__
        slot_indices = []
        setters = []
        for slot in slots:
dboe's avatar
dboe committed
519
520
521
522
523
524
525
526
            slot_index = cls.__slots__.index(slot)\
                if slot in cls.__slots__ else None
            if slot_index is None:
                # slot not in cls.__slots__.
                if demand_existence:
                    raise ValueError(
                        "Slot {slot} not existing".format(**locals()))
                continue
527
528
529
530
531
532
533
            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
534
        yield
535
536
        for slot_index, setter in zip(slot_indices, setters):
            cls.__slot_setters__[slot_index] = setter
537

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
538
539
540
    def copy(self, *args, **kwargs):
        """
        The standard ndarray copy does not copy slots. Correct for this.
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
541

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
542
543
        Examples:
            >>> import tfields
dboe's avatar
dboe committed
544
545
            >>> m = tfields.TensorMaps(
            ...     [[1,2,3], [3,3,3], [0,0,0], [5,6,7]],
dboe's avatar
dboe committed
546
            ...     [[1], [3], [0], [5]],
547
548
            ...     maps=[
            ...         ([[0, 1, 2], [1, 2, 3]], [21, 42]),
dboe's avatar
dboe committed
549
550
            ...         [[1]],
            ...         [[0, 1, 2, 3]]
551
            ...     ])
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
552
            >>> mc = m.copy()
dboe's avatar
dboe committed
553
554
            >>> mc.equal(m)
            True
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
555
556
            >>> mc is m
            False
dboe's avatar
dboe committed
557
558
559
560
            >>> mc.fields is m.fields
            False
            >>> mc.fields[0] is m.fields[0]
            False
dboe's avatar
dboe committed
561
            >>> mc.maps[3].fields[0] is m.maps[3].fields[0]
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
562
563
564
            False

        """
dboe's avatar
dboe committed
565
566
        # works with __reduce__ / __setstate__
        return deepcopy(self)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
567
568
569
570
571


class Tensors(AbstractNdarray):
    """
    Set of tensors with the same basis.
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
572

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
573
574
    TODO:
        all slot args should be protected -> _base
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
575

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
576
577
    Args:
        tensors: np.ndarray or AbstractNdarray subclass
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
578
579
        **kwargs:
            name: optional - custom name, can be anything
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
580

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
581
582
    Examples:
        >>> import numpy as np
583
        >>> import tfields
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
584
585

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

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
587
588
589
590
591
        >>> scalars = tfields.Tensors([0, 1, 2])
        >>> scalars.rank == 0
        True

        Initialize vectors
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
592

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
593
594
595
596
597
        >>> vectors = tfields.Tensors([[0, 0, 0], [0, 0, 1], [0, -1, 0]])
        >>> vectors.rank == 1
        True
        >>> vectors.dim == 3
        True
598
        >>> assert vectors.coord_sys == 'cartesian'
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
599
600

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

602
603
604
605
        >>> 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
606
607
608
609
610
611
612
613
        >>> 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
614

dboe's avatar
dboe committed
615
616
        >>> cyl = tfields.Tensors([[5, np.arctan(4. / 3.), 42]],
        ...                       coord_sys='cylinder')
617
        >>> assert cyl.coord_sys == 'cylinder'
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
618
        >>> cyl.transform('cartesian')
619
        >>> assert cyl.coord_sys == 'cartesian'
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
620
621
622
623
624
625
        >>> 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
626

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
627
628
        >>> with vectors.tmp_transform('cylinder'):
        ...     vect_cyl = tfields.Tensors(vectors)
629
630
        ...     assert vect_cyl.coord_sys == vectors.coord_sys
        >>> assert vect_cyl.coord_sys == 'cylinder'
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
631
632

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

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
634
635
636
637
638
639
640
641
        >>> _ = 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
642

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
643
644
645
646
647
648
649
650
        >>> _ = 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)

    """
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
651
    __slots__ = ['coord_sys', 'name']
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
652
653
654
655
    __slot_defaults__ = ['cartesian']
    __slot_setters__ = [tfields.bases.get_coord_system_name]

    def __new__(cls, tensors, **kwargs):
dboe's avatar
dboe committed
656
657
658
        dtype = kwargs.pop("dtype", None)
        order = kwargs.pop("order", None)
        dim = kwargs.pop("dim", None)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
659

dboe's avatar
dboe committed
660
        """ copy constructor extracts the kwargs from tensors"""
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
661
662
663
        if issubclass(type(tensors), Tensors):
            if dim is not None:
                dim = tensors.dim
dboe's avatar
dboe committed
664
            coord_sys = kwargs.pop("coord_sys", tensors.coord_sys)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
665
            tensors = tensors.copy()
666
667
            tensors.transform(coord_sys)
            kwargs['coord_sys'] = coord_sys
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
668
            kwargs['name'] = kwargs.pop('name', tensors.name)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
669
670
671
672
            if dtype is None:
                dtype = tensors.dtype
        else:
            if dtype is None:
dboe's avatar
dboe committed
673
                if hasattr(tensors, "dtype"):
674
675
676
                    dtype = tensors.dtype
                else:
                    dtype = np.float64
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
677

dboe's avatar
dboe committed
678
        """ demand iterable structure """
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
679
680
        try:
            len(tensors)
dboe's avatar
dboe committed
681
        except TypeError:
dboe's avatar
dboe committed
682
683
684
685
            raise TypeError(
                "Iterable structure necessary."
                " Got {tensors}".format(**locals())
            )
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
686

dboe's avatar
dboe committed
687
        """ process empty inputs """
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
688
689
690
691
692
693
694
695
        if len(tensors) == 0:
            if issubclass(type(tensors), tfields.Tensors):
                tensors = np.empty(tensors.shape, dtype=tensors.dtype)
            elif dim is not None:
                tensors = np.empty((0, dim))
            if issubclass(type(tensors), np.ndarray):
                # np.empty
                pass
dboe's avatar
dboe committed
696
697
            elif hasattr(tensors, 'shape'):
                dim = dim(tensors)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
698
            else:
dboe's avatar
dboe committed
699
                raise ValueError(
dboe's avatar
dboe committed
700
                    "Empty tensors need dimension parameter 'dim'."
dboe's avatar
dboe committed
701
                )
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
702
703
704
705

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

dboe's avatar
dboe committed
706
        """ check dimension(s) """
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
707
708
        for d in obj.shape[1:]:
            if not d == obj.dim:
dboe's avatar
dboe committed
709
710
711
712
713
714
715
                raise ValueError(
                    "Dimensions are inconstistent. "
                    "Manifold dimension is {obj.dim}. "
                    "Found dimensions {found} in {obj}.".format(
                        found=obj.shape[1:], **locals()
                    )
                )
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
716
717
        if dim is not None:
            if dim != obj.dim:
dboe's avatar
dboe committed
718
719
720
721
                raise ValueError(
                    "Incorrect dimension: {obj.dim} given,"
                    " {dim} demanded.".format(**locals())
                )
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
722

dboe's avatar
dboe committed
723
        """ update kwargs with defaults from slots """
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
724
725
        cls._update_slot_kwargs(kwargs)

dboe's avatar
dboe committed
726
        """ set kwargs to slots attributes """
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
727
728
        for attr in kwargs:
            if attr not in cls._iter_slots():
dboe's avatar
dboe committed
729
730
731
732
                raise AttributeError(
                    "Keyword argument {attr} not accepted "
                    "for class {cls}".format(**locals())
                )
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
733
734
735
736
            setattr(obj, attr, kwargs[attr])

        return obj

737
738
739
740
    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
741

742
743
744
        Examples:
            >>> import tfields
            >>> vectors = tfields.Tensors([[0, 0, 0], [0, 0, 1], [0, -1, 0]])
dboe's avatar
dboe committed
745
746
            >>> scalar_field = tfields.TensorFields(
            ...     vectors, [42, 21, 10.5], [1, 2, 3])
747
748
749
750
751
752
753
            >>> [(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
754
755
756
757
    @classmethod
    def merged(cls, *objects, **kwargs):
        """
        Factory method
dboe's avatar
dboe committed
758
        Merges all input arguments to one object
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
759

760
761
762
        Args:
            return_templates (bool): return the templates which can be used
                together with cut to retrieve the original objects
dboe's avatar
dboe committed
763
764
            dim (int):
            **kwargs: passed to cls
765

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
766
767
768
769
770
        Examples:
            >>> import numpy as np
            >>> import tfields
            >>> import tfields.bases

771
772
            The new object with turn out in the most frequent coordinate
            system if not specified explicitly
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
773

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
774
            >>> vec_a = tfields.Tensors([[0, 0, 0], [0, 0, 1], [0, -1, 0]])
dboe's avatar
dboe committed
775
776
777
778
779
780
            >>> 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]])
781
            >>> assert merge.coord_sys == 'cylinder'
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
782
783
784
785
786
787
788
789
            >>> 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
790

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
791
792
            >>> tm_a = tfields.TensorMaps(merge, maps=[[[0, 1, 2]]])
            >>> tm_b = tm_a.copy()
793
            >>> assert tm_a.coord_sys == 'cylinder'
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
794
            >>> tm_merge = tfields.TensorMaps.merged(tm_a, tm_b)
795
            >>> assert tm_merge.coord_sys == 'cylinder'
dboe's avatar
dboe committed
796
            >>> assert tm_merge.maps[3].equal([[0, 1, 2],
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
797
798
799
            ...                               list(range(len(merge),
            ...                                          len(merge) + 3,
            ...                                          1))])
dboe's avatar
dboe committed
800

801
802
            >>> obj_list = [tfields.Tensors([[1, 2, 3]],
            ...             coord_sys=tfields.bases.CYLINDER),
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
803
804
            ...             tfields.Tensors([[3] * 3]),
            ...             tfields.Tensors([[5, 1, 3]])]
805
806
            >>> merge2 = tfields.Tensors.merged(
            ...     *obj_list, coord_sys=tfields.bases.CARTESIAN)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
807
808
            >>> assert merge2.equal([[-0.41614684, 0.90929743, 3.],
            ...                      [3, 3, 3], [5, 1, 3]], atol=1e-8)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
809

810
811
812
813
814
815
816
817
818
            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
819
820
        """

dboe's avatar
dboe committed
821
822
        """ get most frequent coord_sys or predefined coord_sys """
        coord_sys = kwargs.get("coord_sys", None)
823
        return_templates = kwargs.pop("return_templates", False)
824
        if coord_sys is None:
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
825
826
827
            bases = []
            for t in objects:
                try:
828
                    bases.append(t.coord_sys)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
829
830
831
                except AttributeError:
                    pass
            if bases:
832
                # get most frequent coord_sys
dboe's avatar
dboe committed
833
834
835
                coord_sys = sorted(
                    bases, key=Counter(bases).get, reverse=True
                )[0]
dboe's avatar
dboe committed
836
                kwargs["coord_sys"] = coord_sys
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
837
            else:
dboe's avatar
dboe committed
838
839
840
841
                default = cls.__slot_defaults__[
                    cls.__slots__.index("coord_sys")
                ]
                kwargs["coord_sys"] = default
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
842

dboe's avatar
dboe committed
843
        """ transform all raw inputs to cls type with correct coord_sys. Also
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
844
        automatically make a copy of those instances that are of the correct
dboe's avatar
dboe committed
845
        type already."""
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
846
        objects = [cls.__new__(cls, t, **kwargs) for t in objects]
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
847

dboe's avatar
dboe committed
848
        """ check rank and dimension equality """
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
849
850
851
852
853
        if not len(set([t.rank for t in objects])) == 1:
            raise TypeError("Tensors must have the same rank for merging.")
        if not len(set([t.dim for t in objects])) == 1:
            raise TypeError("Tensors must have the same dimension for merging.")

dboe's avatar
dboe committed
854
        """ merge all objects """
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
855
856
857
858
859
860
        remainingObjects = objects[1:] or []
        tensors = objects[0]

        for i, obj in enumerate(remainingObjects):
            tensors = np.append(tensors, obj, axis=0)

dboe's avatar
dboe committed
861
        if len(tensors) == 0 and not kwargs.get('dim', None):
862
863
            # if you can not determine the tensor dimension, search for the
            # first object with some entries
dboe's avatar
dboe committed
864
            kwargs['dim'] = dim(objects[0])
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
865

866
        inst = cls.__new__(cls, tensors, **kwargs)
867
        if not return_templates:
868
            return inst
869
870
871
872
873
874
        else:
            tensor_lengths = [len(o) for o in objects]
            cum_tensor_lengths = [sum(tensor_lengths[:i])
                                  for i in range(len(objects))]
            templates = [
                tfields.TensorFields(
875
                    np.empty((len(obj), 0)),
876
877
                    np.arange(tensor_lengths[i]) + cum_tensor_lengths[i])
                for i, obj in enumerate(objects)]
878
            return inst, templates
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
879
880
881
882
883

    @classmethod
    def grid(cls, *base_vectors, **kwargs):
        """
        Args:
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
884
885
886
887
888
889
890
            *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
891

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
892
893
894
895
896
897
                    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
898
899
900

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

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
902
903
904
905
906
907
908
909
910
911
912
            >>> 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
913
914
915

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

dboe's avatar
dboe committed
917
918
919
            >>> 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
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
            >>> 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
943
944
            When given the coord_sys argument, the grid is performed in the
            given coorinate system:
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
945

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
946
947
948
949
950
951
952
953
954
            >>> 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
955
        """
dboe's avatar
dboe committed
956
957
958
959
960
961
962
963
        cls_kwargs = {
            attr: kwargs.pop(attr)
            for attr in list(kwargs)
            if attr in cls.__slots__
        }
        inst = cls.__new__(
            cls, tfields.lib.grid.igrid(*base_vectors, **kwargs), **cls_kwargs
        )
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
        return inst

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

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

980
    def transform(self, coord_sys):
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
981
982
        """
        Args:
983
            coord_sys (str)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
984
985
986
987
988
989

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

            CARTESIAN to SPHERICAL
dboe's avatar
dboe committed
990
991
            >>> 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
992
993
994
            >>> t.transform('spherical')

            r
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
995

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
996
997
998
            >>> assert t[0, 0] == 3

            phi
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
999

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1000
1001
1002
1003
            >>> 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
1004

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1005
1006
1007
1008
1009
            >>> 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
1010

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1011
1012
1013
1014
1015
            >>> assert t[4, 0] == 0.
            >>> assert t[4, 2] == 0.


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

dboe's avatar
dboe committed
1017
1018
            >>> 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
1019
1020
            >>> t_cyl = tCart.copy()
            >>> t_cyl.transform('cylinder')
1021
            >>> assert t_cyl.coord_sys == 'cylinder'
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1022
1023

            R
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1024

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1025
1026
1027
1028
1029
1030
            >>> 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
1031

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1032
1033
1034
1035
1036
1037
            >>> 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
1038

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1039
1040
1041
1042
            >>> assert t_cyl[0, 2] == 42
            >>> assert t_cyl[2, 2] == -1

            >>> t_cyl.transform('cartesian')
1043
            >>> assert t_cyl.coord_sys == 'cartesian'
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1044
1045
1046
1047
            >>> assert t_cyl[0, 0] == 3

        """
        #           scalars                 empty             already there
1048
1049
        if self.rank == 0 or self.shape[0] == 0 or self.coord_sys == coord_sys:
            self.coord_sys = coord_sys
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1050
1051
            return

1052
1053
1054
        tfields.bases.transform(self, self.coord_sys, coord_sys)
        # self[:] = tfields.bases.transform(self, self.coord_sys, coord_sys)
        self.coord_sys = coord_sys
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1055
1056

    @contextmanager
1057
    def tmp_transform(self, coord_sys):
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1058
        """
1059
        Temporarily change the coord_sys to another coord_sys and change it back at exit
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1060
1061
        This method is for cleaner code only.
        No speed improvements go with this.
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1062

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1063
1064
        Args:
            see transform
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1065

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1066
1067
        Examples:
            >>> import tfields
1068
            >>> p = tfields.Tensors([[1,2,3]], coord_sys=tfields.bases.SPHERICAL)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1069
            >>> with p.tmp_transform(tfields.bases.CYLINDER):
1070
1071
            ...     assert p.coord_sys == tfields.bases.CYLINDER
            >>> assert p.coord_sys == tfields.bases.SPHERICAL
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1072
1073

        """
1074
1075
        baseBefore = self.coord_sys
        if baseBefore == coord_sys:
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1076
1077
            yield
        else:
1078
            self.transform(coord_sys)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1079
1080
1081
1082
1083
1084
1085
1086

            yield

            self.transform(baseBefore)

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

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1088
1089
        Args:
            coordinate (int): coordinate index
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1090

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1091
1092
1093
1094
1095
1096
        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
1097
1098
            multiple coordinates can be mirrored at the same time
            i.e. a point mirrorion would be
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1099

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1100
1101
1102
1103
1104
            >>> 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
1105
1106
            The mirroring will only be applied to the points meeting the
            condition.
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1107

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1108
1109
            >>> import sympy
            >>> x, y, z = sympy.symbols('x y z')
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1110
            >>> p.mirror([0, 2], y > 3)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
            >>> p.equal([[-1, 2, -3], [4, 5, 6], [-1, 2, 6]])
            True

        """
        if condition is None:
            condition = np.array([True for i in range(len(self))])
        elif isinstance(condition, sympy.Basic):
            condition = self.evalf(condition)
        if isinstance(coordinate, list) or isinstance(coordinate, tuple):
            for c in coordinate:
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1121
                self.mirror(c, condition=condition)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1122
1123
1124
1125
1126
        elif isinstance(coordinate, int):
            self[:, coordinate][condition] *= -1
        else:
            raise TypeError()

dboe's avatar
dboe committed
1127
1128
1129
1130
1131
1132
1133
1134
1135
    def to_segment(
        self,
        segment,
        num_segments,
        coordinate,
        periodicity=2 * np.pi,
        offset=0.0,
        coord_sys=None,
    ):
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1136
1137
1138
1139
1140
        """
        For circular (close into themself after
        <periodicity>) coordinates at index <coordinate> assume
        <num_segments> segments and transform all values to
        segment number <segment>
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1141

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1142
1143
1144
1145
1146
1147
        Args:
            segment (int): segment index (starting at 0)
            num_segments (int): number of segments
            coordinate (int): coordinate index
            periodicity (float): after what lenght, the coordiante repeats
            offset (float): offset in the mapping
1148
            coord_sys (str or sympy.CoordinateSystem): in which coord sys the
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1149
                transformation should be done
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1150

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1151
1152
1153
1154
1155
        Examples:
            >>> import tfields
            >>> import numpy as np
            >>> pStart = tfields.Points3D([[6, 2 * np.pi, 1],
            ...                            [6, 2 * np.pi / 5 * 3, 1]],
1156
            ...                           coord_sys='cylinder')
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
            >>> p = tfields.Points3D(pStart)
            >>> p.to_segment(0, 5, 1, offset=-2 * np.pi / 10)
            >>> assert np.array_equal(p[:, 1], [0, 0])

            >>> p2 = tfields.Points3D(pStart)
            >>> p2.to_segment(1, 5, 1, offset=-2 * np.pi / 10)
            >>> assert np.array_equal(np.round(p2[:, 1], 4), [1.2566] * 2)

        """
        if segment > num_segments - 1:
            raise ValueError("Segment {0} not existent.".format(segment))

1169
1170
1171
        if coord_sys is None:
            coord_sys = self.coord_sys
        with self.tmp_transform(coord_sys):
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1172
            # map all values to first segment
dboe's avatar
dboe committed
1173
1174
1175
1176
1177
            self[:, coordinate] = (
                (self[:, coordinate] - offset) % (periodicity / num_segments)
                + offset
                + segment * periodicity / num_segments
            )
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1178

dboe's avatar
dboe committed
1179
1180
1181
    def equal(
        self, other, rtol=None, atol=None, equal_nan=False, return_bool=True
    ):
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1182
1183
        """
        Evaluate, whether the instance has the same content as other.
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1184

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1185
1186
1187
1188
1189
1190
1191
        Args:
            optional:
                rtol (float)
                atol (float)
                equal_nan (bool)
            see numpy.isclose
        """
dboe's avatar
dboe committed
1192
1193
1194
1195
        if (
            issubclass(type(other), Tensors)
            and self.coord_sys != other.coord_sys
        ):
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1196
            other = other.copy()
1197
            other.transform(self.coord_sys)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1198
1199
        x, y = np.asarray(self), np.asarray(other)
        if rtol is None and atol is None:
dboe's avatar
dboe committed
1200
            mask = x == y
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1201
1202
1203
1204
1205
            if equal_nan:
                both_nan = np.isnan(x) & np.isnan(y)
                mask[both_nan] = both_nan[both_nan]
        else:
            if rtol is None:
dboe's avatar
dboe committed
1206
                rtol = 0.0
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1207
            if atol is None:
dboe's avatar
dboe committed
1208
                atol = 0.0
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1209
1210
1211
1212
1213
1214
1215
1216
1217
            mask = np.isclose(x, y, rtol=rtol, atol=atol, equal_nan=equal_nan)
        if return_bool:
            return bool(np.all(mask))
        return mask

    def contains(self, other, **kwargs):
        """
        Inspired by a speed argument @
        stackoverflow.com/questions/14766194/testing-whether-a-numpy-array-contains-a-given-row
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1218

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1219
1220
1221
1222
1223
1224
1225
1226
1227
        Examples:
            >>> import tfields
            >>> p = tfields.Tensors([[1,2,3], [4,5,6], [6,7,8]])
            >>> p.contains([4,5,6])
            True

        """
        return any(self.equal(other, return_bool=False).all(1))

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1228
    def indices(self, tensor, rtol=None, atol=None):
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1229
1230
1231
        """
        Returns:
            list of int: indices of tensor occuring
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1232

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1233
        Examples:
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1234
            Rank 1 Tensors
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1235

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1236
1237
1238
1239
1240
1241
1242
1243
            >>> import tfields
            >>> p = tfields.Tensors([[1,2,3], [4,5,6], [6,7,8], [4,5,6],
            ...                      [4.1, 5, 6]])
            >>> p.indices([4,5,6])
            array([1, 3])
            >>> p.indices([4,5,6.1], rtol=1e-5, atol=1e-1)
            array([1, 3, 4])

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1244
            Rank 0 Tensors
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1245

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1246
1247
1248
1249
1250
1251
            >>> p = tfields.Tensors([2, 3, 6, 3.01])
            >>> p.indices(3)
            array([1])
            >>> p.indices(3, rtol=1e-5, atol=1e-1)
            array([1, 3])

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1252
        """
1253
1254
        x, y = np.asarray(self), np.asarray(tensor)
        if rtol is None and atol is None:
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1255
            equal_method = np.equal
1256
        else: