core.py 74.9 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:
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
11
    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
12
13
14
15
16
17
18
19
20
21
22
"""
import warnings
import os
import pathlib
from six import string_types
from contextlib import contextmanager
from collections import Counter

import numpy as np
import sympy
import scipy as sp
23
import rna
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
24
import tfields.bases
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
25
from nltk.misc.chomsky import objects
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
np.seterr(all='warn', over='raise')


def rank(tensor):
    """
    Tensor rank
    """
    return len(tensor.shape) - 1


def dim(tensor):
    """
    Manifold dimension
    """
    if rank(tensor) == 0:
        return 1
    return tensor.shape[1]


class AbstractNdarray(np.ndarray):
    """
    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
50
51

    Attributes:
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
52
53
54
55
56
57
58
59
60
61
62
63
64
        __slots__ (list of str): If you want to add attributes to
            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.
        __slotDtype__ (list of types): for the conversion of the
            args in __slots__ to numpy arrays. None values mean no
            conversion.

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

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
66
67
    TODO:
        equality check
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
68

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
    """
    __slots__ = []
    __slot_defaults__ = []
    __slotDtypes__ = []
    __slot_setters__ = []

    def __new__(cls, array, **kwargs):  # pragma: no cover
        raise NotImplementedError("{clsType} type must implement '__new__'"
                                  .format(clsType=type(cls)))

    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):
        return [att for att in cls.__slots__ if att != '_cache']

    @classmethod
    def _update_slot_kwargs(cls, kwargs):
        """
        set the defaults in kwargs according to __slot_defaults__
        and convert the kwargs according to __slotDtypes__
        """
        slotDefaults = cls.__slot_defaults__ + \
            [None] * (len(cls.__slots__) - len(cls.__slot_defaults__))
        slotDtypes = cls.__slotDtypes__ + \
            [None] * (len(cls.__slots__) - len(cls.__slotDtypes__))
        for attr, default, dtype in zip(cls.__slots__, slotDefaults, slotDtypes):
            if attr == '_cache':
                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:
                    raise ValueError(str(attr) + str(dtype) + str(kwargs[attr]) + str(err))

    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
            if setter is not None:
                value = setter(value)
        super(AbstractNdarray, self).__setattr__(name, value)

    def __reduce__(self):
        """
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
126
127
        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
128
129
130
131
132
133
        Examples:
            >>> from tempfile import NamedTemporaryFile
            >>> import pickle
            >>> import tfields

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

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
135
136
137
            >>> from tfields import Tensors, TensorFields
            >>> scalars = Tensors([0, 1, 2])
            >>> vectors = Tensors([[0, 0, 0], [0, 0, 1], [0, -1, 0]])
138
            >>> scalar_field = TensorFields(vectors, scalars, coord_sys='cylinder')
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
139
140

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

142
            >>> out_file = NamedTemporaryFile(suffix='.pickle')
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
143

144
            >>> pickle.dump(scalar_field,
145
146
            ...             out_file)
            >>> _ = out_file.seek(0)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
147

148
            >>> sf = pickle.load(out_file)
149
            >>> sf.coord_sys == 'cylinder'
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
            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__
        new_state = pickled_state[2] + tuple([getattr(self, slot) for slot in
                                              self._iter_slots()])

        # Return a tuple that replaces the parent's __setstate__ tuple with our own
        return (pickled_state[0], pickled_state[1], new_state)

    def __setstate__(self, state):
        """
167
        Counterpart to __reduce__. Important for unpickling.
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
168
169
170
171
172
173
174
175
176
        """
        # Call the parent's __setstate__ with the other tuple elements.
        super(AbstractNdarray, self).__setstate__(state[0:-len(self._iter_slots())])

        # set the __slot__ attributes
        for i, slot in enumerate(reversed(self._iter_slots())):
            index = -(i + 1)
            setattr(self, slot, state[index])

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
177
178
179
180
181
182
183
184
    @property
    def bulk(self):
        """
        The pure ndarray version of the actual state
            -> nothing attached
        """
        return np.array(self)

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
185
186
187
    def copy(self, *args, **kwargs):
        """
        The standard ndarray copy does not copy slots. Correct for this.
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
188

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
189
190
191
192
193
194
195
196
197
198
199
        Examples:
            >>> import tfields
            >>> m = tfields.TensorMaps([[1,2,3], [3,3,3], [0,0,0], [5,6,7]],
            ...                        maps=[tfields.TensorFields([[0, 1, 2], [1, 2, 3]],
            ...                                                   [1, 2])])
            >>> mc = m.copy()
            >>> mc is m
            False
            >>> mc.maps[0].fields[0] is m.maps[0].fields[0]
            False

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
200
201
        TODO:
            This function implementation could be more general or maybe redirect to deepcopy?
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
202
203
204
205
        """
        inst = super(AbstractNdarray, self).copy(*args, **kwargs)
        for attr in self._iter_slots():
            value = getattr(self, attr)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
