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

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

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

        ''' set kwargs to slots attributes '''
        for attr in kwargs:
419
            if attr not in cls._iter_slots():
420
                raise AttributeError("Keyword argument {attr} not accepted "
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
421
422
423
424
425
426
427
428
429
430
431
432
433
                                     "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
434
            >>> import tfields
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
435
436
            >>> import tfields.bases

437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
            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]])

            >>> 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
466
467
468
469
        """

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

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

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

506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
    @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
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
556
557
558
559
560
561
            >>> 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
562
563

        """
564
        inst = cls.__new__(cls, tfields.lib.grid.igrid(*base_vectors, **kwargs))
565
566
        return inst

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
567
568
569
570
571
572
573
574
575
576
577
578
579
580
    @property
    def rank(self):
        """
        Tensor rank
        """
        return rank(self)

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

581
    def transform(self, coordSys):
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
582
583
584
585
586
587
        """
        Args:
            coordSys (str)

        Examples:
            >>> import numpy as np
588
            >>> import tfields
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
589
590

            CARTESIAN to SPHERICAL
591
            >>> t = tfields.Tensors([[1, 2, 2], [1, 0, 0], [0, 0, -1], [0, 0, 1], [0, 0, 0]])
592
            >>> t.transform('spherical')
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
593
594
595
596
597
598
599
600

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

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

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

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


            CARTESIAN to CYLINDER
612
            >>> 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
613
            >>> tCyl = tCart.copy()
614
            >>> tCyl.transform('cylinder')
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
            >>> 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

633
            >>> tCyl.transform('cartesian')
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
634
635
636
637
638
639
640
641
642
            >>> 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

643
644
        tfields.bases.transform(self, self.coordSys, coordSys)
        # self[:] = tfields.bases.transform(self, self.coordSys, coordSys)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
645
646
647
        self.coordSys = coordSys

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

        """
        baseBefore = self.coordSys
664
        if baseBefore == coordSys:
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
665
666
            yield
        else:
667
            self.transform(coordSys)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
668
669
670

            yield

671
672
            self.transform(baseBefore)

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

            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])
687
            >>> assert p.equal([[-1, 2, -3], [-4, 5, -6], [-1, 2., 6.]])
688
689
690
691
692
693

            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)
694
695
            >>> p.equal([[-1, 2, -3], [4, 5, 6], [-1, 2, 6]])
            True
696
697
698
699
700
701
702
703
704
705
706
707
708
709

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

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
758
759
760
761
762
763
    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
764
765
766
767
        elif rtol is None:
            rtol = 0.
        elif atol is None:
            atol = 0.
768
769
770
771
772
773
774
775
776
777
        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:
778
            >>> import tfields
779
780
781
782
783
784
785
            >>> 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))

786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
    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))

812
813
814
815
816
817
818
819
820
821
    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
        """
822
        return tfields.lib.stats.getMoment(self, moment)
823

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

            And combination
868
869
870
            >>> np.array_equal(p.getMask((x > 0) & (y < 3)),
            ...                [True, False, True, False, True, False])
            True
871
872

            Or combination
873
874
875
            >>> np.array_equal(p.getMask((x > 0) | (y > 3)),
            ...                [True, True, True, False, True, False])
            True
876
877
878

        """
        coords = sympy.symbols('x y z')
879
        with self.tmp_transform(coordSys or self.coordSys):
880
881
882
883
884
885
886
887
888
889
890
            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:
891
892
            >>> import tfields
            >>> import sympy
893
            >>> x, y, z = sympy.symbols('x y z')
894
895
896
897
898
899
900
            >>> 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
901
902

            combinations of cuts
903
904
            >>> p.cut((x > 0) & (z < 0)).equal([[1, 2, -6], [1, 0, -1]])
            True
905
906
907
908
909
910
911

        Returns:
            copy of self with cut applied

        """
        if len(self) == 0:
            return self.copy()
912
        mask = self.getMask(cutExpression, coordSys=coordSys or self.coordSys)
913
914
915
916
        mask.astype(bool)
        inst = self[mask].copy()
        return inst

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

        """
Daniel Böckenhoff's avatar
Daniel Böckenhoff committed
937
938
939
940
        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)
941

Daniel Böckenhoff's avatar
Daniel Böckenhoff committed
942
    def minDistances(self, other=None, **kwargs):
943
        """
Daniel Böckenhoff's avatar
Daniel Böckenhoff committed
944
945
946
947
948
949
950
951
        Args:
            other(array or None)
            **kwargs:
                memory_saving (bool): for very large array comparisons
                    default False
                ... rest is forwarded to sp.spatial.distance.cdist


952
        Examples:
953
954
            >>> import tfields
            >>> import numpy as np
955
956
957
958
959
            >>> p = tfields.Tensors.grid((0, 2, 3),
            ...                          (0, 2, 3),
            ...                          (0, 0, 1))
            >>> p[4,2] = 1
            >>> dMin = p.minDistances()
960
961
962
963
            >>> expected = [1] * 9
            >>> expected[4] = np.sqrt(2)
            >>> np.array_equal(dMin, expected)
            True
964

Daniel Böckenhoff's avatar
Daniel Böckenhoff committed
965
            >>> dMin2 = p.minDistances(memory_saving=True)
966
967
968
969
            >>> bool((dMin2 == dMin).all())
            True

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

Daniel Böckenhoff's avatar
Daniel Böckenhoff committed
972
        if other is None:
973
            other = self
Daniel Böckenhoff's avatar
Daniel Böckenhoff committed
974
975
        else:
            raise NotImplementedError("Should be easy but make shure not to remove diagonal")
976
977

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

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