mesh3D.py 43.3 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#!/usr/bin/env
# encoding: utf-8
"""
Author:     Daniel Boeckenhoff
Mail:       daniel.boeckenhoff@ipp.mpg.de

part of tfields library
"""
import numpy as np
import os
import sympy
import warnings
import tfields
import ioTools
import mplTools
import decoTools
import pyTools
import symTools
from sympy.abc import y, z
from scipy.spatial import ConvexHull
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import loggingTools
import cuttingTree

logger = loggingTools.Logger(__name__)


29
30
31
32
33
34
35
36
37
38
def scalars_to_fields(scalars):
    scalars = np.array(scalars)
    if len(scalars.shape) == 1:
        return [tfields.Tensors(scalars)]
    return [tfields.Tensors(fs) for fs in scalars]

def fields_to_scalars(fields):
    return np.array(fields)

def faces_to_maps(faces, *fields):
39
    return [tfields.TensorFields(faces, *fields, dtype=int, dim=3)]
40
41

def maps_to_faces(maps):
42
43
44
45
46
    if len(maps) == 0:
        return np.array([])
    elif len(maps) > 1:
        raise NotImplementedError("Multiple maps")
    return np.array(maps[0])
47
48


49
50
51
52
53
class Mesh3D(tfields.TensorMaps):
    # pylint: disable=R0904
    """
    Points3D child used as vertices combined with faces to build a geometrical mesh of triangles
    Examples:
54
55
        >>> import tfields
        >>> import numpy as np
56
        >>> m = tfields.Mesh3D([[1,2,3], [3,3,3], [0,0,0], [5,6,7]], faces=[[0, 1, 2], [1, 2, 3]])
57
58
59
60
61
        >>> m.equal([[1, 2, 3],
        ...          [3, 3, 3],
        ...          [0, 0, 0],
        ...          [5, 6, 7]])
        True
62
        >>> np.array_equal(m.faces, [[0, 1, 2], [1, 2, 3]])
63
        True
64
65

        conversion to points only
66
67
68
69
70
        >>> tfields.Points3D(m).equal([[1, 2, 3],
        ...                            [3, 3, 3],
        ...                            [0, 0, 0],
        ...                            [5, 6, 7]])
        True
71
72
73
74
75
76

        Empty instances
        >>> m = tfields.Mesh3D([]);

        going from Mesh3D to Triangles3D instance is easy and will be cached.
        >>> m = tfields.Mesh3D([[1,0,0], [0,1,0], [0,0,0]], faces=[[0, 1, 2]]);
77
78
79
        >>> assert m.triangles.equal(tfields.Triangles3D([[ 1.,  0.,  0.],
        ...                                               [ 0.,  1.,  0.],
        ...                                               [ 0.,  0.,  0.]]))
80
81

        a list of scalars is assigned to each face
82
83
84
        >>> mScalar = tfields.Mesh3D([[1,0,0], [0,1,0], [0,0,0]], faces=[[0, 1, 2]], faceScalars=[.5]);
        >>> np.array_equal(mScalar.faceScalars, [[ 0.5]])
        True
85
86

        adding together two meshes:
87
88
89
90
91
92
93
94
95
96
        >>> m2 = tfields.Mesh3D([[1,0,0],[2,0,0],[0,3,0]],
        ...                     faces=[[0,1,2]], faceScalars=[.7])
        >>> msum = tfields.Mesh3D.merged(mScalar, m2)
        >>> msum.equal([[ 1.,  0.,  0.],
        ...             [ 0.,  1.,  0.],
        ...             [ 0.,  0.,  0.],
        ...             [ 1.,  0.,  0.],
        ...             [ 2.,  0.,  0.],
        ...             [ 0.,  3.,  0.]])
        True
97
        >>> assert np.array_equal(msum.faces, [[0, 1, 2], [3, 4, 5]])
98
99
100
101

        Saving and reading
        >>> from tempfile import NamedTemporaryFile
        >>> outFile = NamedTemporaryFile(suffix='.npz')
102
        >>> m.save(outFile.name)
103
        >>> _ = outFile.seek(0)
104
        >>> m1 = tfields.Mesh3D.load(outFile.name)
105
106
107
108
109
110
111
112
113
        >>> bool(np.all(m == m1))
        True
        >>> m1.faces
        array([[0, 1, 2]])

    """
    def __new__(cls, tensors, **kwargs):
        if not issubclass(type(tensors), Mesh3D):
            kwargs['dim'] = 3
114
        fields = kwargs.pop('fields', [])
115
116
117
        faces = kwargs.pop('faces', None)
        faceScalars = kwargs.pop('faceScalars', [])
        maps = kwargs.pop('maps', None)