206
            if hasattr(value, 'copy') and not isinstance(value, list):
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
                setattr(inst, attr, value.copy(*args, **kwargs))
            elif isinstance(value, list):
                list_copy = []
                for item in value:
                    if hasattr(item, 'copy'):
                        list_copy.append(item.copy(*args, **kwargs))
                    else:
                        list_copy.append(item)
                setattr(inst, attr, list_copy)

        return inst

    def save(self, path, *args, **kwargs):
        """
        Saving a tensors object by redirecting to the correct save method depending on path
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
222

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
223
224
225
226
227
228
229
230
231
        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
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
232
        if isinstance(path, (string_types, pathlib.Path)):
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
233
            extension = pathlib.Path(path).suffix.lstrip('.')
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
234
235
236
        else:
            raise ValueError("Wrong path type {0}".format(type(path)))
        path = str(path)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
237
238
239
240
241
242
243
244
245

        # get the save method
        try:
            save_method = getattr(self,
                                  '_save_{extension}'.format(**locals()))
        except:
            raise NotImplementedError("Can not find save method for extension: "
                                      "{extension}.".format(**locals()))

246
        path = rna.path.resolve(path)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
247
248
249
250
251
252
        return save_method(path, **kwargs)

    @classmethod
    def load(cls, path, *args, **kwargs):
        """
        load a file as a tensors object.
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
253

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
254
255
256
257
258
259
260
261
        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
        """
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
262
        if isinstance(path, (string_types, pathlib.Path)):
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
263
            extension = pathlib.Path(path).suffix.lstrip('.')
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
264
            path = str(path)
265
            path = rna.path.resolve(path)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
266
267
        else:
            extension = kwargs.pop('extension', 'npz')
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
268
269
270
271
272
273
274
275
276
277
278
279

        try:
            load_method = getattr(cls, '_load_{e}'.format(e=extension))
        except:
            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.
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
280

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
281
        Examples:
282
            Build some dummies:
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
283
284
            >>> import tfields
            >>> from tempfile import NamedTemporaryFile
285
            >>> out_file = NamedTemporaryFile(suffix='.npz')
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
286
            >>> p = tfields.Points3D([[1., 2., 3.], [4., 5., 6.], [1, 2, -6]])
287
288
289
290
291
292
293
294
295
296
297
298

            >>> scalars = tfields.Tensors([0, 1, 2])
            >>> 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)
            >>> p1 = tfields.Points3D.load(out_file.name)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
299
300
            >>> assert p.equal(p1)

301
302
303
304
305
306
            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)
            >>> assert m.equal(m1)
307
            >>> assert m.maps[0].dtype == m1.maps[0].dtype
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
308

309
        """
310
311
        content_dict = self._as_dict()
        np.savez(path, **content_dict)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
312
313
314
315
316
317
318
319

    @classmethod
    def _load_npz(cls, path, **load_kwargs):
        """
        Factory method
        Given a path to a npz file, construct the object
        """
        np_file = np.load(path, **load_kwargs)
320
321
322
323
324
325
326
        return cls._from_dict(**np_file)

    def _as_dict(self):
        """
        Recursively walk trough all __slots__ and describe all elements
        """
        d = {}
327
        d['bulk'] = self.bulk
328
329
330
331
332
333
334
335
336
337
338
        d['bulk_type'] = self.__class__.__name__
        for attr in self._iter_slots():
            value = getattr(self, attr)
            if isinstance(value, list):
                if len(value) == 0:
                    d[attr] = None
                if all([isinstance(part, AbstractNdarray) for part in value]):
                    for i, part in enumerate(value):
                        part_dict = part._as_dict()
                        for part_attr, part_value in part_dict.items():
                            d["{attr}::{i}::{part_attr}".format(**locals())] = part_value
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
339
                    continue
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
            if isinstance(value, AbstractNdarray):
                value = value._as_dict()
            d[attr] = value
        return d

    @classmethod
    def _from_dict(cls, **d):
        """
        Opposite of _as_dict
        """
        list_dict = {}
        kwargs = {}
        '''
        De-Flatten the first layer of lists
        '''
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
355
        for key in sorted(list(d)):
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
            if '::' in key:
                splits = key.split('::')
                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)
        '''
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
375
        for key in list(list_dict):
376
377
            sub_dict = list_dict[key]
            list_dict[key] = []
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
378
            for index in sorted(list(sub_dict)):
Priyanjana Sinha's avatar
Priyanjana Sinha committed
379
380
381
382
383
                bulk_type = sub_dict[index].get('bulk_type').tolist()
                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)
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
                list_dict[key].append(bulk_type._from_dict(**sub_dict[index]))

        '''
        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
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
399
400
401
402
403


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

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
405
406
    TODO:
        all slot args should be protected -> _base
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
407

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
408
409
    Args:
        tensors: np.ndarray or AbstractNdarray subclass
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
410

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
411
412
    Examples:
        >>> import numpy as np
413
        >>> import tfields
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
414
415

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

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
417
418
419
420
421
        >>> scalars = tfields.Tensors([0, 1, 2])
        >>> scalars.rank == 0
        True

        Initialize vectors
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
422

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
423
424
425
426
427
        >>> vectors = tfields.Tensors([[0, 0, 0], [0, 0, 1], [0, -1, 0]])
        >>> vectors.rank == 1
        True
        >>> vectors.dim == 3
        True
