mesh3D.py 43.5 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
#!/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
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__)


28
29
30
31
32
33
34
35
36
37
38
39
40
def _dist_from_plane(point, plane):
    return plane['normal'].dot(point) + plane['d']


def _segment_plane_intersection(p0, p1, plane):
    """
    Returns:
        points, direction
    """
    distance0 = _dist_from_plane(p0, plane)
    distance1 = _dist_from_plane(p1, plane)
    p0OnPlane = abs(distance0) < np.finfo(float).eps
    p1OnPlane = abs(distance1) < np.finfo(float).eps
41
    points = []
42
43
    direction = 0
    if p0OnPlane:
44
        points.append(p0)
45
46

    if p1OnPlane:
47
        points.append(p1)
48
    # remove duplicate points
49
50
    if len(points) > 1:
        points = np.unique(points, axis=0)
51
    if p0OnPlane and p1OnPlane:
52
        return points, direction
53
54

    if distance0 * distance1 > np.finfo(float).eps:
55
        return points, direction
56
57
58

    direction = np.sign(distance0)
    if abs(distance0) < np.finfo(float).eps:
59
        return points, direction
60
    elif abs(distance1) < np.finfo(float).eps:
61
        return points, direction
62
63
64
    if abs(distance0 - distance1) > np.finfo(float).eps:
        t = distance0 / (distance0 - distance1)
    else:
65
        return points, direction
66

67
    points.append(p0 + t * (p1 - p0))
68
    # remove duplicate points
69
70
71
    if len(points) > 1:
        points = np.unique(points, axis=0)
    return points, direction
72
73
74
75
76
77
78


def _intersect(triangle, plane, vertices_rejected):
    """
    Intersect a triangle with a plane. Give the info, which side of the
    triangle is rejected by passing the mask vertices_rejected
    Returns:
79
80
81
82
83
84
85
86
87
        list of list. The inner list is of length 3 and refers to the points of
        new triangles. The reference is done with varying types:
            int: reference to triangle index
            complex: reference to duplicate point. This only happens in case
                two triangles are returned. Then only in the second triangle
            iterable: new vertex

    TODO:
        align norm vectors with previous face
88
89
90
91
92
93
94
95
    """
    nTrue = vertices_rejected.count(True)
    lonely_bool = True if nTrue == 1 else False
    index = vertices_rejected.index(lonely_bool)
    s0, d0 = _segment_plane_intersection(triangle[0], triangle[1], plane)
    s1, d1 = _segment_plane_intersection(triangle[1], triangle[2], plane)
    s2, d2 = _segment_plane_intersection(triangle[2], triangle[0], plane)

96
97
98
    single_index = index
    couple_indices = [j for j in range(3)
                      if not vertices_rejected[j] == lonely_bool]
99
100
101
102
103
104

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

    if len(s0) == 2:
        # both points on plane
105
        return new_points
106
107
    if len(s1) == 2:
        # both points on plane
108
        return new_points
109
110
    if len(s2) == 2:
        # both points on plane
111
        return new_points
112
    if lonely_bool:
113
        # two new triangles
114
        if len(s0) == 1 and len(s1) == 1:
115
116
            new_points = [[couple_indices[0], s0[0], couple_indices[1]],
                          [couple_indices[1], complex(1), s1[0]]]
117
        elif len(s1) == 1 and len(s2) == 1:
118
119
            new_points = [[couple_indices[0], couple_indices[1], s1[0]],
                          [couple_indices[0], complex(2), s2[0]]]
120
        elif len(s0) == 1 and len(s2) == 1:
121
122
            new_points = [[couple_indices[0], couple_indices[1], s0[0]],
                          [couple_indices[1], s2[0], complex(2)]]
123
124

    else:
125
        # one new triangle
126
        if len(s0) == 1 and len(s1) == 1:
127
            new_points = [[single_index, s1[0], s0[0]]]
128
        elif len(s1) == 1 and len(s2) == 1:
129
            new_points = [[single_index, s2[0], s1[0]]]
130
        elif len(s0) == 1 and len(s2) == 1:
131
132
            new_points = [[single_index, s0[0], s2[0]]]
    return new_points
133
134