118
        if maps is not None and faces is not None:
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
            raise ValueError("Conflicting options maps and faces")
        if maps is not None:
            kwargs['maps'] = maps
        if faceScalars:
            map_fields = scalars_to_fields(faceScalars)
        else:
            map_fields = []
        if faces is not None:
            kwargs['maps'] = faces_to_maps(faces,
                                           *map_fields)
        obj = super(Mesh3D, cls).__new__(cls, tensors, *fields, **kwargs)
        if len(obj.maps) > 1:
            raise ValueError("Mesh3D only allows one map")
        if obj.maps and obj.maps[0].dim != 3:
            raise ValueError("Face dimension should be 3")
        return obj

    @property
    def faces(self):
        return maps_to_faces(self.maps)

    @faces.setter
    def faces(self, faces):
        self.maps = faces_to_maps(faces)

    @property
    def faceScalars(self):
        return fields_to_scalars(self.maps[0].fields)

    @faceScalars.setter
149
150
    def faceScalars(self, scalars):
        self.maps[0].fields = scalars_to_fields(scalars)
151
152
153
154
155
156
157
158
159

    @decoTools.cached_property()
    def triangles(self):
        """
        with the decorator, this should be handled like an attribute though it is a function

        """
        if self.faces.size == 0:
            return tfields.Triangles3D([])
160
161
162
163
        tris = tfields.Tensors.merged(*[self[mp.flatten()] for mp in self.maps])
        map_fields = [mp.fields for mp in self.maps]
        fields = [tfields.Tensors.merged(*fields) for fields in zip(*map_fields)]
        return tfields.Triangles3D(tris, *fields)
164
165
166
167
168

    @decoTools.cached_property()
    def planes(self):
        if self.faces.size == 0:
            return tfields.Planes3D([])
169
        return tfields.Planes3D(self.getCentroids(), self.triangles.norms())
170

171
    def nfaces(self):
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
197
198
199
200
201
202
203
204
        return self.faces.shape[0]

    def toOneSegment(self, mirrorZ=True):
        """
        Map the points to the first segment and mirror to positive z
        if mirrorZOption is True. Special w7x method
        Examples:
            Build a mesh in three segments
            >>> scalars = np.array([[1,2], [3,4], [5,6], [7,8]], dtype=float)
            >>> m = tfields.Mesh3D([[6,-1,1], [6,0,1], [6,1,1],
            ...                     [6,-1,0.5], [6,0,0.5], [6,1,0.5]],
            ...                    [[0, 3, 4], [0, 1, 4], [1,4,5], [1,2,5]],
            ...                    faceScalars=scalars)
            >>> c = m.copy()
            >>> c.coordinateTransform(c.CYLINDER)
            >>> c[:, 1] *= -1
            >>> c[:, 2] *= -1

            >>> m = tfields.Mesh3D([m, c])
            >>> m2 = m.copy()
            >>> m2.toSegment(1)
            >>> m3 = m.copy()
            >>> m3.toSegment(2)
            >>> mAll = tfields.Mesh3D([m, m2, m3])
            >>> mAll.toOneSegment()
            >>> bool((mAll.faceScalars == scalars * 6).all())
            True

        """
        with self.tempCoordSys(self.CYLINDER):
            dropCut = (-2 * np.pi / 10 < y) & (y < 2 * np.pi / 10)
            if mirrorZ:
                dropCut = dropCut & (z > 0)
205
            dropCutMask = self.evalf(dropCut)
206
207
208
209
210
211
            faceKeepMask = self.getFaceMask(dropCutMask)
            excludedMesh = self.copy()
            self.removeFaces(~faceKeepMask)
            excludedMesh.removeFaces(faceKeepMask)
            # remove 0 faces to be faster
            from sympy.abc import s
212
213
            zeroMask = tfields.evalf(excludedMesh.faceScalars,
                                       expression=(s == 0),
214
215
216
217
218
219
220
221
222
223
224
                                       coords=[s] * excludedMesh.getScalarDepth())
            excludedMesh.removeFaces(zeroMask)

            # to one segment
            super(Mesh3D, self).toOneSegment(mirrorZ=mirrorZ)
            centroidSF = tfields.ScalarField3D(excludedMesh.getCentroids(),
                                               excludedMesh.faceScalars)
            centroidSF.toOneSegment(mirrorZ=mirrorZ)

        self.stackScalars(centroidSF)

225
    def in_faces(self, points, delta, assign_multiple=False):
226
227
228
        """
        Check whether points lie within triangles with Barycentric Technique
        """
229
230
        masks = self.triangles.in_triangles(points, delta,
                                            assign_multiple=assign_multiple)
231
232
        return masks