428
        >>> assert vectors.coord_sys == 'cartesian'
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
429
430

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

432
433
434
435
        >>> 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
436
437
438
439
440
441
442
443
        >>> 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
444

445
446
        >>> cyl = tfields.Tensors([[5, np.arctan(4. / 3.), 42]], coord_sys='cylinder')
        >>> assert cyl.coord_sys == 'cylinder'
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
447
        >>> cyl.transform('cartesian')
448
        >>> assert cyl.coord_sys == 'cartesian'
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
449
450
451
452
453
454
        >>> 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
455

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
456
457
        >>> with vectors.tmp_transform('cylinder'):
        ...     vect_cyl = tfields.Tensors(vectors)
458
459
        ...     assert vect_cyl.coord_sys == vectors.coord_sys
        >>> assert vect_cyl.coord_sys == 'cylinder'
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
460
461

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

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
463
464
465
466
467
468
469
470
        >>> _ = 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
471

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
472
473
474
475
476
477
478
479
        >>> _ = 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)

    """
480
    __slots__ = ['coord_sys']
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
481
482
483
484
485
486
487
488
489
490
491
492
    __slot_defaults__ = ['cartesian']
    __slot_setters__ = [tfields.bases.get_coord_system_name]

    def __new__(cls, tensors, **kwargs):
        dtype = kwargs.pop('dtype', None)
        order = kwargs.pop('order', None)
        dim = kwargs.pop('dim', None)

        ''' copy constructor extracts the kwargs from tensors'''
        if issubclass(type(tensors), Tensors):
            if dim is not None:
                dim = tensors.dim
493
            coord_sys = kwargs.pop('coord_sys', tensors.coord_sys)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
494
            tensors = tensors.copy()
495
496
            tensors.transform(coord_sys)
            kwargs['coord_sys'] = coord_sys
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
497
498
499
500
            if dtype is None:
                dtype = tensors.dtype
        else:
            if dtype is None:
501
502
503
504
                if hasattr(tensors, 'dtype'):
                    dtype = tensors.dtype
                else:
                    dtype = np.float64
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533

        ''' demand iterable structure '''
        try:
            len(tensors)
        except TypeError as err:
            raise TypeError("Iterable structure necessary."
                            " Got {tensors}"
                            .format(**locals()))

        ''' process empty inputs '''
        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
            else:
                raise ValueError("Empty tensors need dimension "
                                 "parameter 'dim'.")

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

        ''' check dimension(s) '''
        for d in obj.shape[1:]:
            if not d == obj.dim:
                raise ValueError("Dimensions are inconstistent. "
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
534
                                 "Manifold dimension is {obj.dim}. "
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
                                 "Found dimensions {found} in {obj}."
                                 .format(found=obj.shape[1:], **locals()))
        if dim is not None:
            if dim != obj.dim:
                raise ValueError("Incorrect dimension: {obj.dim} given,"
                                 " {dim} demanded."
                                 .format(**locals()))

        ''' update kwargs with defaults from slots '''
        cls._update_slot_kwargs(kwargs)

        ''' set kwargs to slots attributes '''
        for attr in kwargs:
            if attr not in cls._iter_slots():
                raise AttributeError("Keyword argument {attr} not accepted "
                                     "for class {cls}".format(**locals()))
            setattr(obj, attr, kwargs[attr])

        return obj

555
556
557
558
    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
559

560
561
562
563
564
565
566
567
568
569
570
        Examples:
            >>> import tfields
            >>> vectors = tfields.Tensors([[0, 0, 0], [0, 0, 1], [0, -1, 0]])
            >>> scalar_field = tfields.TensorFields(vectors, [42, 21, 10.5], [1, 2, 3])
            >>> [(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
571
572
573
574
575
576
577
578
579
580
581
582
    @classmethod
    def merged(cls, *objects, **kwargs):
        """
        Factory method
        Merges all tensor inputs to one tensor

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

            Use of most frequent coordinate system
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
583

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
584
            >>> vec_a = tfields.Tensors([[0, 0, 0], [0, 0, 1], [0, -1, 0]])
585
586
            >>> vec_b = tfields.Tensors([[5, 4, 1]], coord_sys=tfields.bases.cylinder)
            >>> vec_c = tfields.Tensors([[4, 2, 3]], coord_sys=tfields.bases.cylinder)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
587
            >>> merge = tfields.Tensors.merged(vec_a, vec_b, vec_c, [[2, 0, 1]])
588
            >>> assert merge.coord_sys == 'cylinder'
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
589
590
591
592
593
594
595
596
            >>> 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
597

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
598
599
            >>> tm_a = tfields.TensorMaps(merge, maps=[[[0, 1, 2]]])
            >>> tm_b = tm_a.copy()
600
            >>> assert tm_a.coord_sys == 'cylinder'
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
601
            >>> tm_merge = tfields.TensorMaps.merged(tm_a, tm_b)
602
            >>> assert tm_merge.coord_sys == 'cylinder'
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
603
604
605
606
607
            >>> assert tm_merge.maps[0].equal([[0, 1, 2],
            ...                               list(range(len(merge),
            ...                                          len(merge) + 3,
            ...                                          1))])
            