135
136
137
138
139
140
141
142
143
144
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):
145
    return [tfields.TensorFields(faces, *fields, dtype=int, dim=3)]
146

147

148
def maps_to_faces(maps):
149
150
151
152
153
    if len(maps) == 0:
        return np.array([])
    elif len(maps) > 1:
        raise NotImplementedError("Multiple maps")
    return np.array(maps[0])
154
155


156
157
158
159
160
class Mesh3D(tfields.TensorMaps):
    # pylint: disable=R0904
    """
    Points3D child used as vertices combined with faces to build a geometrical mesh of triangles
    Examples:
161
162
        >>> import tfields
        >>> import numpy as np
163
        >>> m = tfields.Mesh3D([[1,2,3], [3,3,3], [0,0,0], [5,6,7]], faces=[[0, 1, 2], [1, 2, 3]])
164
165
166
167
168
        >>> m.equal([[1, 2, 3],
        ...          [3, 3, 3],
        ...          [0, 0, 0],
        ...          [5, 6, 7]])
        True
169
        >>> np.array_equal(m.faces, [[0, 1, 2], [1, 2, 3]])
170
        True
171
172

        conversion to points only
173
174
175
176
177
        >>> tfields.Points3D(m).equal([[1, 2, 3],
        ...                            [3, 3, 3],
        ...                            [0, 0, 0],
        ...                            [5, 6, 7]])
        True
178
179
180
181
182
183

        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]]);
184
185
186
        >>> assert m.triangles.equal(tfields.Triangles3D([[ 1.,  0.,  0.],
        ...                                               [ 0.,  1.,  0.],
        ...                                               [ 0.,  0.,  0.]]))
187
188

        a list of scalars is assigned to each face
189
190
191
        >>> 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
192
193

        adding together two meshes:
194
195
196
197
198
199
200
201
202
203
        >>> 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
204
        >>> assert np.array_equal(msum.faces, [[0, 1, 2], [3, 4, 5]])
205
206
207
208

        Saving and reading
        >>> from tempfile import NamedTemporaryFile
        >>> outFile = NamedTemporaryFile(suffix='.npz')
209
        >>> m.save(outFile.name)
210
        >>> _ = outFile.seek(0)
211
        >>> m1 = tfields.Mesh3D.load(outFile.name)
212
213
214
215
216
217
        >>> bool(np.all(m == m1))
        True
        >>> m1.faces
        array([[0, 1, 2]])

    """
218
    def __new__(cls, tensors, *fields, **kwargs):
219
220
        if not issubclass(type(tensors), Mesh3D):
            kwargs['dim'] = 3
221
222
223
        faces = kwargs.pop('faces', None)
        faceScalars = kwargs.pop('faceScalars', [])
        maps = kwargs.pop('maps', None)
224
        if maps is not None and faces is not None:
225
226
227
            raise ValueError("Conflicting options maps and faces")
        if maps is not None:
            kwargs['maps'] = maps
228
        if len(faceScalars) > 0:
229
230
231
232
233
234
235
236
237
238
239
240
241
            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

242

243
244
245
    @classmethod
    def plane(cls, *base_vectors, **kwargs):
        vertices = tfields.Tensors.grid(*base_vectors)
246
247
248

        base_vectors = tfields.grid.ensure_complex(*base_vectors)
        base_vectors = tfields.grid.to_base_vectors(*base_vectors)
249
250
251
252
253
254
255
        fix_coord = None
        for coord in range(3):
            if len(base_vectors[coord]) > 1:
                continue
            if len(base_vectors[coord]) == 0:
                continue
            fix_coord = coord
256
257
        if fix_coord is None:
            raise ValueError("Describe a plane with one variable fiexed")
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279

        var_coords = list(range(3))
        var_coords.pop(var_coords.index(fix_coord))

        faces = []
        base0, base1 = base_vectors[var_coords[0]], base_vectors[var_coords[1]]
        for i1 in range(len(base1) - 1):
            for i0 in range(len(base0) - 1):
                idx_top_left = len(base1) * (i0 + 0) + (i1 + 0)
                idx_top_right = len(base1) * (i0 + 0) + (i1 + 1)
                idx_bot_left = len(base1) * (i0 + 1) + (i1 + 0)
                idx_bot_right = len(base1) * (i0 + 1) + (i1 + 1)
                faces.append([idx_top_left, idx_top_right, idx_bot_left])
                faces.append([idx_top_right, idx_bot_left, idx_bot_right])
        inst = cls.__new__(cls, vertices, faces=faces, **kwargs)
        return inst

    @classmethod
    def grid(cls, *base_vectors, **kwargs):
        if not len(base_vectors) == 3:
            raise AttributeError("3 base_vectors vectors required")

