core.py 53.3 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
        dtype = kwargs.pop('dtype', np.float64)
        order = kwargs.pop('order', None)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
361
362
        dim = kwargs.pop('dim', None)

363
364
365
366
367
368
369
370
371
372
        ''' copy constructor extracts the kwargs from tensors'''
        if issubclass(type(tensors), Tensors):
            dtype = tensors.dtype
            if dim is not None:
                dim = tensors.dim
            coordSys = kwargs.pop('coordSys', tensors.coordSys)
            tensors = tensors.copy()
            tensors.transform(coordSys)
            kwargs['coordSys'] = coordSys

373
374
375
376
377
378
379
380
        ''' demand iterable structure '''
        try:
            len(tensors)
        except TypeError as err:
            raise TypeError("Iterable structure necessary."
                            " Got {tensors}"
                            .format(**locals()))

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

        ''' set kwargs to slots attributes '''
        for attr in kwargs:
412
            if attr not in cls._iter_slots():
413
                raise AttributeError("Keyword argument {attr} not accepted "
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
414
415
416
417
418
419
420
421
422
423
424
425
426
                                     "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
427
            >>> import tfields
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
428
429
            >>> import tfields.bases

430
431
432
433
434
435
436
437
438
439
440
441
442
            Use of most frequent coordinate system
            >>> vec_a = tfields.Tensors([[0, 0, 0], [0, 0, 1], [0, -1, 0]])
            >>> vec_b = tfields.Tensors([[5, 4, 1]], coordSys=tfields.bases.cylinder)
            >>> vec_c = tfields.Tensors([[4, 2, 3]], coordSys=tfields.bases.cylinder)
            >>> merge = tfields.Tensors.merged(vec_a, vec_b, vec_c, [[2, 0, 1]])
            >>> assert merge.coordSys == 'cylinder'
            >>> assert merge.equal([[0, 0, 0],
            ...                     [0, 0, 1],
            ...                     [1, -np.pi / 2, 0],
            ...                     [5, 4, 1],
            ...                     [4, 2, 3],
            ...                     [2, 0, 1]])

443
            Merge also shifts the maps to still refer to the same tensors
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
            >>> tm_a = tfields.TensorMaps(merge, maps=[[[0, 1, 2]]])
            >>> tm_b = tm_a.copy()
            >>> tm_a.coordSys
            >>> tm_merge = tfields.TensorMaps.merged(tm_a, tm_b)
            >>> assert tm_merge.coordSys == 'cylinder'
            >>> assert tm_merge.maps[0].equal([[0, 1, 2],
            ...                               list(range(len(merge),
            ...                                          len(merge) + 3,
            ...                                          1))])
            
            >>> obj_list = [tfields.Tensors([[1, 2, 3]], coordSys=tfields.bases.CYLINDER),
            ...             tfields.Tensors([[3] * 3]),
            ...             tfields.Tensors([[5, 1, 3]])]
            >>> merge2 = tfields.Tensors.merged(*obj_list, coordSys=tfields.bases.CARTESIAN)
            >>> assert merge2.equal([[-0.41614684, 0.90929743, 3.],
            ...                      [3, 3, 3], [5, 1, 3]], atol=1e-8)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
460
461
462
463
        """

        ''' get most frequent coordSys or predefined coordSys '''
        coordSys = kwargs.get('coordSys', None)
464
        dimension = kwargs.get('dim', None)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
465
466
467
468
469
        if coordSys is None:
            bases = []
            for t in objects:
                try:
                    bases.append(t.coordSys)
470
                except AttributeError:
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
                    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)
493
494
495
496
497

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

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
498
499
        return cls.__new__(cls, tensors, **kwargs)

500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
    @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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
            >>> 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
556
557

        """
558
        inst = cls.__new__(cls, tfields.lib.grid.igrid(*base_vectors, **kwargs))
559
560
        return inst

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
561
562
563
564
565
566
567
568
569
570
571
572
573
574
    @property
    def rank(self):
        """
        Tensor rank
        """
        return rank(self)

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

575
    def transform(self, coordSys):
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
576
577
578
579
580
581
        """
        Args:
            coordSys (str)

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

            CARTESIAN to SPHERICAL
585
            >>> t = tfields.Tensors([[1, 2, 2], [1, 0, 0], [0, 0, -1], [0, 0, 1], [0, 0, 0]])
586
            >>> t.transform('spherical')
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
587
588
589
590
591
592
593
594

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

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

595
596
597
598
            theta is 0 at (0, 0, 1) and pi / 2 at (0, 0, -1)
            >>> assert round(t[1, 2], 10) == round(0, 10)
            >>> assert t[2, 2] == -np.pi / 2
            >>> assert t[3, 2] == np.pi / 2
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
599
600
601
602
603
604
605

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


            CARTESIAN to CYLINDER
606
            >>> tCart = tfields.Tensors([[3, 4, 42], [1, 0, 0], [0, 1, -1], [-1, 0, 1], [0, 0, 0]])
607
608
609
            >>> t_cyl = tCart.copy()
            >>> t_cyl.transform('cylinder')
            >>> assert t_cyl.coordSys == 'cylinder'
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
610
611

            R
612
613
614
615
            >>> assert t_cyl[0, 0] == 5
            >>> assert t_cyl[1, 0] == 1
            >>> assert t_cyl[2, 0] == 1
            >>> assert t_cyl[4, 0] == 0
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
616
617

            Phi
618
619
620
621
            >>> 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
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
622
623

            Z
624
625
            >>> assert t_cyl[0, 2] == 42
            >>> assert t_cyl[2, 2] == -1
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
626

627
628
629
            >>> t_cyl.transform('cartesian')
            >>> assert t_cyl.coordSys == 'cartesian'
            >>> assert t_cyl[0, 0] == 3
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
630
631
632
633
634
635
636

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

637
638
        tfields.bases.transform(self, self.coordSys, coordSys)
        # self[:] = tfields.bases.transform(self, self.coordSys, coordSys)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
639
640
641
        self.coordSys = coordSys

    @contextmanager
642
    def tmp_transform(self, coordSys):
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
643
644
645
646
647
        """
        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:
648
            see transform
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
649
        Examples:
650
            >>> import tfields
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
651
            >>> p = tfields.Tensors([[1,2,3]], coordSys=tfields.bases.SPHERICAL)
652
            >>> with p.tmp_transform(tfields.bases.CYLINDER):
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
653
654
655
656
657
            ...     assert p.coordSys == tfields.bases.CYLINDER
            >>> assert p.coordSys == tfields.bases.SPHERICAL

        """
        baseBefore = self.coordSys
658
        if baseBefore == coordSys:
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
659
660
            yield
        else:
661
            self.transform(coordSys)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
662
663
664

            yield

665
666
            self.transform(baseBefore)

667
668
669
670
671
672
    def mirror(self, coordinate, condition=None):
        """
        Reflect/Mirror the entries meeting <condition> at <coordinate> = 0
        Args:
            coordinate (int): coordinate index
        Examples:
673
            >>> import tfields
674
675
            >>> p = tfields.Tensors([[1., 2., 3.], [4., 5., 6.], [1, 2, -6]])
            >>> p.mirror(1)
676
            >>> assert p.equal([[1, -2, 3], [4, -5,  6], [1, -2, -6]])
677
678
679
680

            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])