608
            >>> obj_list = [tfields.Tensors([[1, 2, 3]], coord_sys=tfields.bases.CYLINDER),
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
609
610
            ...             tfields.Tensors([[3] * 3]),
            ...             tfields.Tensors([[5, 1, 3]])]
611
            >>> merge2 = tfields.Tensors.merged(*obj_list, coord_sys=tfields.bases.CARTESIAN)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
612
613
            >>> assert merge2.equal([[-0.41614684, 0.90929743, 3.],
            ...                      [3, 3, 3], [5, 1, 3]], atol=1e-8)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
614

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
615
616
        """

617
618
        ''' get most frequent coord_sys or predefined coord_sys '''
        coord_sys = kwargs.get('coord_sys', None)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
619
        dimension = kwargs.get('dim', None)
620
        if coord_sys is None:
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
621
622
623
            bases = []
            for t in objects:
                try:
624
                    bases.append(t.coord_sys)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
625
626
627
                except AttributeError:
                    pass
            if bases:
628
629
630
                # get most frequent coord_sys
                coord_sys = sorted(bases, key=Counter(bases).get, reverse=True)[0]
                kwargs['coord_sys'] = coord_sys
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
631
            else:
632
633
                default = cls.__slot_defaults__[cls.__slots__.index('coord_sys')]
                kwargs['coord_sys'] = default
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
634

635
        ''' transform all raw inputs to cls type with correct coord_sys. Also
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
636
637
        automatically make a copy of those instances that are of the correct
        type already.'''
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
638
        objects = [cls.__new__(cls, t, **kwargs) for t in objects]
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662

        ''' check rank and dimension equality '''
        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.")

        ''' merge all objects '''
        remainingObjects = objects[1:] or []
        tensors = objects[0]

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

        if len(tensors) == 0 and dimension is None:
            for obj in objects:
                kwargs['dim'] = dim(obj)

        return cls.__new__(cls, tensors, **kwargs)

    @classmethod
    def grid(cls, *base_vectors, **kwargs):
        """
        Args:
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
663
664
665
666
667
668
669
670
671
672
673
674
675
676
            *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::
                          
                    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
677
678
679

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

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
681
682
683
684
685
686
687
688
689
690
691
            >>> 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
692
693
694

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

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
            >>> lins = tfields.Tensors.grid(np.linspace(3, 4, 2), np.linspace(0, 1, 2),
            ...                             np.linspace(6, 7, 2), iter_order=[1, 0, 2])
            >>> 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
721
722
            When given the coord_sys argument, the grid is performed in the
            given coorinate system:
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
723

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
724
725
726
727
728
729
730
731
732
            >>> 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
733
        """
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
734
        cls_kwargs = {attr: kwargs.pop(attr) for attr in list(kwargs) if attr in cls.__slots__}
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
735
736
737
        inst = cls.__new__(cls,
                           tfields.lib.grid.igrid(*base_vectors, **kwargs),
                           **cls_kwargs)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
        return inst

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

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

754
    def transform(self, coord_sys):
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
755
756
        """
        Args:
757
            coord_sys (str)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
758
759
760
761
762
763
764
765
766
767

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

            CARTESIAN to SPHERICAL
            >>> t = tfields.Tensors([[1, 2, 2], [1, 0, 0], [0, 0, -1], [0, 0, 1], [0, 0, 0]])
            >>> t.transform('spherical')

            r
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
768

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
769
770
771
            >>> assert t[0, 0] == 3

            phi
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
772

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
773
774
775
776
            >>> 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
777

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
778
779
780
781
782
            >>> 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
783

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
784
785
786
787
788
            >>> assert t[4, 0] == 0.
            >>> assert t[4, 2] == 0.


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

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
790
791
792
            >>> tCart = tfields.Tensors([[3, 4, 42], [1, 0, 0], [0, 1, -1], [-1, 0, 1], [0, 0, 0]])
            >>> t_cyl = tCart.copy()
            >>> t_cyl.transform('cylinder')
793
            >>> assert t_cyl.coord_sys == 'cylinder'
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
794
795

            R
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
796

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
797
798
799
800
801
802
            >>> 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
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
803
            
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
804
805
806
807
808
809
            >>> 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
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
810
            
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
811
812
813
814
            >>> assert t_cyl[0, 2] == 42
            >>> assert t_cyl[2, 2] == -1

            >>> t_cyl.transform('cartesian')
815
            >>> assert t_cyl.coord_sys == 'cartesian'
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
816
817
818
819
            >>> assert t_cyl[0, 0] == 3

        """
        #           scalars                 empty             already there
820
821
        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
822
823
            return

824
825
826
        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
827
828

    @contextmanager
829
    def tmp_transform(self, coord_sys):
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
830
        """
831
        Temporarily change the coord_sys to another coord_sys and change it back at exit
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
832
833
        This method is for cleaner code only.
        No speed improvements go with this.
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
834

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
835
836
        Args:
            see transform
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
837

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
838
839
        Examples:
            >>> import tfields
840
            >>> p = tfields.Tensors([[1,2,3]], coord_sys=tfields.bases.SPHERICAL)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