280
281
282
        base_vectors = tfields.grid.ensure_complex(*base_vectors)
        base_vectors = tfields.grid.to_base_vectors(*base_vectors)

283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
        indices = [0, -1]
        coords = range(3)
        baseLengthsAbove1 = [len(b) > 1 for b in base_vectors]
        # if one plane is given: rearrange indices and coords
        if not all(baseLengthsAbove1):
            indices = [0]
            for i, b in enumerate(baseLengthsAbove1):
                if not b:
                    coords = [i]
                    break

        base_vectors = list(base_vectors)
        planes = []
        for ind in indices:
            for coord in coords:
                basePart = base_vectors[:]
                basePart[coord] = np.array([base_vectors[coord][ind]],
                                           dtype=float)

                planes.append(cls.plane(*basePart))
        inst = cls.merged(*planes, **kwargs)
        return inst

306
307
308
309
310
311
312
313
314
315
316
317
318
    @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
319
320
    def faceScalars(self, scalars):
        self.maps[0].fields = scalars_to_fields(scalars)
321
322
323
324
325
326
327
328
329

    @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([])
330
331
332
333
        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)
334
335
336
337
338

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

341
    def nfaces(self):
342
343
        return self.faces.shape[0]

344
    def in_faces(self, points, delta, assign_multiple=False):
345
346
347
        """
        Check whether points lie within triangles with Barycentric Technique
        """
348
349
        masks = self.triangles.in_triangles(points, delta,
                                            assign_multiple=assign_multiple)
350
351
        return masks

352
    def cutScalars(self, expression, coords=None,
353
354
355
356
                   replaceValue=np.nan, scalarIndex=None, inplace=False):
        """
        Set a threshold to the scalars.
        Args:
357
            expression (sympy cut expression or list of those):
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
                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()

389
        if isinstance(expression, list):
390
391
            if scalarIndex is not None:
                raise ValueError("scalarIndex must be None, "
392
393
394
395
                                 "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):
396
397
398
399
400
                inst.cutScalars(ce, coords=coords,
                                replaceValue=replaceValue,
                                scalarIndex=si, inplace=True)
        else:
            if coords is None:
401
                freeSymbols = expression.free_symbols
402
403
404
                if len(freeSymbols) > 1:
                    raise ValueError('coords must be given if multiple variables are given')
                elif len(freeSymbols) == 0:
405
                    raise NotImplementedError("Expressiongs like {expression} "
406
407
408
409
410
411
                                              "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]

412
413
                maskBelow = tfields.evalf(scalarArrays,
                                            expression=expression,
414
415
416
417
                                            coords=[coords[scalarIndex]])
                scalarArrays[maskBelow] = replaceValue
                inst.faceScalars[:, scalarIndex:scalarIndex + 1] = scalarArrays
            else:
418
419
                maskBelow = tfields.evalf(scalarArrays,
                                            expression=expression,
420
421
422
423
424
425
426
427
428
429
430
431
432
                                            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
433
            >>> vertexMask = m.evalf(z < 6)
434
435
436
437
438
439
440
441
            >>> 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)
442
        indices = np.array(range(len(self)))
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
491
492
493
494
495
496
497
        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 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
        """
498
        staleMask = np.full(len(self), False, dtype=bool)
499
        used = set(self.faces.flatten())
500
        for i in range(len(self)):
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
            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)
578
            mesh = mesh.cleaned(duplicates=False)
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
            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)]
638
            >>> mesh = tfields.Mesh3D.grid(*base).cleaned()
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658

            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)

659
        norms = self.triangles.norms()
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
        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)]
698
            >>> mesh = tfields.Mesh3D.grid(*base).cleaned()
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722

            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

723
        norms = self.triangles.norms()