233
    def cutScalars(self, expression, coords=None,
234
235
236
237
                   replaceValue=np.nan, scalarIndex=None, inplace=False):
        """
        Set a threshold to the scalars.
        Args:
238
            expression (sympy cut expression or list of those):
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
                threshold(sympy cut expression): cut scalars globaly
                threshold(list of sympy cut expressions): set on threshold for every scalar array
        Examples:
            >>> m = tfields.Mesh3D([[0,0,0], [1,0,0], [0,1,0], [0,0,1]],
            ...            faces=[[0,1,2], [0,1,3]],
            ...            faceScalars=[[1, 1], [2, 2]])

            Cuting all scalars at once
            >>> from sympy.abc import s
            >>> m.cutScalars(s <= 1., replaceValue=0.).faceScalars
            array([[ 0.,  0.],
                   [ 2.,  2.]])

            Cutting scalars different:
            >>> m.cutScalars([s <= 1, s >= 2], replaceValue=0.).faceScalars
            array([[ 0.,  1.],
                   [ 2.,  0.]])

            Cuttin one special scalar Array only
            >>> m.cutScalars(s <= 1, replaceValue=0., scalarIndex=1).faceScalars
            array([[ 1.,  0.],
                   [ 2.,  2.]])

            Using a list of cut expressions to cut every scalar index different

        """
        if inplace:
            inst = self
        else:
            inst = self.copy()

270
        if isinstance(expression, list):
271
272
            if scalarIndex is not None:
                raise ValueError("scalarIndex must be None, "
273
274
275
276
                                 "if expression is list of expressions")
            if not len(expression) == inst.getScalarDepth():
                raise ValueError("lenght of expression must meet scalar depth")
            for si, ce in enumerate(expression):
277
278
279
280
281
                inst.cutScalars(ce, coords=coords,
                                replaceValue=replaceValue,
                                scalarIndex=si, inplace=True)
        else:
            if coords is None:
282
                freeSymbols = expression.free_symbols
283
284
285
                if len(freeSymbols) > 1:
                    raise ValueError('coords must be given if multiple variables are given')
                elif len(freeSymbols) == 0:
286
                    raise NotImplementedError("Expressiongs like {expression} "
287
288
289
290
291
292
                                              "are not understood for coords".format(**locals()))
                coords = list(freeSymbols) * inst.getScalarDepth()
            scalarArrays = inst.getScalars()
            if scalarIndex is not None:
                scalarArrays = scalarArrays[:, scalarIndex:scalarIndex + 1]

293
294
                maskBelow = tfields.evalf(scalarArrays,
                                            expression=expression,
295
296
297
298
                                            coords=[coords[scalarIndex]])
                scalarArrays[maskBelow] = replaceValue
                inst.faceScalars[:, scalarIndex:scalarIndex + 1] = scalarArrays
            else:
299
300
                maskBelow = tfields.evalf(scalarArrays,
                                            expression=expression,
301
302
303
304
305
306
307
308
309
310
311
312
313
                                            coords=coords)
                scalarArrays[maskBelow] = replaceValue
                inst.faceScalars = scalarArrays
        if not inplace:
            return inst

    def getFaceMask(self, mask):
        """
        Examples:
            >>> m = tfields.Mesh3D([[1,2,3], [3,3,3], [0,0,0], [5,6,7]],
            ...            [[0, 1, 2], [1, 2, 3]],
            ...            faceScalars=[[1,2,3,4,5], [6,7,8,9,0]])
            >>> from sympy.abc import x,y,z
314
            >>> vertexMask = m.evalf(z < 6)
315
316
317
318
319
320
321
322
            >>> faceMask = m.getFaceMask(vertexMask)
            >>> faceMask
            array([ True, False], dtype=bool)

        Returns:
            mask of faces with all vertices in mask
        """
        faceDeleteMask = np.full((self.faces.shape[0]), False, dtype=bool)
323
        indices = np.array(range(len(self)))
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
        deleteIndices = set(indices[~mask])  # set speeds up everything
        for i, face in enumerate(self.faces):
            for index in face:
                if index in deleteIndices:
                    faceDeleteMask[i] = True
                    break

        return ~faceDeleteMask

    def getRemovedVertices(self, vertexDeleteMask):
        """
        Return copy of self without vertices where vertexDeleteMask is True
        Copy because self is immutable

        Examples:
            >>> m = tfields.Mesh3D([[0,0,0], [1,1,1], [2,2,2], [0,0,0],
            ...                     [3,3,3], [4,4,4], [5,5,5]],
            ...                    [[0, 1, 2], [0, 1, 3], [3, 4, 5], [3, 4, 1],
            ...                     [3, 4, 6]],
            ...                    faceScalars=[[1,2], [3,4], [5,6], [7,8], [9,0]])
            >>> c = m.getRemovedVertices([True, True, True, False, False,
            ...                           False, False])
            >>> c
            Mesh3D([[ 0.,  0.,  0.],
                    [ 3.,  3.,  3.],
                    [ 4.,  4.,  4.],
                    [ 5.,  5.,  5.]])
            >>> c.faces
            array([[0, 1, 2],
                   [0, 1, 3]])
            >>> c.faceScalars
            array([[ 5.,  6.],
                   [ 9.,  0.]])
        
        """
        log = logger.new()
        vertexDeleteMask = np.array(vertexDeleteMask)
        log.verbose("Remove {0} vertices.".format(vertexDeleteMask.sum()))
        # built instance that only contains the vaild points
        inst = self[~vertexDeleteMask].copy()

        moveUpCounter = np.zeros(self.faces.shape, dtype=int)

        # correct faces:
368
        deleteIndices = np.arange(len(self))[vertexDeleteMask]
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
        for p in deleteIndices:
            moveUpCounter[self.faces > p] -= 1

        faceKeepMask = self.getFaceMask(~vertexDeleteMask)
        inst.faces = (self.faces + moveUpCounter)[faceKeepMask]
        inst.faceScalars = self.faceScalars[faceKeepMask]
        return inst

    def cleaned(self, stale=True, duplicates=True):
        """
        Args:
            stale (bool): remove stale vertices
            duplicates (bool): replace duplicate vertices by originals
        Examples:
            >>> m = tfields.Mesh3D([[0,0,0], [1,1,1], [2,2,2], [0,0,0],
            ...                     [3,3,3], [4,4,4], [5,6,7]],
            ...                    [[0, 1, 2], [3, 4, 5]],
            ...                    faceScalars=[[1,2,3,4,5], [6,7,8,9,0]])
            >>> c = m.clean()
            >>> c
            Mesh3D([[ 0.,  0.,  0.],
                    [ 1.,  1.,  1.],
                    [ 2.,  2.,  2.],
                    [ 3.,  3.,  3.],
                    [ 4.,  4.,  4.]])
            >>> c.faces
            array([[0, 1, 2],
                   [0, 3, 4]])

        Returns:
            copy of self without stale vertices and duplicat points
        """
        log = logger.new()
        log.verbose("Cleaning up.")
        # remove stale vertices
        if stale:
            vertexDeleteMask = self.staleVertices()
        else:
            vertexDeleteMask = np.full(self.shape[0], False, dtype=bool)
        # remove duplicates in order to not have any artificial separations
        inst = self
        if duplicates:
            inst = self.copy()
            log.verbose("Finding Duplicates")
            dups = tfields.duplicates(self, axis=0)
            for i, dupi in zip(range(self.shape[0]), dups):
                if dupi != i:
                    log.verbose("Found Duplicate point @ index {0}".format(i))
                    vertexDeleteMask[i] = True
                    # redirect faces
                    log.verbose("Run trough all faces to let it point to the"
                                "original")
421
                    for f in range(self.nfaces()):
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
                        if i in self.faces[f]:
                            index = tfields.index(self.faces[f], i)
                            inst.faces[f][index] = dupi

        return inst.getRemovedVertices(vertexDeleteMask)

    def clean(self, *args, **kwargs):
        """
        Deprecated
        """
        warnings.warn("Name clean is deprecated. take cleaned instead", DeprecationWarning)
        return self.cleaned(*args, **kwargs)

    def getScalarMap(self, mask):
        """
        Return copy of self without vertices where mask is True
        Copy because self is immutable
        """
        # built instance that only contains the vaild points
        faceKeepMask = self.getFaceMask(mask)
442
        scalarMap = np.arange(self.nfaces())[faceKeepMask]
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
        return scalarMap

    def removeFaces(self, faceDeleteMask):
        """
        Remove faces where faceDeleteMask is True
        Examples:
            >>> m = tfields.Mesh3D([[1,2,3], [3,3,3], [0,0,0], [5,6,7]],
            ...            [[0, 1, 2], [1, 2, 3]],
            ...            faceScalars=[[1,2], [6,7]])
            >>> m.removeFaces([True, False])
            >>> m.faces
            array([[1, 2, 3]])

        """
        faceDeleteMask = np.array(faceDeleteMask, dtype=bool)
        self.faces = self.faces[~faceDeleteMask]
        self.faceScalars = self.faceScalars[~faceDeleteMask]

    def keepFaces(self, faceMask=None, faces=None, faceIndices=None):
        """
        Inverse method like removeFaces
        Args:
            faceMask (np.array):
            faces (list of list of int)
            faceIndices (list of int)
        """
        if faces is None:
            faces = []
        if faceIndices is None:
            faceIndices = []
        if faceMask is None:
            faceMask = np.full(self.faces.shape[0], False, dtype=bool)

        for i, face in enumerate(self.faces):
            # np. version of if face in faces:
            if any((face == f).all() for f in faces):
                faceIndices.append(i)

        for ind in faceIndices:
            faceMask[ind] = True

        self.removeFaces(~faceMask)

    def staleVertices(self):
        """
        Returns:
            Mask for all vertices that are stale i.e. are not refered by faces
        """
491
        staleMask = np.full(len(self), False, dtype=bool)
492
        used = set(self.faces.flatten())