841
            >>> with p.tmp_transform(tfields.bases.CYLINDER):
842
843
            ...     assert p.coord_sys == tfields.bases.CYLINDER
            >>> assert p.coord_sys == tfields.bases.SPHERICAL
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
844
845

        """
846
847
        baseBefore = self.coord_sys
        if baseBefore == coord_sys:
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
848
849
            yield
        else:
850
            self.transform(coord_sys)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
851
852
853
854
855
856
857
858

            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
859

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
860
861
        Args:
            coordinate (int): coordinate index
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
862

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
863
864
865
866
867
868
        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
869
870
            multiple coordinates can be mirrored at the same time
            i.e. a point mirrorion would be
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
871

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
872
873
874
875
876
877
            >>> 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.
            The mirroring will only be applied to the points meeting the condition.
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
878

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
879
880
            >>> import sympy
            >>> x, y, z = sympy.symbols('x y z')
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
881
            >>> p.mirror([0, 2], y > 3)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
882
883
884
885
886
887
888
889
890
891
            >>> 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
892
                self.mirror(c, condition=condition)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
893
894
895
896
897
898
        elif isinstance(coordinate, int):
            self[:, coordinate][condition] *= -1
        else:
            raise TypeError()

    def to_segment(self, segment, num_segments, coordinate,
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
899
                   periodicity=2 * np.pi, offset=0.,
900
                   coord_sys=None):
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
901
902
903
904
905
        """
        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
906

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
907
908
909
910
911
912
        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
913
            coord_sys (str or sympy.CoordinateSystem): in which coord sys the
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
914
                transformation should be done
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
915

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
916
917
918
919
920
        Examples:
            >>> import tfields
            >>> import numpy as np
            >>> pStart = tfields.Points3D([[6, 2 * np.pi, 1],
            ...                            [6, 2 * np.pi / 5 * 3, 1]],
921
            ...                           coord_sys='cylinder')
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
922
923
924
925
926
927
928
929
930
931
932
933
            >>> 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))

934
935
936
        if coord_sys is None:
            coord_sys = self.coord_sys
        with self.tmp_transform(coord_sys):
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
937
938
939
940
941
942
943
944
945
946
            # map all values to first segment
            self[:, coordinate] = \
                (self[:, coordinate] - offset) % (periodicity / num_segments) + \
                offset + segment * periodicity / num_segments

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

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
948
949
950
951
952
953
954
        Args:
            optional:
                rtol (float)
                atol (float)
                equal_nan (bool)
            see numpy.isclose
        """
955
        if issubclass(type(other), Tensors) and self.coord_sys != other.coord_sys:
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
956
            other = other.copy()
957
            other.transform(self.coord_sys)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
        x, y = np.asarray(self), np.asarray(other)
        if rtol is None and atol is None:
            mask = (x == y)
            if equal_nan:
                both_nan = np.isnan(x) & np.isnan(y)
                mask[both_nan] = both_nan[both_nan]
        else:
            if rtol is None:
                rtol = 0.
            if atol is None:
                atol = 0.
            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
978

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
979
980
981
982
983
984
985
986
987
        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
988
    def indices(self, tensor, rtol=None, atol=None):
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
989
990
991
        """
        Returns:
            list of int: indices of tensor occuring
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
992

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
993
        Examples:
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
994
            Rank 1 Tensors
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
995

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
996
997
998
999
1000
1001
1002
1003
            >>> 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
1004
            Rank 0 Tensors
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1005

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1006
1007
1008
1009
1010
1011
            >>> 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