724
725
726
727
728
729
730
731
732
733
734
        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

735
    def template(self, sub_mesh, delta=1e-9):
736
737
        """
        Returns:
738
739
            Mesh3D: template (see cut), can be used as template to retrieve
                sub_mesh from self instance
740
741
742
743
744
        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
745
746
            >>> mCut, mapMesh = m.cut(y < 1.5, at_intersection='split')
            >>> mm = m.template(mCut)
747
748
749
750
751
752
753
754
755
            >>> bool((mm == mapMesh).all())
            True
            >>> bool((mm.faceScalars == mapMesh.faceScalars).all())
            True
            >>> bool((mm.faces == mapMesh.faces).all())
            True

        """
        faceIndices = np.arange(self.faces.shape[0])
756
        cents = tfields.Points3D(sub_mesh.getCentroids())
757
758
759
        scalars = []
        mask = self.pointsInMesh(cents, delta=delta)
        scalars = [faceIndices[faceMask] for faceMask in mask]
760
        inst = sub_mesh.copy()
761
762
763
        inst.setScalarArray(0, scalars)
        return inst

764
    def _cut_sympy(self, expression, at_intersection="remove", _in_recursion=False):
765
        """
766
        Partition the mesh with the cuts given and return the template
767
768

        """
769
770
771
772
773
        eps = 0.000000001
        # direct return if self is empty
        if len(self) == 0:
            return self.copy(), self.copy()

774
775
776
777
778
779
780
781
782
783
784
        inst = self.copy()

        '''
        add the indices of the vertices and maps to the fields. They will be
        removed afterwards
        '''
        if not _in_recursion:
            inst.fields.append(tfields.Tensors(np.arange(len(inst))))
            for mp in inst.maps:
                mp.fields.append(tfields.Tensors(np.arange(len(mp))))

785
        # mask for points that do not fulfill the cut expression
786
        mask = inst.evalf(expression)
787
        # remove the points
788
789

        if not any(~mask) or all(~mask):
790
            inst = inst[mask]
791
792
        elif at_intersection == 'split' or at_intersection == 'splitRough':
            '''
793
            add vertices and faces that are at the border of the cuts
794
            '''
795
            expression_parts = tfields.lib.symbolics.split_expression(expression)
796
            if len(expression_parts) > 1:
797
                new_mesh = inst.copy()
798
799
800
801
802
803
804
805
                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.
                    """
806
807
                    faceIntersMask = np.full((inst.faces.shape[0]), False, dtype=bool)
                    for i, face in enumerate(inst.faces):
808
809
                        vertices_rejected = [-mask[f] for f in face]
                        face_on_edge = any(vertices_rejected) and not all(vertices_rejected)
810
                        if face_on_edge:
811
                            faceIntersMask[i] = True
812
                    new_mesh.removeFaces(-faceIntersMask)
813

814
                for exprPart in expression_parts:
815
816
817
                    inst, _ = inst._cut_sympy(exprPart,
                                              at_intersection='split',
                                              _in_recursion=True)
818
            elif len(expression_parts) == 1:
819
                # TODO maps[0] -> smthng like inst.get_map(dim=3)
820
821
822
                points = [sympy.symbols('x0, y0, z0'),
                          sympy.symbols('x1, y1, z1'),
                          sympy.symbols('x2, y2, z2')]
823
                plane_sympy = tfields.lib.symbolics.to_plane(expression)
824
825
826
                norm_sympy = np.array(plane_sympy.normal_vector).astype(float)
                d = -norm_sympy.dot(np.array(plane_sympy.p1).astype(float))
                plane = {'normal': norm_sympy, 'd': d}
827

828
                norm_vectors = inst.triangles.norms()
829
830
                new_points = np.empty((0, 3))
                new_faces = np.empty((0, 3))
831
832
833
834
                new_fields = [tfields.Tensors(np.empty((0,) + field.shape[1:]),
                                              coordSys=field.coordSys)
                              for field in inst.fields]
                new_map_fields = [[] for field in inst.maps[0].fields]
835
                new_norm_vectors = []
836
                newScalarMap = []
837
                n_new = 0
838

839
840
841
842
843
844
845
                vertices = np.array(inst)
                faces = np.array(inst.maps[0])
                fields = [np.array(field) for field in inst.fields]
                faces_fields = [np.array(field) for field in inst.maps[0].fields]

                face_delete_indices = set([])
                for i, face in enumerate(inst.maps[0]):
846
                    """
