core.py 48.7 KB
Newer Older
1
2
3
4
5
6
7
8
9
#!/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
"""
10
import tfields.bases
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
11
12
13
import numpy as np
from contextlib import contextmanager
from collections import Counter
14
15
16
import sympy
import scipy as sp
import scipy.spatial  # NOQA: F401
17
18
19
20
import os
from six import string_types
import pathlib
import warnings
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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:
        __slots__ (list of str): If you want to add attributes to
            your AbstractNdarray subclass, add the attribute name to __slots__
47
        __slot_defaults__ (list): if __slot_defaults__ is None, the
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
48
49
50
51
52
53
54
55
56
57
58
59
60
61
            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__
    TODO:
        equality check
    """
    __slots__ = []
62
    __slot_defaults__ = []
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
63
    __slotDtypes__ = []
64
    __slot_setters__ = []
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
65

66
    def __new__(cls, array, **kwargs):  # pragma: no cover
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
67
68
69
70
71
72
        raise NotImplementedError("{clsType} type must implement '__new__'"
                                  .format(clsType=type(cls)))

    def __array_finalize__(self, obj):
        if obj is None:
            return
73
        for attr in self._iter_slots():
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
74
75
76
77
78
79
            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
80
    def _iter_slots(cls):
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
81
82
83
        return [att for att in cls.__slots__ if att != '_cache']

    @classmethod
84
    def _update_slot_kwargs(cls, kwargs):
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
85
        """
86
        set the defaults in kwargs according to __slot_defaults__
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
87
88
        and convert the kwargs according to __slotDtypes__
        """
89
90
        slotDefaults = cls.__slot_defaults__ + \
            [None] * (len(cls.__slots__) - len(cls.__slot_defaults__))
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
91
92
93
94
95
96
97
98
        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:
99
100
101
102
                try:
                    kwargs[attr] = np.array(kwargs[attr], dtype=dtype)
                except Exception as err:
                    raise ValueError(str(attr) + str(dtype) + str(kwargs[attr]) + str(err))
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
103
104
105
106
107

    def __setattr__(self, name, value):
        if name in self.__slots__:
            index = self.__slots__.index(name)
            try:
108
                setter = self.__slot_setters__[index]
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
109
110
111
112
113
114
115
116
117
118
119
120
            except IndexError:
                setter = None
            if setter is not None:
                value = setter(value)
        super(AbstractNdarray, self).__setattr__(name, value)

    def __reduce__(self):
        """
        important for pickling
        Examples:
            >>> from tempfile import NamedTemporaryFile
            >>> import pickle
121
            >>> import tfields
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
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
147

            Build a dummy scalar field
            >>> from tfields import Tensors, TensorFields
            >>> scalars = Tensors([0, 1, 2])
            >>> vectors = Tensors([[0, 0, 0], [0, 0, 1], [0, -1, 0]])
            >>> scalarField = TensorFields(vectors, scalars, coordSys='cylinder')

            Save it and restore it
            >>> outFile = NamedTemporaryFile(suffix='.pickle')

            >>> pickle.dump(scalarField,
            ...             outFile)
            >>> _ = outFile.seek(0)

            >>> sf = pickle.load(outFile)
            >>> sf.coordSys == 'cylinder'
            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
148
                                              self._iter_slots()])
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
149
150
151
152
153
154
155
156
157

        # 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):
        """
        important for unpickling
        """
        # Call the parent's __setstate__ with the other tuple elements.
158
        super(AbstractNdarray, self).__setstate__(state[0:-len(self._iter_slots())])
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
159
160

        # set the __slot__ attributes
161
        for i, slot in enumerate(reversed(self._iter_slots())):
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
162
163
164
            index = -(i + 1)
            setattr(self, slot, state[index])

165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
    def copy(self, *args, **kwargs):
        """
        The standard ndarray copy does not copy slots. Correct for this.
        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

        TODO: This function implementation could be more general or maybe redirect to deepcopy?
        """
        inst = super(AbstractNdarray, self).copy(*args, **kwargs)
        for attr in self._iter_slots():
            value = getattr(self, attr)
            if hasattr(value, 'copy'):
                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

197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
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
    def save(self, path, *args, **kwargs):
        """
        Saving a tensors object 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):
            extension = pathlib.Path(path).suffix.lstrip('.')

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

        # resolve:     relative paths,  symlinks and    ~
        path = os.path.realpath(os.path.abspath(os.path.expanduser(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
        """
        extension = kwargs.pop('extension', 'npz')
        if isinstance(path, string_types):
            path = os.path.realpath(os.path.abspath(os.path.expanduser(path)))
            extension = pathlib.Path(path).suffix.lstrip('.')

        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.
        Examples:
            >>> import tfields
            >>> from tempfile import NamedTemporaryFile
            >>> outFile = NamedTemporaryFile(suffix='.npz')
            >>> p = tfields.Points3D([[1., 2., 3.], [4., 5., 6.], [1, 2, -6]])
            >>> p.save(outFile.name)
            >>> _ = outFile.seek(0)
            >>> p1 = tfields.Points3D.load(outFile.name)
            >>> assert p.equal(p1)

        """
        kwargs = {}
        for attr in self._iter_slots():
            if not hasattr(self, attr):
                # attribute in __slots__ not found.
                warnings.warn("When saving instance of class {0} Attribute {1} not set."
                              "This Attribute is not saved.".format(self.__class__, attr), Warning)
            else:
                kwargs[attr] = getattr(self, attr)

        np.savez(path, self, **kwargs)

    @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)
        keys = np_file.keys()
        bulk = np_file['arr_0']
        data_kwargs = {key: np_file[key] for key in keys if key not in ['arr_0']}
        return cls.__new__(cls, bulk, **data_kwargs)

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
286
287
288
289
290
291
292
293
294
295
296
297

class Tensors(AbstractNdarray):
    """
    Set of tensors with the same basis.
    TODO:
        all slot args should be protected -> _base
    Args:
        tensors: np.ndarray or AbstractNdarray subclass
    Examples:
        >>> import numpy as np

        Initialize a scalar range
298
        >>> scalars = tfields.Tensors([0, 1, 2])
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
299
300
301
302
        >>> scalars.rank == 0
        True

        Initialize vectors
303
        >>> vectors = tfields.Tensors([[0, 0, 0], [0, 0, 1], [0, -1, 0]])
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
304
305
306
307
308
309
310
        >>> vectors.rank == 1
        True
        >>> vectors.dim == 3
        True
        >>> assert vectors.coordSys == 'cartesian'

        Initialize the Levi-Zivita Tensor
311
        >>> matrices = tfields.Tensors([[[0, 0, 0], [0, 0, 1], [0, -1, 0]],
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
312
313
314
315
316
317
318
319
320
321
        ...                     [[0, 0, -1], [0, 0, 0], [1, 0, 0]],
        ...                     [[0, 1, 0], [-1, 0, 0], [0, 0, 0]]])
        >>> matrices.shape == (3, 3, 3)
        True
        >>> matrices.rank == 2
        True
        >>> matrices.dim == 3
        True

        Initializing in different start coordinate system
322
        >>> cyl = tfields.Tensors([[5, np.arctan(4. / 3.), 42]], coordSys='cylinder')
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
323
        >>> assert cyl.coordSys == 'cylinder'
324
        >>> cyl.transform('cartesian')
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
325
326
327
328
329
330
331
        >>> assert cyl.coordSys == 'cartesian'
        >>> 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
332
        >>> with vectors.tmp_transform('cylinder'):
333
        ...     vect_cyl = tfields.Tensors(vectors)
334
335
        ...     assert vect_cyl.coordSys == vectors.coordSys
        >>> assert vect_cyl.coordSys == 'cylinder'
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
336
337

        You can demand a special dimension.
338
339
        >>> _ = tfields.Tensors([[1, 2, 3]], dim=3)
        >>> _ = tfields.Tensors([[1, 2, 3]], dim=2)  # doctest: +ELLIPSIS
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
340
341
342
343
        Traceback (most recent call last):
            ...
        ValueError: Incorrect dimension: 3 given, 2 demanded.

344
345
        The dimension argument (dim) becomes necessary if you want to initialize
        an empty array
346
        >>> _ = tfields.Tensors([])  # doctest: +ELLIPSIS
347
348
349
        Traceback (most recent call last):
            ...
        ValueError: Empty tensors need dimension parameter 'dim'.
350
        >>> tfields.Tensors([], dim=7)
351
352
        Tensors([], shape=(0, 7), dtype=float64)

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
353
354
    """
    __slots__ = ['coordSys']
355
356
    __slot_defaults__ = ['cartesian']
    __slot_setters__ = [tfields.bases.get_coord_system_name]
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
357
358

    def __new__(cls, tensors, **kwargs):
359
360
361
        dtype = kwargs.pop('dtype', np.float64)
        order = kwargs.pop('order', None)

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
362
363
364
        ''' copy constructor '''
        if issubclass(type(tensors), cls):
            obj = tensors.copy()
365
            if dtype != obj.dtype or order is not None:
366
                obj = obj.astype(dtype, order=order)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
367
368
            coordSys = kwargs.pop('coordSys', None)
            if kwargs:
369
                raise AttributeError("In copy constructor only 'dtype' and 'coordSys' "
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
370
371
372
373
                                     "attribute is supported. Kwargs {kwargs} "
                                     "are not consumed"
                                     .format(**locals()))
            if coordSys is not None:
374
                obj.transform(coordSys)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
375
376
377
378
379
380
381
            return obj

        dim = kwargs.pop('dim', None)

        ''' process empty inputs '''
        if len(tensors) == 0:
            if dim is not None:
382
                tensors = np.empty((0, dim))
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
383
384
385
386
387
388
389
390
391
392
            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:
393
394
395
396
                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
397
398
399
400
401
402
403
        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 '''
404
        cls._update_slot_kwargs(kwargs)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
405
406
407

        ''' set kwargs to slots attributes '''
        for attr in kwargs:
408
            if attr not in cls._iter_slots():
409
                raise AttributeError("Keyword argument {attr} not accepted "
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
410
411
412
413
414
415
416
417
418
419
420
421
422
                                     "for class {cls}".format(**locals()))
            setattr(obj, attr, kwargs[attr])

        return obj

    @classmethod
    def merged(cls, *objects, **kwargs):
        """
        Factory method
        Merges all tensor inputs to one tensor

        Examples:
            >>> import numpy as np
423
            >>> import tfields
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
424
            >>> import tfields.bases
425
426
427
428
            >>> vecA = tfields.Tensors([[0, 0, 0], [0, 0, 1], [0, -1, 0]])
            >>> vecB = tfields.Tensors([[5, 4, 1]], coordSys=tfields.bases.cylinder)
            >>> vecC = tfields.Tensors([[5, 4, 1]], coordSys=tfields.bases.cylinder)
            >>> merge = tfields.Tensors.merged(vecA, vecB, vecC, [[2, 0, 1]])
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
429
430
431
432
433
434
435
436
437
438
439
            >>> assert merge.coordSys == 'cylinder'

        """

        ''' get most frequent coordSys or predefined coordSys '''
        coordSys = kwargs.get('coordSys', None)
        if coordSys is None:
            bases = []
            for t in objects:
                try:
                    bases.append(t.coordSys)
440
                except AttributeError:
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
                    pass
            # get most frequent coordSys
            coordSys = sorted(bases, key=Counter(bases).get, reverse=True)[0]
            kwargs['coordSys'] = coordSys

        ''' transform all raw inputs to cls type with correct coordSys. Also
        automatically make a copy of those instances that are of the correct
        type already.'''
        objects = [cls(t, **kwargs) for t in objects]

        ''' 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)
        return cls.__new__(cls, tensors, **kwargs)

465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
    @classmethod
    def grid(cls, *base_vectors, **kwargs):
        """
        Args:
            baseVector 0 (list/np.array of base coordinates)
            baseVector 1 (list/np.array of base coordinates)
            baseVector 2 (list/np.array of base coordinates)
        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]])

        Examples:
            Initilaize using the mgrid notation
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
            >>> 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
            >>> 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
521
522

        """
523
        inst = cls.__new__(cls, tfields.lib.grid.igrid(*base_vectors, **kwargs))
524
525
        return inst

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
526
527
528
529
530
531
532
533
534
535
536
537
538
539
    @property
    def rank(self):
        """
        Tensor rank
        """
        return rank(self)

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

540
    def transform(self, coordSys):
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
541
542
543
544
545
546
        """
        Args:
            coordSys (str)

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

            CARTESIAN to SPHERICAL
550
            >>> t = tfields.Tensors([[1, 2, 2], [1, 0, 0], [0, 0, -1], [0, 0, 1], [0, 0, 0]])
551
            >>> t.transform('spherical')
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570

            r
            >>> assert t[0, 0] == 3

            phi
            >>> assert t[1, 1] == 0.
            >>> assert t[2, 1] == 0.

            theta is 0 at (0, 0, 1) and pi at (0, 0, -1)
            >>> assert round(t[1, 2], 10) == round(np.pi / 2, 10)
            >>> assert t[2, 2] == np.pi
            >>> assert t[3, 2] == 0.

            theta is defined 0 for R == 0
            >>> assert t[4, 0] == 0.
            >>> assert t[4, 2] == 0.


            CARTESIAN to CYLINDER
571
            >>> 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
572
            >>> tCyl = tCart.copy()
573
            >>> tCyl.transform('cylinder')
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
            >>> assert tCyl.coordSys == 'cylinder'

            R
            >>> assert tCyl[0, 0] == 5
            >>> assert tCyl[1, 0] == 1
            >>> assert tCyl[2, 0] == 1
            >>> assert tCyl[4, 0] == 0

            Phi
            >>> assert round(tCyl[0, 1], 10) == round(np.arctan(4. / 3), 10)
            >>> assert tCyl[1, 1] == 0
            >>> assert round(tCyl[2, 1], 10) == round(np.pi / 2, 10)
            >>> assert tCyl[1, 1] == 0

            Z
            >>> assert tCyl[0, 2] == 42
            >>> assert tCyl[2, 2] == -1

592
            >>> tCyl.transform('cartesian')
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
593
594
595
596
597
598
599
600
601
            >>> assert tCyl.coordSys == 'cartesian'
            >>> assert tCyl[0, 0] == 3

        """
        #           scalars                 empty             already there
        if self.rank == 0 or self.shape[0] == 0 or self.coordSys == coordSys:
            self.coordSys = coordSys
            return

602
603
        tfields.bases.transform(self, self.coordSys, coordSys)
        # self[:] = tfields.bases.transform(self, self.coordSys, coordSys)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
604
605
606
        self.coordSys = coordSys

    @contextmanager
607
    def tmp_transform(self, coordSys):
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
608
609
610
611
612
        """
        Temporarily change the coordSys to another coordSys and change it back at exit
        This method is for cleaner code only.
        No speed improvements go with this.
        Args:
613
            see transform
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
614
        Examples:
615
            >>> import tfields
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
616
            >>> p = tfields.Tensors([[1,2,3]], coordSys=tfields.bases.SPHERICAL)
617
            >>> with p.tmp_transform(tfields.bases.CYLINDER):
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
618
619
620
621
622
            ...     assert p.coordSys == tfields.bases.CYLINDER
            >>> assert p.coordSys == tfields.bases.SPHERICAL

        """
        baseBefore = self.coordSys
623
        if baseBefore == coordSys:
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
624
625
            yield
        else:
626
            self.transform(coordSys)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
627
628
629

            yield

630
631
            self.transform(baseBefore)

632
633
634
635
636
637
    def mirror(self, coordinate, condition=None):
        """
        Reflect/Mirror the entries meeting <condition> at <coordinate> = 0
        Args:
            coordinate (int): coordinate index
        Examples:
638
            >>> import tfields
639
640
            >>> p = tfields.Tensors([[1., 2., 3.], [4., 5., 6.], [1, 2, -6]])
            >>> p.mirror(1)
641
            >>> assert p.equal([[1, -2, 3], [4, -5,  6], [1, -2, -6]])
642
643
644
645

            multiple coordinates can be mirrored. Eg. a point mirrorion would be
            >>> p = tfields.Tensors([[1., 2., 3.], [4., 5., 6.], [1, 2, -6]])
            >>> p.mirror([0,2])
646
            >>> assert p.equal([[-1, 2, -3], [-4, 5, -6], [-1, 2., 6.]])
647
648
649
650
651
652

            You can give a condition as mask or as str.
            The mirroring will only be applied to the points meeting the condition.
            >>> import sympy
            >>> x, y, z = sympy.symbols('x y z')
            >>> p.mirror([0,2], y > 3)
653
654
            >>> p.equal([[-1, 2, -3], [4, 5, 6], [-1, 2, 6]])
            True
655
656
657
658
659
660
661
662
663
664
665
666
667
668

        """
        if condition is None:
            condition = np.array([True for i in range(len(self))])
        elif isinstance(condition, sympy.Basic):
            condition = self.getMask(condition)
        if isinstance(coordinate, list) or isinstance(coordinate, tuple):
            for c in coordinate:
                self.mirror(c, condition)
        elif isinstance(coordinate, int):
            self[:, coordinate][condition] *= -1
        else:
            raise TypeError()

669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
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
721
722
    def to_segment(self, segment, num_segments, coordinate,
                   periodicity=2 * np.pi, offset=0,
                   coordSys=None):
        """
        For circular (close into themself after
        <periodicity>) coordinates at index <coordinate> assume
        <num_segments> segments and transform all values to
        segment number <segment> 
        Examples:
            >>> import tfields
            >>> import numpy as np
            >>> pStart = tfields.Points3D([[6, 2 * np.pi, 1],
            ...                            [6, 2 * np.pi / 5 * 3, 1]],
            ...                           coordSys='cylinder')
            >>> 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))

        if coordSys is None:
            coordSys = self.coordSys
        with self.tmp_transform(coordSys):
            # 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):
        """
        Test, whether the instance has the same content as other.
        Args:
            optional:
                rtol (float)
                atol (float)
                equal_nan (bool)
            see numpy.isclose
        """
        if issubclass(type(other), Tensors) and self.coordSys != other.coordSys:
            other = other.copy()
            other.transform(self.coordSys)
        if rtol is None and atol is None:
            if return_bool:
                return np.array_equal(self, other)
            return self == other
723
724
725
726
        elif rtol is None:
            rtol = 0.
        elif atol is None:
            atol = 0.
727
728
729
730
731
732
733
734
735
736
        mask = np.isclose(self, other, 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
        Examples:
737
            >>> import tfields
738
739
740
741
742
743
744
            >>> 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))

745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
    def indices(self, tensor):
        """
        Returns:
            list of int: indices of tensor occuring
        """
        indices = []
        for i, p in enumerate(self):
            if all(p == tensor):
                indices.append(i)
        return indices

    def index(self, tensor):
        """
        Args:
            tensor
        Returns:
            int: index of tensor occuring
        """
        indices = self.indices(tensor)
        if not indices:
            return None
        if len(indices) == 1:
            return indices[0]
        raise ValueError("Multiple occurences of value {}"
                         .format(tensor))

771
772
773
774
775
776
777
778
779
780
    def getMoment(self, moment):
        """
        Returns:
            Moments of the distribution.
        Note:
            The first moment is given as the mean,
            second as variance etc. Not 0 as it is mathematicaly correct.
        Args:
            moment (int): n-th moment
        """
781
        return tfields.lib.stats.getMoment(self, moment)
782

783
784
785
786
787
788
789
790
    def closestPoints(self, other, **kwargs):
        """
        Args:
            other (Tensors): closest points to what? -> other
            **kwargs: forwarded to scipy.spatial.cKDTree.query
        Returns:
            array shape(len(self)): Indices of other points that are closest to own points
        Examples:
791
            >>> import tfields
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
            >>> 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.closestPoints(m)
            array([2, 3, 4])

        """
        with other.tmp_transform(self.coordSys):
            # balanced_tree option gives huge speedup!
            kdTree = sp.spatial.cKDTree(other, 1000,
                                        balanced_tree=False)
            res = kdTree.query(self, **kwargs)
            array = res[1]

        return array

    def getMask(self, cutExpression=None, coordSys=None):
        """
        Args:
            cutExpression (sympy logical expression)
            coordSys (str): coordSys to evaluate the expression in.
        Returns: np.array of dtype bool with lenght of number of points in self.
                 This array is True, where cutExpression evaluates True.
        Examples:
816
817
818
            >>> import tfields
            >>> import numpy
            >>> import sympy
819
820
821
            >>> x, y, z = sympy.symbols('x y z')
            >>> p = tfields.Points3D([[1., 2., 3.], [4., 5., 6.], [1, 2, -6],
            ...               [-5, -5, -5], [1,0,-1], [0,1,-1]])
822
823
824
            >>> np.array_equal(p.getMask(x > 0),
            ...                [True, True, True, False, True, False])
            True
825
826

            And combination
827
828
829
            >>> np.array_equal(p.getMask((x > 0) & (y < 3)),
            ...                [True, False, True, False, True, False])
            True
830
831

            Or combination
832
833
834
            >>> np.array_equal(p.getMask((x > 0) | (y > 3)),
            ...                [True, True, True, False, True, False])
            True
835
836
837

        """
        coords = sympy.symbols('x y z')
838
        with self.tmp_transform(coordSys or self.coordSys):
839
840
841
842
843
844
845
846
847
848
849
            mask = tfields.getMask(self, cutExpression, coords=coords)
        return mask

    def cut(self, cutExpression, coordSys=None):
        """
        Default cut method for Points3D. Works on a copy.
        Args:
            cutExpression (sympy logical expression): logical expression which will be evaluated.
                             use symbols x, y and z
            coordSys (str): coordSys to evaluate the expression in.
        Examples:
850
851
            >>> import tfields
            >>> import sympy
852
            >>> x, y, z = sympy.symbols('x y z')
853
854
855
856
857
858
859
            >>> 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
860
861

            combinations of cuts
862
863
            >>> p.cut((x > 0) & (z < 0)).equal([[1, 2, -6], [1, 0, -1]])
            True
864
865
866
867
868
869
870

        Returns:
            copy of self with cut applied

        """
        if len(self) == 0:
            return self.copy()
871
        mask = self.getMask(cutExpression, coordSys=coordSys or self.coordSys)
872
873
874
875
        mask.astype(bool)
        inst = self[mask].copy()
        return inst

Daniel Böckenhoff's avatar
Daniel Böckenhoff committed
876
    def distances(self, other, **kwargs):
877
878
        """
        Args:
Daniel Böckenhoff's avatar
Daniel Böckenhoff committed
879
880
881
            other(array)
            **kwargs:
                ... is forwarded to sp.spatial.distance.cdist
882
        Examples:
883
            >>> import tfields
884
885
886
            >>> p = tfields.Tensors.grid((0, 2, 3j),
            ...                          (0, 2, 3j),
            ...                          (0, 0, 1j))
887
888
889
890
891
            >>> p[4,2] = 1
            >>> p.distances(p)[0,0]
            0.0
            >>> p.distances(p)[5,1]
            1.4142135623730951
892
893
            >>> p.distances([[0,1,2]])[-1][0] == 3
            True
894
895

        """
Daniel Böckenhoff's avatar
Daniel Böckenhoff committed
896
897
898
899
        if issubclass(type(other), Tensors) and self.coordSys != other.coordSys:
            other = other.copy()
            other.transform(self.coordSys)
        return sp.spatial.distance.cdist(self, other, **kwargs)
900

Daniel Böckenhoff's avatar
Daniel Böckenhoff committed
901
    def minDistances(self, other=None, **kwargs):
902
        """
Daniel Böckenhoff's avatar
Daniel Böckenhoff committed
903
904
905
906
907
908
909
910
        Args:
            other(array or None)
            **kwargs:
                memory_saving (bool): for very large array comparisons
                    default False
                ... rest is forwarded to sp.spatial.distance.cdist


911
        Examples:
912
913
            >>> import tfields
            >>> import numpy as np
914
915
916
917
918
            >>> p = tfields.Tensors.grid((0, 2, 3),
            ...                          (0, 2, 3),
            ...                          (0, 0, 1))
            >>> p[4,2] = 1
            >>> dMin = p.minDistances()
919
920
921
922
            >>> expected = [1] * 9
            >>> expected[4] = np.sqrt(2)
            >>> np.array_equal(dMin, expected)
            True
923

Daniel Böckenhoff's avatar
Daniel Böckenhoff committed
924
            >>> dMin2 = p.minDistances(memory_saving=True)
925
926
927
928
            >>> bool((dMin2 == dMin).all())
            True

        """
Daniel Böckenhoff's avatar
Daniel Böckenhoff committed
929
        memory_saving = kwargs.pop('memory_saving', False)
930

Daniel Böckenhoff's avatar
Daniel Böckenhoff committed
931
        if other is None:
932
            other = self
Daniel Böckenhoff's avatar
Daniel Böckenhoff committed
933
934
        else:
            raise NotImplementedError("Should be easy but make shure not to remove diagonal")
935
936

        try:
Daniel Böckenhoff's avatar
Daniel Böckenhoff committed
937
            if memory_saving:
938
                raise MemoryError()
Daniel Böckenhoff's avatar
Daniel Böckenhoff committed
939
            d = self.distances(other, **kwargs)
940
941
            return d[d > 0].reshape(d.shape[0], - 1).min(axis=1)
        except MemoryError:
Daniel Böckenhoff's avatar
Daniel Böckenhoff committed
942
            min_dists = np.empty(self.shape[0])
943
            for i, point in enumerate(other):
Daniel Böckenhoff's avatar
Daniel Böckenhoff committed
944
945
946
                d = self.distances([point], **kwargs)
                min_dists[i] = d[d > 0].reshape(-1).min()
            return min_dists
947

Daniel Böckenhoff's avatar
Daniel Böckenhoff committed
948
    def epsilon_neighbourhood(self, epsilon):
949
950
951
952
953
954
        """
        Returns:
            indices for those sets of points that lie within epsilon around the other
        Examples:
            Create mesh grid with one extra point that will have 8 neighbours
            within epsilon
955
            >>> import tfields
956
957
958
            >>> p = tfields.Tensors.grid((0, 1, 2j),
            ...                          (0, 1, 2j),
            ...                          (0, 1, 2j))
959
            >>> p = tfields.Tensors.merged(p, [[0.5, 0.5, 0.5]])
Daniel Böckenhoff's avatar
Daniel Böckenhoff committed
960
            >>> [len(en) for en in p.epsilon_neighbourhood(0.9)]
961
962
963
964
965
966
967
968
            [2, 2, 2, 2, 2, 2, 2, 2, 9]

        """
        indices = np.arange(self.shape[0])
        dists = self.distances(self)
        distsInEpsilon = dists <= epsilon
        return [indices[die] for die in distsInEpsilon]

969

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
class TensorFields(Tensors):
    """
    Discrete Tensor Field

    Examples:
        >>> from tfields import Tensors, TensorFields
        >>> scalars = Tensors([0, 1, 2])
        >>> vectors = Tensors([[0, 0, 0], [0, 0, 1], [0, -1, 0]])
        >>> scalarField = TensorFields(vectors, scalars)
        >>> scalarField.rank
        1
        >>> scalarField.fields[0].rank
        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

994
995
996
997
998
999
1000
        Empty initialization
        >>> empty_field = TensorFields([], dim=3)
        >>> assert empty_field.shape == (0, 3)
        >>> assert empty_field.fields == []

        Directly initializing with lists or arrays
        >>> vec_field_raw = tfields.TensorFields([[0, 1, 2], [3, 4, 5]],