1012
        """
1013
1014
        x, y = np.asarray(self), np.asarray(tensor)
        if rtol is None and atol is None:
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1015
            equal_method = np.equal
1016
1017
        else:
            equal_method = lambda a, b: np.isclose(a, b, rtol=rtol, atol=atol)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1018
1019

        # inspired by https://stackoverflow.com/questions/19228295/find-ordered-vector-in-numpy-array
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1020
1021
1022
1023
1024
1025
        if self.rank == 0:
            indices = np.where(equal_method((x-y), 0))[0]
        elif self.rank == 1:
            indices = np.where(np.all(equal_method((x-y), 0), axis=1))[0]
        else:
            raise NotImplementedError()
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1026
1027
        return indices

1028
    def index(self, tensor, **kwargs):
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1029
1030
1031
        """
        Args:
            tensor
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1032

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1033
1034
1035
        Returns:
            int: index of tensor occuring
        """
1036
        indices = self.indices(tensor, **kwargs)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1037
1038
1039
1040
1041
1042
1043
        if not indices:
            return None
        if len(indices) == 1:
            return indices[0]
        raise ValueError("Multiple occurences of value {}"
                         .format(tensor))

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1044
    def moment(self, moment, weights=None):
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1045
1046
1047
        """
        Returns:
            Moments of the distribution.
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1048

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1049
1050
        Args:
            moment (int): n-th moment
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1051

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1052
1053
        Examples:
            >>> import tfields
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1054
            >>> import numpy as np
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1055
1056

            Skalars
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1057

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1058
            >>> t = tfields.Tensors(range(1, 6))
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1059
            >>> assert t.moment(1) == 0
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1060
1061
1062
1063
            >>> assert t.moment(1, weights=[-2, -1, 20, 1, 2]) == 0.5
            >>> assert t.moment(2, weights=[0.25, 1, 17.5, 1, 0.25]) == 0.2

            Vectors
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1064

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1065
            >>> t = tfields.Tensors(list(zip(range(1, 6), range(1, 6))))
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1066
1067
1068
1069
            >>> assert Tensors([0.5, 0.5]).equal(t.moment(1, weights=[-2, -1, 20, 1, 2]))
            >>> assert Tensors([1. , 0.5]).equal(
            ...     t.moment(1, weights=list(zip([-2, -1, 10, 1, 2],
            ...                                  [-2, -1, 20, 1, 2]))))
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1070

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1071
        """
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1072
1073
1074
1075
        array = tfields.lib.stats.moment(self, moment, weights=weights)
        if self.rank == 0:  # scalar
            array = [array]
        return Tensors(array, coord_sys=self.coord_sys)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1076
1077
1078
1079
1080
1081

    def closest(self, other, **kwargs):
        """
        Args:
            other (Tensors): closest points to what? -> other
            **kwargs: forwarded to scipy.spatial.cKDTree.query
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1082

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1083
1084
        Returns:
            array shape(len(self)): Indices of other points that are closest to own points
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1085

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1086
1087
1088
1089
1090
1091
1092
1093
1094
        Examples:
            >>> import tfields
            >>> m = tfields.Tensors([[1,0,0], [0,1,0], [1,1,0], [0,0,1],
            ...                      [1,0,1]])
            >>> p = tfields.Tensors([[1.1,1,0], [0,0.1,1], [1,0,1.1]])
            >>> p.closest(m)
            array([2, 3, 4])

        """
1095
        with other.tmp_transform(self.coord_sys):
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1096
1097
1098
1099
1100
1101
1102
1103
            # balanced_tree option gives huge speedup!
            kd_tree = sp.spatial.cKDTree(other, 1000,
                                         balanced_tree=False)
            res = kd_tree.query(self, **kwargs)
            array = res[1]

        return array

1104
    def evalf(self, expression=None, coord_sys=None):
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1105
1106
1107
        """
        Args:
            expression (sympy logical expression)
1108
            coord_sys (str): coord_sys to evalfuate the expression in.
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1109

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1110
1111
1112
        Returns:
            np.ndarray: mask of dtype bool with lenght of number of points in self.
                 This array is True, where expression evalfuates True.
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1113

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
        Examples:
            >>> import tfields
            >>> import numpy
            >>> import sympy
            >>> x, y, z = sympy.symbols('x y z')
            >>> p = tfields.Tensors([[1., 2., 3.], [4., 5., 6.], [1, 2, -6],
            ...                      [-5, -5, -5], [1,0,-1], [0,1,-1]])
            >>> np.array_equal(p.evalf(x > 0),
            ...                [True, True, True, False, True, False])
            True
            >>> np.array_equal(p.evalf(x >= 0),
            ...                [True, True, True, False, True, True])
            True

            And combination
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1129

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1130
1131
1132
1133
1134
            >>> np.array_equal(p.evalf((x > 0) & (y < 3)),
            ...                [True, False, True, False, True, False])
            True

            Or combination
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1135

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1136
1137
1138
1139
1140
1141
            >>> np.array_equal(p.evalf((x > 0) | (y > 3)),
            ...                [True, True, True, False, True, False])
            True

        """
        coords = sympy.symbols('x y z')
1142
        with self.tmp_transform(coord_sys or self.coord_sys):
1143
            mask = tfields.evalf(np.array(self), expression, coords=coords)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1144
1145
        return mask

1146
    def cut(self, expression, coord_sys=None):
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1147
1148
        """
        Default cut method for Points3D. Works on a copy.
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1149

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1150
1151
1152
        Args:
            expression (sympy logical expression): logical expression which will be evalfuated.
                             use symbols x, y and z
1153
            coord_sys (str): coord_sys to evalfuate the expression in.
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1154

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
        Examples:
            >>> import tfields
            >>> import sympy
            >>> x, y, z = sympy.symbols('x y z')
            >>> p = tfields.Tensors([[1., 2., 3.], [4., 5., 6.], [1, 2, -6],
            ...                      [-5, -5, -5], [1,0,-1], [0,1,-1]])
            >>> p.cut(x > 0).equal([[1, 2, 3],
            ...                     [4, 5, 6],
            ...                     [1, 2, -6],
            ...                     [1, 0, -1]])
            True

            combinations of cuts
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1168

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1169
1170
1171
1172
1173
1174
1175
1176
1177
            >>> p.cut((x > 0) & (z < 0)).equal([[1, 2, -6], [1, 0, -1]])
            True

        Returns:
            copy of self with cut applied

        """
        if len(self) == 0:
            return self.copy()
1178
        mask = self.evalf(expression, coord_sys=coord_sys or self.coord_sys)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1179
1180
1181
1182
1183
1184
1185
        mask.astype(bool)
        inst = self[mask].copy()
        return inst

    def distances(self, other, **kwargs):
        """
        Args:
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1186
            other(Iterable)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1187