493
        for i in range(len(self)):
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
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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
            if i not in used:
                staleMask[i] = True
        return staleMask

    def getFaces(self, vertex=None):
        """
        Args:
            vertex (None / int / array of length 3)
        """
        if vertex is None:
            return self.faces
        if isinstance(vertex, int):
            vertex = self[vertex]
        if not (isinstance(vertex, list) or isinstance(vertex, np.ndarray)):
            raise TypeError("Vertex has wrong type {0}".format(type(vertex)))
        index = tfields.index(self, vertex, axis=0)
        faces = []
        for face in self.faces:
            if index in face:
                faces.append(face)
        return faces

    def _inputToFaceIndices(self, arg):
        """
        convert an input to a faceIndices list
        Returns:
            list
        """
        arg = np.array(arg)
        if arg.dtype == bool:
            # mask
            return np.arange(self.faces.shape[0])[arg]
        if len(arg.shape) > 1:
            # face
            raise NotImplementedError()
        else:
            return arg

    def _inputToFaceMask(self, arg):
        """
        convert an input to a face mask
        Returns:
            np.array, dtype=bool
        """
        arg = np.array(arg)
        if arg.dtype == bool:
            # mask
            return arg
        if len(arg.shape) > 1:
            # face
            raise NotImplementedError()
        else:
            # faceIndices
            tmp = np.full(self.faces.shape[0], False)
            tmp[arg] = True
            return tmp

    def getParts(self, faceGroupIndicesList):
        """
        Args:
            faceGroupIndicesList (list of int)
        """
        log = logger.new()
        faceIndices = range(len(self.faces))
        parts = []
        log.verbose("Run through all {0} groups and partition mesh"
                    .format(len(faceGroupIndicesList)))
        for f, faceGroupIndices in enumerate(faceGroupIndicesList):
            log.verbose("Group {0} / {1}".format(f, len(faceGroupIndicesList)))
            mesh = self.copy()
            # for speed up:
            faceGroupIndices = set(faceGroupIndices)
            faceDeleteMask = [True
                              if i not in faceGroupIndices
                              else False
                              for i in faceIndices]
            mesh.removeFaces(faceDeleteMask)
            mesh = mesh.getRemovedVertices(mesh.staleVertices())
            parts.append(mesh)
        return parts

    def getLinkedFaces(self, skipFaces=None):
        """
        Retrieve the faceIndices that are connected grouped together
        Args:
            skipFaces: faceSelector (mask, faces, faceIndices)
        Returns:
            list of list of int: groups of face indices that are linked

        Examples:
            >>> import tfields
            >>> a = tfields.Mesh3D([[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0]],
            ...                    faces=[[0, 1, 2], [0, 2, 3]])
            >>> b = a.copy()

            >>> b[:, 0] += 2
            >>> m = tfields.Mesh3D([a, b])
            >>> groupIndices = m.getLinkedFaces()
            >>> parts = m.getParts(groupIndices)
            >>> aa, ba = parts
            >>> bool((aa.faces == a.faces).all())
            True
            >>> bool((ba.faces == b.faces).all())
            True
            >>> bool((aa == a).all())
            True
            >>> bool((ba == b).all())
            True

        """
        faces = self.faces
        if skipFaces is not None:
            mask = ~self._inputToFaceMask(skipFaces)
            faces = faces[mask]
        faceGroupIndicesList = pyTools.setTools.disjointGroupIndices(faces)
        if skipFaces is not None:
            faceIndices = np.arange(self.faces.shape[0])
            faceGroupIndicesList = [faceIndices[mask][group]
                                    for group in faceGroupIndicesList]
        return faceGroupIndicesList

    def getRegion(self, seedFace, **kwargs):
        """
        Grow a region from the seedFace until breaking criterion is reached
        Breaking criterion is specified in kwargs
        Args:
            seedFace (faceMask or faces or faceIndices):
            **kwargs: keys:
                    maxAngle: breaking criterion specified for the normal
                        vectors not to deviate from neighbours more than maxAngle
        Examples:
            Get only one side of a cube:
            >>> import tfields
            >>> import numpy as np
            >>> base = [np.linspace(0, 1, 10),
            ...         np.linspace(0, 1, 10),
            ...         np.linspace(0, 1, 10)]
            >>> mesh = tfields.Mesh3D.createMeshGrid(*base).cleaned()

            Some small mistake occured in the test. Check that.
            # Select the first face as a seedFace
            # >>> faceGroups = mesh.getRegion([0], maxAngle=np.pi * 2 / 8)
            # >>> parts = mesh.getParts(faceGroups)

            # Should only return one group. does not yet -> TODO!
            # >>> len(parts) == 1

        """
        log = logger.new()
        if not kwargs:
            log.warning("No boundaries specified")
            return np.arange(self.faces.shape[0])

        faceIndices = list(self._inputToFaceIndices(seedFace))

        # get break condition from kwargs
        maxAngle = kwargs.pop('maxAngle', None)