847
                    vertices_rejected is a mask for each face that is True, where
848
849
                    a Point is on the rejected side of the plane
                    """
850
                    vertices_rejected = [~mask[f] for f in face]
851
852
853
854
855
                    if any(vertices_rejected):
                        # delete face
                        face_delete_indices.add(i)
                    if any(vertices_rejected) and not all(vertices_rejected):
                        # face on edge
856
                        nTrue = vertices_rejected.count(True)
857
                        lonely_bool = True if nTrue == 1 else False
858

859
                        triangle_points = [inst[f] for f in face]
860
                        """
861
                        Add the intersection points and faces
862
                        """
863
864
865
                        newP = _intersect(triangle_points, plane, vertices_rejected)
                        last_idx = len(vertices) - 1
                        for tri_list in newP:
866
                            new_face = []
867
868
869
                            for item in tri_list:
                                if isinstance(item, int):
                                    # reference to old vertex
870
                                    new_face.append(face[item])
871
872
873
                                elif isinstance(item, complex):
                                    # reference to new vertex that has been
                                    # concatenated already
874
                                    new_face.append(last_idx + int(item.imag))
875
876
                                else:
                                    # new vertex
877
                                    new_face.append(len(vertices))
878
879
880
881
882
883
884
                                    vertices = np.append(vertices,
                                                         [map(float, item)],
                                                         axis=0)
                                    fields = [np.append(field,
                                                        np.full((1,) + field.shape[1:], np.nan),
                                                        axis=0)
                                              for field in fields]
885
                            faces = np.append(faces, [new_face], axis=0)
886
                            faces_fields = [np.append(field,
887
                                                      [field[i]],
888
889
890
891
892
                                                      axis=0)
                                            for field in faces_fields]
                            faces_fields[-1][-1] = i

                face_map = tfields.TensorFields(faces, *faces_fields,
893
                                                dtype=int,
894
895
896
897
898
899
900
901
902
903
                                                coordSys=inst.maps[0].coordSys)
                inst = tfields.Mesh3D(vertices,
                                      *fields,
                                      maps=[face_map] + inst.maps[1:],
                                      coordSys=inst.coordSys)
                mask = np.full(len(inst.maps[0]), True, dtype=bool)
                for face_idx in range(len(inst.maps[0])):
                    if face_idx in face_delete_indices:
                        mask[face_idx] = False
                inst.maps[0] = inst.maps[0][mask]
904
            else:
905
                raise ValueError("Sympy expression is not splitable.")
906
            inst = inst.cleaned()
907
        elif at_intersection == 'remove':
908
            inst = inst[mask]
909
        else:
910
911
            raise AttributeError("No at_intersection method called {at_intersection} "
                                 "implemented".format(**locals()))
912
913
914
915
916
917
918
919
920
921
922
923
924

        if _in_recursion:
            template = None
        else:
            template_field = inst.fields.pop(-1)
            template_maps = []
            for mp in inst.maps:
                t_mp = tfields.TensorFields(tfields.Tensors(mp),
                                            mp.fields.pop(-1))
                template_maps.append(t_mp)
            template = tfields.Mesh3D(tfields.Tensors(inst),
                                      template_field,
                                      maps=template_maps)
925
        return inst, template
926
927

    def _cut_template(self, template):
928
929
930
931
932
933
934
935
        """
        Args:
            template (tfields.Mesh3D)

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

936
            Build mesh
937
938
939
            >>> mmap = tfields.TensorFields([[0, 1, 2], [0, 3, 4]],
            ...                             [[42, 21], [-42, -21]])
            >>> m = tfields.Mesh3D([[0]*3, [1]*3, [2]*3, [3]*3, [4]*3],
940
941
            ...                    [0.0, 0.1, 0.2, 0.3, 0.4],
            ...                    [0.0, -0.1, -0.2, -0.3, -0.4],
942
943
            ...                    maps=[mmap])

944
            Build template