1188
            **kwargs:
                ... is forwarded to sp.spatial.distance.cdist
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1189

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
        Examples:
            >>> import tfields
            >>> p = tfields.Tensors.grid((0, 2, 3j),
            ...                          (0, 2, 3j),
            ...                          (0, 0, 1j))
            >>> p[4,2] = 1
            >>> p.distances(p)[0,0]
            0.0
            >>> p.distances(p)[5,1]
            1.4142135623730951
            >>> p.distances([[0,1,2]])[-1][0] == 3
            True

        """
1204
        if issubclass(type(other), Tensors) and self.coord_sys != other.coord_sys:
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1205
            other = other.copy()
1206
            other.transform(self.coord_sys)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
        return sp.spatial.distance.cdist(self, other, **kwargs)

    def min_dists(self, other=None, **kwargs):
        """
        Args:
            other(array | None): if None: closest distance to self
            **kwargs:
                memory_saving (bool): for very large array comparisons
                    default False
                ... rest is forwarded to sp.spatial.distance.cdist

        Returns:
            np.array: minimal distances of self to other

        Examples:
            >>> import tfields
            >>> import numpy as np
            >>> p = tfields.Tensors.grid((0, 2, 3),
            ...                          (0, 2, 3),
            ...                          (0, 0, 1))
            >>> p[4,2] = 1
            >>> dMin = p.min_dists()
            >>> expected = [1] * 9
            >>> expected[4] = np.sqrt(2)
            >>> np.array_equal(dMin, expected)
            True

            >>> dMin2 = p.min_dists(memory_saving=True)
            >>> bool((dMin2 == dMin).all())
            True

        """
        memory_saving = kwargs.pop('memory_saving', False)

        if other is None:
            other = self
        else:
            raise NotImplementedError("Should be easy but make shure not to remove diagonal")

        try:
            if memory_saving:
                raise MemoryError()
            d = self.distances(other, **kwargs)
            return d[d > 0].reshape(d.shape[0], - 1).min(axis=1)
        except MemoryError:
            min_dists = np.empty(self.shape[0])
1253
            for i, point in enumerate(np.array(other)):
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1254
1255
1256
1257
1258
1259
1260
1261
                d = self.distances([point], **kwargs)
                min_dists[i] = d[d > 0].reshape(-1).min()
            return min_dists

    def epsilon_neighbourhood(self, epsilon):
        """
        Returns:
            indices for those sets of points that lie within epsilon around the other
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1262

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
        Examples:
            Create mesh grid with one extra point that will have 8 neighbours
            within epsilon
            >>> import tfields
            >>> p = tfields.Tensors.grid((0, 1, 2j),
            ...                          (0, 1, 2j),
            ...                          (0, 1, 2j))
            >>> p = tfields.Tensors.merged(p, [[0.5, 0.5, 0.5]])
            >>> [len(en) for en in p.epsilon_neighbourhood(0.9)]
            [2, 2, 2, 2, 2, 2, 2, 2, 9]

        """
        indices = np.arange(self.shape[0])
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1276
        dists = self.distances(self)  # this takes long
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1277
        distsInEpsilon = dists <= epsilon
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1278
1279
        indices = [indices[die] for die in distsInEpsilon]  # this takes long
        return indices
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1280
1281
1282
1283

    def _weights(self, weights, rigid=True):
        """
        transformer method for weights inputs.
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1284

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1285
1286
1287
1288
1289
        Args:
            weights (np.ndarray | None):
                If weights is None, use np.ones
                Otherwise just pass the weights.
            rigid (bool): demand equal weights and tensor length
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1290

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
        Returns:
            weight array
        """
        # set weights to 1.0 if weights is None
        if weights is None:
            weights = np.ones(len(self))
        if rigid:
            if not len(weights) == len(self):
                raise ValueError("Equal number of weights as tensors demanded.")
        return weights

    def cov_eig(self, weights=None):
        """
        Calculate the covariance eigenvectors with lenghts of eigenvalues
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1305

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
        Args:
            weights (np.array | int | None): index to scalars to weight with
        """
        # weights = self.getNormedWeightedAreas(weights=weights)
        weights = self._weights(weights)
        cov = np.cov(self.T,
                     ddof=0,
                     aweights=weights)
        # calculate eigenvalues and eigenvectors of covariance
        evalfs, evecs = np.linalg.eigh(cov)
        idx = evalfs.argsort()[::-1]
        evalfs = evalfs[idx]
        evecs = evecs[:, idx]
        e = np.concatenate((evecs, evalfs.reshape(1, 3)))
        return e.T.reshape(12, )

    def main_axes(self, weights=None):
        """
        Returns:
            Main Axes eigen-vectors
        """
        # weights = self.getNormedWeightedAreas(weights=weights)
        weights = self._weights(weights)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1329
        mean = np.array(self).mean(axis=0)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1330
1331
1332
1333
1334
1335
1336
1337
        relative_coords = self - mean
        cov = np.cov(relative_coords.T,
                     ddof=0,
                     aweights=weights)
        # calculate eigenvalues and eigenvectors of covariance
        evalfs, evecs = np.linalg.eigh(cov)
        return (evecs * evalfs.T).T

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1338
1339
    def plot(self, **kwargs):
        """