681
            >>> assert p.equal([[-1, 2, -3], [-4, 5, -6], [-1, 2., 6.]])
682
683
684
685
686
687

            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)
688
689
            >>> p.equal([[-1, 2, -3], [4, 5, 6], [-1, 2, 6]])
            True
690
691
692
693
694
695
696
697
698
699
700
701
702
703

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

704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
    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
758
759
760
761
        elif rtol is None:
            rtol = 0.
        elif atol is None:
            atol = 0.
762
763
764
765
766
767
768
769
770
771
        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:
772
            >>> import tfields
773
774
775
776
777
778
779
            >>> 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))

780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
    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))

806
807
808
809
810
811
812
813
814
815
    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
        """
816
        return tfields.lib.stats.getMoment(self, moment)
817

818
819
820
821
822
823
824
825
    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:
826
            >>> import tfields
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
            >>> 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:
851
852
853
            >>> import tfields
            >>> import numpy
            >>> import sympy
854
855
856
            >>> 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]])
857
858
859
            >>> np.array_equal(p.getMask(x > 0),
            ...                [True, True, True, False, True, False])
            True
860
861

            And combination
862
863
864
            >>> np.array_equal(p.getMask((x > 0) & (y < 3)),
            ...                [True, False, True, False, True, False])
            True
865
866

            Or combination
867
868
869
            >>> np.array_equal(p.getMask((x > 0) | (y > 3)),
            ...                [True, True, True, False, True, False])
            True
870
871
872

        """
        coords = sympy.symbols('x y z')
873
        with self.tmp_transform(coordSys or self.coordSys):
874
875
876
877
878
879
880
881
882
883
884
            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:
885
886
            >>> import tfields
            >>> import sympy