945
946
947
            >>> tmap = tfields.TensorFields([[0, 3, 4], [0, 1, 2]],
            ...                             [1, 0])
            >>> t = tfields.Mesh3D([[0]*3, [-1]*3, [-2]*3, [-3]*3, [-4]*3],
948
            ...                    [1, 0, 3, 2, 4],
949
950
            ...                    maps=[tmap])

951
            Use template as instruction to make a fast cut
952
953
954
955
956
957
958
959
960
            >>> res = m._cut_template(t)
            >>> assert np.array_equal(res.fields,
            ...                       [[0.1, 0.0, 0.3, 0.2, 0.4],
            ...                        [-0.1, 0.0, -0.3, -0.2, -0.4]])

            >>> assert np.array_equal(res.maps[0].fields[0],
            ...                       [[-42, -21], [42, 21]])
                                   
        """
961
        # Redirect fields
962
        fields = []
963
        if template.fields:
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
            template_field = np.array(template.fields[0])
            if len(self) > 0:
                '''
                if new vertices have been created in the template, it is
                in principle unclear what fields we have to refer to.
                Thus in creating the template, we gave np.nan.
                To make it fast, we replace nan with 0 as a dummy and correct
                the field entries afterwards with np.nan.
                '''
                nan_mask = np.isnan(template_field)
                template_field[nan_mask] = 0  # dummy reference to index 0.
                template_field = template_field.astype(int)
                for field in self.fields:
                    projected_field = field[template_field]
                    projected_field[nan_mask] = np.nan  # correction for nan
                    fields.append(projected_field)
980
981

        # Redirect maps fields
982
983
984
985
986
987
988
        maps = []
        for mp, template_mp in zip(self.maps, template.maps):
            if template_mp.fields:
                mp_fields = [field[template_mp.fields[0].astype(int)]
                             for field in mp.fields]
            else:
                mp_fields = []
989
            new_mp = tfields.TensorFields(tfields.Tensors(template_mp),
990
991
992
                                          *mp_fields)
            maps.append(new_mp)

993
994
        inst = tfields.Mesh3D(tfields.Tensors(template),
                              *fields,
995
                              maps=maps)
996
997
998
999
        return inst

    def cut(self, expression, coordSys=None, at_intersection=None,
            return_template=False):
1000
1001
1002
        """
        cut method for Mesh3D.
        Args:
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
            expression (sympy logical expression | Mesh3D):
                sympy locical expression: Sympy expression that defines planes
                    in 3D
                Mesh3D: A mesh3D will be interpreted as a template, i.e. a
                    fast instruction of how to cut the triangles.
                    It is the second part of the tuple, returned by a previous
                    cut with a sympy locial expression with 'return_template=True'.
                    We use the vertices and maps of the Mesh as the sceleton of
                    the returned mesh. The fields are mapped according to
                    indices in the template.maps[i].fields.
1013
1014
            coordSys (coordinate system to cut in):
            at_intersection (str): instruction on what to do, when a cut will intersect a triangle.
1015
1016
                Options:    "remove" (Default)
                            "split" - Create new triangles that make up the old one.
1017
1018
            return_template (bool): If True: return the template
                            to redo the same cut fast
1019
1020
        Examples:
            define the cut
1021
            >>> import tfields
1022
1023
1024
            >>> from sympy.abc import x,y,z
            >>> cutExpr = x > 1.5

1025
1026
            >>> m = tfields.Mesh3D.grid((0, 3, 4),
            ...                         (0, 3, 4),
1027
            ...                         (0, 0, 1))
1028
1029
1030
1031
1032
1033
            >>> m.fields.append(tfields.Tensors(np.linspace(0, len(m) - 1,
            ...                                             len(m))))
            >>> m.maps[0].fields.append(
            ...     tfields.Tensors(np.linspace(0,
            ...                                 len(m.maps[0]) - 1,
            ...                                 len(m.maps[0]))))
1034
            >>> mNew = m.cut(cutExpr)
1035
            >>> len(mNew)
1036
            8
1037
            >>> mNew.nfaces()
1038
1039
1040
1041
1042
            6
            >>> float(mNew[:, 0].min())
            2.0

            Cutting with the split option will create new triangles on the edge:
1043
1044
            >>> m_split = m.cut(cutExpr, at_intersection='split')
            >>> float(m_split[:, 0].min())
1045
            1.5
1046
            >>> len(m_split)
1047
            15
1048
            >>> m_split.nfaces()
1049
1050
            15

1051
1052
1053
1054
            Cut with 'return_template=True' will return the exact same mesh but
            additionally an instruction to conduct the exact same cut fast (template)
            >>> m_split_2, template = m.cut(cutExpr, at_intersection='split',
            ...                                    return_template=True)
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
            >>> m_split_template = m.cut(template)
            >>> assert m_split.equal(m_split_2, equal_nan=True)
            >>> assert m_split.equal(m_split_template, equal_nan=True)
            >>> assert len(template.fields) == 1
            >>> assert len(m_split.fields) == 1
            >>> assert len(m_split_template.fields) == 1
            >>> assert m_split.fields[0].equal(
            ...     list(range(8, 16)) + [np.nan] * 7, equal_nan=True)
            >>> assert m_split_template.fields[0].equal(
            ...     list(range(8, 16)) + [np.nan] * 7, equal_nan=True)
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075

            This seems irrelevant at first but Consider, the map field or the
            tensor field changes:
            >>> m_altered_fields = m.copy()
            >>> m_altered_fields[0] += 42
            >>> assert not m_split.equal(m_altered_fields.cut(template))
            >>> assert tfields.Tensors(m_split).equal(m_altered_fields.cut(template))
            >>> assert tfields.Tensors(m_split.maps[0]).equal(m_altered_fields.cut(template).maps[0])


            The cut expression may be a sympy.BooleanFunction:
1076
1077
            >>> cut_expr_bool_fun = (x > 1.5) & (y < 1.5) & (y >0.2) & (z > -0.5)
            >>> m_split_bool = m.cut(cut_expr_bool_fun, at_intersection='split')
1078
1079
1080

        Returns:
            copy of cut mesh
1081
            * optional: template
1082
1083

        """
1084
        with self.tmp_transform(coordSys or self.coordSys):
1085
1086
1087
1088
1089
1090
1091
1092
            if isinstance(expression, Mesh3D):
                obj = self._cut_template(expression)
            else:
                at_intersection = at_intersection or "remove"
                obj, template = self._cut_sympy(expression, at_intersection=at_intersection)
        if return_template:
            return obj, template
        return obj
1093

1094
    def align_norms(self, norm_vectors):
1095
        """
1096
1097
        Orientate the faces such, that their norm_vectors align to the
        norm_vectors given.
1098
1099
1100
        Examples
            >>> m = tfields.Mesh3D([[0,0,0], [1,0,0], [-1,0,0], [0,1,0], [0,0,1]],
            ...            [[0, 1, 3], [1, 3, 4], [1, 3, 2]]);
1101
1102
            >>> newNorms = m.triangles.norms() * -1
            >>> m.align_norms(newNorms)
1103
1104
1105
1106
1107
1108
            >>> m.faces
            array([[0, 3, 1],
                   [1, 4, 3],
                   [1, 2, 3]])

        """
1109
        if not self.nfaces() == 0:
1110
            # vector product < 0
1111
            mask = np.einsum('...i,...i', self.triangles.norms(), norm_vectors) < 0
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
            """
            the line:
            " self.faces[:, [1, 2]][mask] = self.faces[:, [2, 1]][mask] "
            would be a nice solution, but numpy does not mutate the [1, 2] but returns a copy

            """
            temp = np.copy(self.faces[mask, 1])
            self.faces[mask, 1] = self.faces[mask, 2]
            self.faces[mask, 2] = temp

1122
1123
1124
1125
1126
1127
    def plot(self):
        import mplTools as mpt
        mpt.plotMesh(self, self.faces, color=self.maps[0].fields[0], vmin=0,
                     vmax=20, axis=mpt.gca(3))
        mpt.plt.show()

1128
1129
1130
1131

if __name__ == '__main__':
    import doctest

1132
    # doctest.run_docstring_examples(Mesh3D.cut, globals())
1133
    # doctest.run_docstring_examples(Mesh3D._cut_template, globals())
1134
    # quit()
1135
    doctest.testmod()