652
        norms = self.triangles.norms()
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
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
        meanVector = np.mean(norms[faceIndices], axis=0)

        excludedFaceIndices = set()
        length = 0
        while len(faceIndices) > length:
            length = len(faceIndices)
            for f, face in enumerate(self.faces):
                vertexIndices = list(set(pyTools.flatten(self.faces[faceIndices])))
                for index in vertexIndices:
                    if index not in face:
                        continue
                    if f in faceIndices:
                        continue
                    if f in excludedFaceIndices:
                        continue
                    norm = norms[f]
                    angle = np.arccos(np.einsum("...j,...j", meanVector, norm))
                    if abs(angle) > maxAngle:
                        excludedFaceIndices.add(f)
                        continue
                    log.verbose("Found new neighbour at face index "
                                "{f}".format(**locals()))
                    faceIndices.append(f)
            if not len(faceIndices) > length:
                log.info("Found no neighbours")
        return faceIndices

    def getSides(self, mainAxes=None, deviation=2 * np.pi / 8):
        """
        Grouping together face indices that have normal vectors in the
        limits of +- deviation or +- pi + deviation.
        Examples:
            Get only one side of a cube:
            >>> import tfields
            >>> import numpy as np
            >>> base = [np.linspace(0, 1, 2),
            ...         np.linspace(0, 1, 4),
            ...         np.linspace(0, 1, 4)]
            >>> mesh = tfields.Mesh3D.createMeshGrid(*base).cleaned()

            Select the first face as a seedFace
            >>> faceGroups = mesh.getSides([[1,0,0],[0,1,0],[0,0,1]])
            >>> parts = mesh.getParts(faceGroups)
            >>> len(parts) == 6
            True

            Faces that have inconsistant norm vector direction are no problem
            To show that, we invert the normal vector of one
            face in the middle of the cube
            >>> mesh.faces[8] = [5, 9, 6]
            >>> faceGroups2 = mesh.getSides([[1,0,0],[0,1,0],[0,0,1]])
            >>> parts2 = mesh.getParts(faceGroups2)
            >>> len(parts2) == 6
            True

        """
        if mainAxes is None:
            axes = self.getMainAxes()
        else:
            axes = tfields.Points3D(mainAxes)
        n = np.apply_along_axis(np.linalg.norm, 0, axes.T).reshape(-1, 1)
        axes = axes / n

716
        norms = self.triangles.norms()
717
718
719
720
721
722
723
724
725
726
727
        norms = tfields.Points3D(norms)

        faceGroupIndices = []
        for vector in axes:
            angles = np.arccos(np.einsum("...ij,...j", norms, vector))
            mask = np.logical_or(abs(angles) < deviation,
                                 abs(angles - np.pi) < deviation)
            tmp = self.getLinkedFaces(skipFaces=~mask)
            faceGroupIndices += tmp
        return faceGroupIndices

728
    def template(self, sub_mesh, delta=1e-9):
729
730
        """
        Returns:
731
732
            Mesh3D: template (see cut), can be used as template to retrieve
                sub_mesh from self instance
733
734
735
736
737
        Examples:
            >>> m = tfields.Mesh3D([[0,0,0], [1,0,0], [1,1,0], [0,1,0], [0,2,0], [1,2,0]],
            ...            faces=[[0,1,2],[2,3,0],[3,2,5],[5,4,3]],
            ...            faceScalars=[[1],[2],[3],[4]])
            >>> from sympy.abc import y
738
739
            >>> mCut, mapMesh = m.cut(y < 1.5, at_intersection='split')
            >>> mm = m.template(mCut)
740
741
742
743
744
745
746
747
748
749
            >>> bool((mm == mapMesh).all())
            True
            >>> bool((mm.faceScalars == mapMesh.faceScalars).all())
            True
            >>> bool((mm.faces == mapMesh.faces).all())
            True

        """
        # log = logger.new()
        faceIndices = np.arange(self.faces.shape[0])
750
        cents = tfields.Points3D(sub_mesh.getCentroids())
751
752
753
754
755
756
757
758
759
760
761
762
763
764
        scalars = []
        # nCents = cents.shape[0]
        # for i in range(nCents):
        #     faceMask = self.pointsInMesh(cents[i: i + 1], delta=delta)[0]
        #     if True not in faceMask:
        #         log.warning("No point face was assigned to this. I will retry.")
        #         faceMask = self.pointsInMesh(cents[i: i + 1], delta=delta * 100)[0]
        #         if True not in faceMask:
        #             raise ValueError()
        #     else:
        #         log.info("Centroid {i} / {nCents}".format(**locals()))
        #     scalars.append(faceIndices[faceMask])
        mask = self.pointsInMesh(cents, delta=delta)
        scalars = [faceIndices[faceMask] for faceMask in mask]
765
        inst = sub_mesh.copy()