887
            >>> x, y, z = sympy.symbols('x y z')
888
889
890
891
892
893
894
            >>> 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
895
896

            combinations of cuts
897
898
            >>> p.cut((x > 0) & (z < 0)).equal([[1, 2, -6], [1, 0, -1]])
            True
899
900
901
902
903
904
905

        Returns:
            copy of self with cut applied

        """
        if len(self) == 0:
            return self.copy()
906
        mask = self.getMask(cutExpression, coordSys=coordSys or self.coordSys)
907
908
909
910
        mask.astype(bool)
        inst = self[mask].copy()
        return inst

Daniel Böckenhoff's avatar
Daniel Böckenhoff committed
911
    def distances(self, other, **kwargs):
912
913
        """
        Args:
Daniel Böckenhoff's avatar
Daniel Böckenhoff committed
914
915
916
            other(array)
            **kwargs:
                ... is forwarded to sp.spatial.distance.cdist
917
        Examples:
918
            >>> import tfields
919
920
921
            >>> p = tfields.Tensors.grid((0, 2, 3j),
            ...                          (0, 2, 3j),
            ...                          (0, 0, 1j))
922
923
924
925
926
            >>> p[4,2] = 1
            >>> p.distances(p)[0,0]
            0.0
            >>> p.distances(p)[5,1]
            1.4142135623730951
927
928
            >>> p.distances([[0,1,2]])[-1][0] == 3
            True
929
930

        """
Daniel Böckenhoff's avatar
Daniel Böckenhoff committed
931
932
933
934
        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)
935

Daniel Böckenhoff's avatar
Daniel Böckenhoff committed
936
    def minDistances(self, other=None, **kwargs):
937
        """
Daniel Böckenhoff's avatar
Daniel Böckenhoff committed
938
939
940
941
942
943
944
945
        Args:
            other(array or None)
            **kwargs:
                memory_saving (bool): for very large array comparisons
                    default False
                ... rest is forwarded to sp.spatial.distance.cdist


946
        Examples:
947
948
            >>> import tfields
            >>> import numpy as np
949
950
951
952
953
            >>> p = tfields.Tensors.grid((0, 2, 3),
            ...                          (0, 2, 3),
            ...                          (0, 0, 1))
            >>> p[4,2] = 1
            >>> dMin = p.minDistances()
954
955
956
957
            >>> expected = [1] * 9
            >>> expected[4] = np.sqrt(2)
            >>> np.array_equal(dMin, expected)
            True
958

Daniel Böckenhoff's avatar
Daniel Böckenhoff committed
959
            >>> dMin2 = p.minDistances(memory_saving=True)
960
961
962
963
            >>> bool((dMin2 == dMin).all())
            True

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

Daniel Böckenhoff's avatar
Daniel Böckenhoff committed
966
        if other is None:
967
            other = self
Daniel Böckenhoff's avatar
Daniel Böckenhoff committed
968
969
        else:
            raise NotImplementedError("Should be easy but make shure not to remove diagonal")
970
971

        try:
Daniel Böckenhoff's avatar
Daniel Böckenhoff committed
972
            if memory_saving:
973
                raise MemoryError()
Daniel Böckenhoff's avatar
Daniel Böckenhoff committed
974
            d = self.distances(other, **kwargs)
975
976
            return d[d > 0].reshape(d.shape[0], - 1).min(axis=1)
        except MemoryError:
Daniel Böckenhoff's avatar
Daniel Böckenhoff committed
977
            min_dists = np.empty(self.shape[0])
978
            for i, point in enumerate(other):
Daniel Böckenhoff's avatar
Daniel Böckenhoff committed
979
980
981
                d = self.distances([point], **kwargs)
                min_dists[i] = d[d > 0].reshape(-1).min()
            return min_dists
982

Daniel Böckenhoff's avatar
Daniel Böckenhoff committed
983
    def epsilon_neighbourhood(self, epsilon):
984
985
986
987
988
989
        """
        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
990
            >>> import tfields
991
992
993
            >>> p = tfields.Tensors.grid((0, 1, 2j),
            ...                          (0, 1, 2j),
            ...                          (0, 1, 2j))
994
            >>> p = tfields.Tensors.merged(p, [[0.5, 0.5, 0.5]])
Daniel Böckenhoff's avatar
Daniel Böckenhoff committed
995
            >>> [len(en) for en in p.epsilon_neighbourhood(0.9)]
996
997
998
999
1000
            [2, 2, 2, 2, 2, 2, 2, 2, 9]

        """
        indices = np.arange(self.shape[0])
        dists = self.distances(self)