1340
        Forwarding to rna.plotting.plot_array
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1341
        """
1342
        artist = rna.plotting.plot_array(self, **kwargs)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1343
1344
        return artist

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361

class TensorFields(Tensors):
    """
    Discrete Tensor Field

    Args:
        tensors (array): base tensors
        *fields (array): multiple fields assigned to one base tensor. Fields
            themself are also of type tensor
        **kwargs:
            rigid (bool): demand equal field and tensor lenght
            ... : see tfields.Tensors

    Examples:
        >>> from tfields import Tensors, TensorFields
        >>> scalars = Tensors([0, 1, 2])
        >>> vectors = Tensors([[0, 0, 0], [0, 0, 1], [0, -1, 0]])
1362
1363
        >>> scalar_field = TensorFields(vectors, scalars)
        >>> scalar_field.rank
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1364
        1
1365
        >>> scalar_field.fields[0].rank
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
        0
        >>> vectorField = TensorFields(vectors, vectors)
        >>> vectorField.fields[0].rank
        1
        >>> vectorField.fields[0].dim
        3
        >>> multiField = TensorFields(vectors, scalars, vectors)
        >>> multiField.fields[0].dim
        1
        >>> multiField.fields[1].dim
        3

        Empty initialization
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1379

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1380
1381
1382
1383
1384
        >>> empty_field = TensorFields([], dim=3)
        >>> assert empty_field.shape == (0, 3)
        >>> assert empty_field.fields == []

        Directly initializing with lists or arrays
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1385

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1386
1387
1388
1389
1390
        >>> vec_field_raw = tfields.TensorFields([[0, 1, 2], [3, 4, 5]],
        ...                                       [1, 6], [2, 7])
        >>> assert len(vec_field_raw.fields) == 2

        Copying
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1391

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1392
1393
1394
        >>> cp = TensorFields(vectorField)
        >>> assert vectorField.equal(cp)

1395
        Copying takes care of coord_sys
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1396

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1397
1398
        >>> cp.transform(tfields.bases.CYLINDER)
        >>> cp_cyl = TensorFields(cp)
1399
        >>> assert cp_cyl.coord_sys == tfields.bases.CYLINDER
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1400
1401

        Copying with changing type
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1402

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1403
1404
1405
1406
1407
1408
        >>> tcp = TensorFields(vectorField, dtype=int)
        >>> assert vectorField.equal(tcp)
        >>> assert tcp.dtype == int

    Raises:
        TypeError:
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1409

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1410
1411
1412
1413
1414
1415
1416
        >>> import tfields
        >>> tfields.TensorFields([1, 2, 3], [3])  # doctest: +ELLIPSIS
        Traceback (most recent call last):
        ...
        ValueError: Length of base (3) should be the same as the length of all fields ([1]).

        This error can be suppressed by setting rigid=False
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1417

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1418
1419
1420
1421
        >>> loose = tfields.TensorFields([1, 2, 3], [3], rigid=False)
        >>> assert len(loose) != 1

    """
1422
    __slots__ = ['coord_sys', 'fields']
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453

    def __new__(cls, tensors, *fields, **kwargs):
        rigid = kwargs.pop('rigid', True)

        obj = super(TensorFields, cls).__new__(cls, tensors, **kwargs)
        if issubclass(type(tensors), TensorFields):
            if tensors.fields is None:
                raise ValueError("Tensor fields were None")
            obj.fields = [Tensors(field) for field in tensors.fields]
        elif not fields:
            obj.fields = []
        if fields:
            # (over)write fields
            obj.fields = [Tensors(field) for field in fields]

        if rigid:
            olen = len(obj)
            field_lengths = [len(f) for f in obj.fields]
            if not all([flen == olen for flen in field_lengths]):
                raise ValueError("Length of base ({olen}) should be the same as"
                                 " the length of all fields ({field_lengths})."
                                 .format(**locals()))
        return obj

    def __getitem__(self, index):
        """
        In addition to the usual, also slice fields
        Examples:
            >>> import tfields
            >>> import numpy as np
            >>> vectors = tfields.Tensors([[0, 0, 0], [0, 0, 1], [0, -1, 0]])
1454
            >>> scalar_field = tfields.TensorFields(vectors, [42, 21, 10.5], [1, 2, 3])
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1455
1456

            Slicing
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1457

1458
            >>> sliced = scalar_field[2:]
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1459
1460
1461
1462
1463
            >>> assert isinstance(sliced, tfields.TensorFields)
            >>> assert isinstance(sliced.fields[0], tfields.Tensors)
            >>> assert sliced.fields[0].equal([10.5])

            Picking
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1464

1465
            >>> picked = scalar_field[1]
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1466
1467
1468
            >>> assert np.array_equal(picked, [0, 0, 1])

            Masking
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1469

1470
            >>> masked = scalar_field[[True, False, True]]
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
1471
1472
1473
1474
1475
            >>> assert masked.equal([[0, 0, 0], [0, -1, 0]])
            >>> assert masked.fields[0].equal([42, 10.5])
            >>> assert masked.fields[1].equal([1, 3])

            Iteration