766
767
768
769
770
771
772
773
774
775
776
777
778
779
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
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
        inst.setScalarArray(0, scalars)
        return inst

    def _distFromPlane(self, point, plane):
        return plane['normal'].dot(point) + plane['d']

    def _getSegmentPlaneIntersection(self, p0, p1, plane):
        distance0 = self._distFromPlane(p0, plane)
        distance1 = self._distFromPlane(p1, plane)
        p0OnPlane = abs(distance0) < np.finfo(float).eps
        p1OnPlane = abs(distance1) < np.finfo(float).eps
        outPoints = []
        direction = 0
        if p0OnPlane:
            outPoints.append(p0)

        if p1OnPlane:
            outPoints.append(p1)
        # remove duplicate points
        if len(outPoints) > 1:
            outPoints = tfields.Points3D(np.unique(outPoints, axis=0))
        if p0OnPlane and p1OnPlane:
            return outPoints, direction

        if distance0 * distance1 > np.finfo(float).eps:
            return outPoints, direction

        direction = np.sign(distance0)
        if abs(distance0) < np.finfo(float).eps:
            return outPoints, direction
        elif abs(distance1) < np.finfo(float).eps:
            return outPoints, direction
        if abs(distance0 - distance1) > np.finfo(float).eps:
            t = distance0 / (distance0 - distance1)
        else:
            return outPoints, direction

        outPoints.append(p0 + t * (p1 - p0))
        # remove duplicate points
        if len(outPoints) > 1:
            outPoints = tfields.Points3D(np.unique(outPoints, axis=0))
        return outPoints, direction

    def _intersect(self, triangle, plane, facePointsRejected):
        nTrue = facePointsRejected.count(True)
        lonelyBool = True if nTrue == 1 else False
        index = facePointsRejected.index(lonelyBool)
        s0, d0 = self._getSegmentPlaneIntersection(triangle[0], triangle[1], plane)
        s1, d1 = self._getSegmentPlaneIntersection(triangle[1], triangle[2], plane)
        s2, d2 = self._getSegmentPlaneIntersection(triangle[2], triangle[0], plane)

        singlePoint = triangle[index]
        couplePoints = [triangle[j] for j in range(3)
                        if not facePointsRejected[j] == lonelyBool]

        # TODO handle special cases. For now triangles with at least two points on plane are excluded
        newPoints = None
        faces = None

        if len(s0) == 2:
            # both points on plane
            return None, None
        if len(s1) == 2:
            # both points on plane
            return None, None
        if len(s2) == 2:
            # both points on plane
            return None, None
        if lonelyBool:
            # one new triangle
            if len(s0) == 1 and len(s1) == 1:
                newPoints = np.array([couplePoints[0], couplePoints[1], s0[0], s1[0]])
                faces = np.array([[0, 2, 1], [1, 2, 3]])
            elif len(s1) == 1 and len(s2) == 1:
                newPoints = np.array([couplePoints[0], couplePoints[1], s1[0], s2[0]])
                faces = np.array([[0, 1, 2], [0, 2, 3]])
            elif len(s0) == 1 and len(s2) == 1:
                newPoints = np.array([couplePoints[0], couplePoints[1], s0[0], s2[0]])
                faces = np.array([[0, 1, 2], [1, 3, 2]])
            else:
                return None, None

        else:
            # two new triangles
            if len(s0) == 1 and len(s1) == 1:
                newPoints = np.array([singlePoint, s0[0], s1[0]])
                faces = np.array([[0, 2, 1]])
            elif len(s1) == 1 and len(s2) == 1:
                newPoints = np.array([singlePoint, s1[0], s2[0]])
                faces = np.array([[0, 2, 1]])
            elif len(s0) == 1 and len(s2) == 1:
                newPoints = np.array([singlePoint, s0[0], s2[0]])
                faces = np.array([[0, 1, 2]])
            else:
                return None, None
        return newPoints, faces

863
    def _cut_sympy(self, expression, at_intersection="remove"):
864
865
866
        """
        Partition the mesh with the cuts given
        Args:
867
868
            expression (sympy logical expression): see Tensors.cut 
            at_intersection (str): option switch for expression (see
869
870
871
872
873
874
875
                tfields.Mesh3D.cut)
        Examples:
            Cut away the first face / select the last face only
            >>> m = tfields.Mesh3D([[1,2,3], [3,3,3], [0,0,0], [5,6,7]],
            ...            faces=[[0, 1, 2], [1, 2, 3]],
            ...            faceScalars=[[1,2], [6,7]])
            >>> mNew = tfields.Mesh3D([[3,3,3], [0,0,0], [5,6,7]], [[0, 1, 2]], faceScalars=[[1]])
876
            >>> mCut = m.cut(mNew)
877
878
879
880
881
882
883
884
885
            >>> mCut.faceScalars
            array([[ 6.,  7.]])

            Cut with condition will return the manual/instruction on how to
            conduct the cut fast (mapMesh)
            >>> from sympy.abc import y
            >>> m = tfields.Mesh3D([[0,0,0], [1,0,0], [1,1,0], [0,1,0], [0,2,0], [1,2,0]],
            ...            faces=[[0,1,2],[2,3,0],[3,2,5],[5,4,3]],
            ...            faceScalars=[[1],[2],[3],[4]])
886
887
            >>> mCut, mapMesh = m.cut(y < 1.5, at_intersection='split',
            ...                       return_template=True)
888
889
890
891
892
            >>> mCut.faceScalars.T
            array([[ 1.,  2.,  3.,  3.,  4.]])

            Applying the mapMesh results in the same result as applying the cut
            with the condition
893
            >>> mCut2 = m.cut(mapMesh)
894
895
896
897
898
899
            >>> bool((mCut == mCut2).all())
            True
            >>> bool((mCut.faceScalars == mCut2.faceScalars).all())
            True

        """
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
        eps = 0.000000001
        # direct return if self is empty
        if len(self) == 0:
            return self.copy(), self.copy()

        # mask for points that do not fulfill the cut expression
        mask = self.evalf(expression, coordSys=coordSys)
        # remove the points
        inst = self.getRemovedVertices(~mask)
        scalarMap = self.getScalarMap(mask)
        scalarMap = scalarMap.reshape((-1, 1)).astype(float)

        if not any(~mask):
            # no faces have been removed.
            return inst, Mesh3D([inst], faceScalars=scalarMap)

        if all(~mask):
            # all faces have been removed)
            return inst, inst.copy()

        # add points and faces intersecting with the plane
        if at_intersection == 'split' or at_intersection == 'splitRough':
            expressionParts = symTools.getExpressionParts(expression)
            if len(expressionParts) > 1:
                onEdgeMesh = self.copy()
                if at_intersection == 'splitRough':
                    """
                    the following is, to speed up the process. Problem is, that
                    triangles can exist, where all points lie outside the cut,
                    but part of the area
                    still overlaps with the cut.
                    These are at the intersection line between two cuts.
                    """
                    faceIntersMask = np.full((self.faces.shape[0]), False, dtype=bool)
                    for i, face in enumerate(self.faces):
                        facePointsRejected = [-mask[f] for f in face]
                        faceOnEdge = any(facePointsRejected) and not all(facePointsRejected)
                        if faceOnEdge:
                            faceIntersMask[i] = True
                    onEdgeMesh.removeFaces(-faceIntersMask)

                for exprPart in expressionParts:
                    onEdgeMesh = onEdgeMesh.cut(exprPart, at_intersection='split')
                newMesh = onEdgeMesh
            elif len(expressionParts) == 1:

                points = [sympy.symbols('x0, y0, z0'),
                          sympy.symbols('x1, y1, z1'),
                          sympy.symbols('x2, y2, z2')]
                fpr = sympy.symbols('fpr2, fpr1, fpr2')
                planeSympy = symTools.getPlane(expression)
                n = np.array(planeSympy.normal_vector).astype(float)
                d = -n.dot(np.array(planeSympy.p1).astype(float))
                plane = {'normal': n, 'd': d}

                norm_vectors = self.triangles.norms()
                newPoints = np.empty((0, 3))
                newFaces = np.empty((0, 3))
                newFaceScalars = []
                newNormVectors = []
                newScalarMap = []
                nNew = 0
                for i, face in enumerate(self.faces):
                    """
                    facePointsRejected is a mask for each face that is True, where
                    a Point is on the rejected side of the plane
                    """
                    facePointsRejected = [~mask[f] for f in face]
                    faceOnEdge = any(facePointsRejected) and not all(facePointsRejected)
                    if faceOnEdge:
970
                        """
971
972
973
                        define the two lines that are intersecting the plane:
                        one point will be alone on one side of the cutting plane (singlePoint)
                        the other two will be on ther other side (couplePoints)
974
                        """
975
976
977
978
979
                        nTrue = facePointsRejected.count(True)
                        # the bool that occures on
                        lonelyBool = True if nTrue == 1 else False

                        triangle_points = [self[f] for f in face]
980
                        """
981
                        Add the intersection points and faces
982
                        """
983
984
985
986
987
988
989
990
991
992
993
994
995
                        # tick = time()
                        if lonelyBool:
                            # singlePoint on cut away side
                            newP, newF = self._intersect(triangle_points, plane, facePointsRejected)
                            if newP is not None:
                                newP = np.array(newP)
                                np.place(newP, np.logical_and(0 < newP, newP <= eps), 0.0)
                                newPoints = np.concatenate((newPoints, newP))
                                newFaces = np.concatenate((newFaces, newF + nNew))
                                newFaceScalars.extend([self.faceScalars[i]] * 2)
                                newNormVectors.extend([norm_vectors[i]] * 2)
                                newScalarMap.extend([i] * 2)
                                nNew += 4
996
                            else:
997
998
999
1000
                                pass
                        else:
                            # singlePoint on keep side
                            newP, newF = self._intersect(triangle_points, plane, facePointsRejected)