mesh3D.py 43 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

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


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

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

        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]]);
78
79
80
        >>> assert m.triangles.equal(tfields.Triangles3D([[ 1.,  0.,  0.],
        ...                                               [ 0.,  1.,  0.],
        ...                                               [ 0.,  0.,  0.]]))
81
82

        a list of scalars is assigned to each face
83
84
85
        >>> 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
86
87

        adding together two meshes:
88
89
90
91
92
93
94
95
96
97
        >>> 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
98
        >>> assert np.array_equal(msum.faces, [[0, 1, 2], [3, 4, 5]])
99
100
101
102

        Saving and reading
        >>> from tempfile import NamedTemporaryFile
        >>> outFile = NamedTemporaryFile(suffix='.npz')
103
        >>> m.save(outFile.name)
104
        >>> _ = outFile.seek(0)
105
        >>> m1 = tfields.Mesh3D.load(outFile.name)
106
107
108
109
110
111
112
113
114
        >>> 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
115
        fields = kwargs.pop('fields', [])
116
117
118
        faces = kwargs.pop('faces', None)
        faceScalars = kwargs.pop('faceScalars', [])
        maps = kwargs.pop('maps', None)
119
        if maps is not None and faces is not None:
120
121
122
            raise ValueError("Conflicting options maps and faces")
        if maps is not None:
            kwargs['maps'] = maps
123
        if len(faceScalars) > 0:
124
125
126
127
128
129
130
131
132
133
134
135
136
            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

137

138
139
140
    @classmethod
    def plane(cls, *base_vectors, **kwargs):
        vertices = tfields.Tensors.grid(*base_vectors)
141
142
143

        base_vectors = tfields.grid.ensure_complex(*base_vectors)
        base_vectors = tfields.grid.to_base_vectors(*base_vectors)
144
145
146
147
148
149
150
        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
151
152
        if fix_coord is None:
            raise ValueError("Describe a plane with one variable fiexed")
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174

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

175
176
177
        base_vectors = tfields.grid.ensure_complex(*base_vectors)
        base_vectors = tfields.grid.to_base_vectors(*base_vectors)

178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
        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

201
202
203
204
205
206
207
208
209
210
211
212
213
    @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
214
215
    def faceScalars(self, scalars):
        self.maps[0].fields = scalars_to_fields(scalars)
216
217
218
219
220
221
222
223
224

    @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([])
225
226
227
228
        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)
229
230
231
232
233

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

236
    def nfaces(self):
237
238
        return self.faces.shape[0]

239
    def in_faces(self, points, delta, assign_multiple=False):
240
241
242
        """
        Check whether points lie within triangles with Barycentric Technique
        """
243
244
        masks = self.triangles.in_triangles(points, delta,
                                            assign_multiple=assign_multiple)
245
246
        return masks

247
    def cutScalars(self, expression, coords=None,
248
249
250
251
                   replaceValue=np.nan, scalarIndex=None, inplace=False):
        """
        Set a threshold to the scalars.
        Args:
252
            expression (sympy cut expression or list of those):
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
                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()

284
        if isinstance(expression, list):
285
286
            if scalarIndex is not None:
                raise ValueError("scalarIndex must be None, "
287
288
289
290
                                 "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):
291
292
293
294
295
                inst.cutScalars(ce, coords=coords,
                                replaceValue=replaceValue,
                                scalarIndex=si, inplace=True)
        else:
            if coords is None:
296
                freeSymbols = expression.free_symbols
297
298
299
                if len(freeSymbols) > 1:
                    raise ValueError('coords must be given if multiple variables are given')
                elif len(freeSymbols) == 0:
300
                    raise NotImplementedError("Expressiongs like {expression} "
301
302
303
304
305
306
                                              "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]

307
308
                maskBelow = tfields.evalf(scalarArrays,
                                            expression=expression,
309
310
311
312
                                            coords=[coords[scalarIndex]])
                scalarArrays[maskBelow] = replaceValue
                inst.faceScalars[:, scalarIndex:scalarIndex + 1] = scalarArrays
            else:
313
314
                maskBelow = tfields.evalf(scalarArrays,
                                            expression=expression,
315
316
317
318
319
320
321
322
323
324
325
326
327
                                            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
328
            >>> vertexMask = m.evalf(z < 6)
329
330
331
332
333
334
335
336
            >>> 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)
337
        indices = np.array(range(len(self)))
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
        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
        """
393
        staleMask = np.full(len(self), False, dtype=bool)
394
        used = set(self.faces.flatten())
395
        for i in range(len(self)):
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
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
466
467
468
469
470
471
472
            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)
473
            mesh = mesh.cleaned(duplicates=False)
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
            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)]
533
            >>> mesh = tfields.Mesh3D.grid(*base).cleaned()
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553

            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)

554
        norms = self.triangles.norms()
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
        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)]
593
            >>> mesh = tfields.Mesh3D.grid(*base).cleaned()
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617

            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

618
        norms = self.triangles.norms()
619
620
621
622
623
624
625
626
627
628
629
        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

630
    def template(self, sub_mesh, delta=1e-9):
631
632
        """
        Returns:
633
634
            Mesh3D: template (see cut), can be used as template to retrieve
                sub_mesh from self instance
635
636
637
638
639
        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
640
641
            >>> mCut, mapMesh = m.cut(y < 1.5, at_intersection='split')
            >>> mm = m.template(mCut)
642
643
644
645
646
647
648
649
650
651
            >>> 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])
652
        cents = tfields.Points3D(sub_mesh.getCentroids())
653
654
655
656
657
658
659
660
661
662
663
664
665
666
        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]
667
        inst = sub_mesh.copy()
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
        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)
713
714
        lonely_bool = True if nTrue == 1 else False
        index = facePointsRejected.index(lonely_bool)
715
716
717
718
719
720
        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)
721
                        if not facePointsRejected[j] == lonely_bool]
722
723

        # TODO handle special cases. For now triangles with at least two points on plane are excluded
724
        new_points = None
725
726
727
728
729
730
731
732
733
734
735
        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
736
        if lonely_bool:
737
738
            # one new triangle
            if len(s0) == 1 and len(s1) == 1:
739
                new_points = np.array([couplePoints[0], couplePoints[1], s0[0], s1[0]])
740
741
                faces = np.array([[0, 2, 1], [1, 2, 3]])
            elif len(s1) == 1 and len(s2) == 1:
742
                new_points = np.array([couplePoints[0], couplePoints[1], s1[0], s2[0]])
743
744
                faces = np.array([[0, 1, 2], [0, 2, 3]])
            elif len(s0) == 1 and len(s2) == 1:
745
                new_points = np.array([couplePoints[0], couplePoints[1], s0[0], s2[0]])
746
747
748
749
750
751
752
                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:
753
                new_points = np.array([singlePoint, s0[0], s1[0]])
754
755
                faces = np.array([[0, 2, 1]])
            elif len(s1) == 1 and len(s2) == 1:
756
                new_points = np.array([singlePoint, s1[0], s2[0]])
757
758
                faces = np.array([[0, 2, 1]])
            elif len(s0) == 1 and len(s2) == 1:
759
                new_points = np.array([singlePoint, s0[0], s2[0]])
760
761
762
                faces = np.array([[0, 1, 2]])
            else:
                return None, None
763
        return new_points, faces
764

765
    def _cut_sympy(self, expression, at_intersection="remove", _template=None):
766
767
768
        """
        Partition the mesh with the cuts given
        Args:
769
            expression (sympy logical expression): see Tensors.cut
770
            at_intersection (str): option switch for expression (see
771
772
773
774
775
776
777
                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]])
778
            >>> mCut = m.cut(mNew)
779
780
781
            >>> mCut.faceScalars
            array([[ 6.,  7.]])

782
783
            Cut with 'return_template=True' will return an instruction
            on how to conduct the cut fast (template)
784
785
786
787
            >>> 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]])
788
            >>> mCut, template = m.cut(y < 1.5, at_intersection='split',
789
            ...                       return_template=True)
790
791
792
            >>> mCut.faceScalars.T
            array([[ 1.,  2.,  3.,  3.,  4.]])

793
            Applying the template results in the same result as applying the cut
794
            with the condition
795
            >>> mCut2 = m.cut(template)
796
797
798
799
800
801
            >>> bool((mCut == mCut2).all())
            True
            >>> bool((mCut.faceScalars == mCut2.faceScalars).all())
            True

        """
802
803
804
805
806
807
        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
808
        mask = self.evalf(expression)
809
        # remove the points
810
        inst = self[mask].copy()
811
812
        faceKeepMask = self.getFaceMask(mask)
        scalarMap = np.arange(self.nfaces())[faceKeepMask]
813
814
815
816
        scalarMap = scalarMap.reshape((-1, 1)).astype(float)

        if not any(~mask):
            # no faces have been removed.
817
            return inst, Mesh3D(inst, faceScalars=scalarMap)
818
819
820
821
822
823
824

        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':
825
826
827
            expression_parts = symTools.getExpressionParts(expression)  # TODO: move to tfields lib
            if len(expression_parts) > 1:
                new_mesh = self.copy()
828
829
830
831
832
833
834
835
836
837
838
                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]
839
840
                        face_on_edge = any(facePointsRejected) and not all(facePointsRejected)
                        if face_on_edge:
841
                            faceIntersMask[i] = True
842
                    new_mesh.removeFaces(-faceIntersMask)
843

844
845
846
847
848
                for exprPart in expression_parts:
                    new_mesh, _template = new_mesh._cut_sympy(exprPart,
                                                              at_intersection='split',
                                                              _template=_template)
            elif len(expression_parts) == 1:
849
850
851
                points = [sympy.symbols('x0, y0, z0'),
                          sympy.symbols('x1, y1, z1'),
                          sympy.symbols('x2, y2, z2')]
852
853
854
855
                plane_sympy = symTools.getPlane(expression)
                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}
856
857

                norm_vectors = self.triangles.norms()
858
859
860
861
                new_points = np.empty((0, 3))
                new_faces = np.empty((0, 3))
                new_map_fields = [[] for field in self.maps[0].fields]
                new_norm_vectors = []
862
                newScalarMap = []
863
                n_new = 0
864
865
866
867
868
869
                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]
870
871
                    face_on_edge = any(facePointsRejected) and not all(facePointsRejected)
                    if face_on_edge:
872
                        """
873
874
875
                        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)
876
                        """
877
878
                        nTrue = facePointsRejected.count(True)
                        # the bool that occures on
879
                        lonely_bool = True if nTrue == 1 else False
880
881

                        triangle_points = [self[f] for f in face]
882
                        """
883
                        Add the intersection points and faces
884
                        """
885
                        # tick = time()
886
                        if lonely_bool:
887
888
889
890
891
                            # 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)
892
893
894
895
896
897
                                new_points = np.concatenate((new_points, newP))
                                new_faces = np.concatenate((new_faces, newF +
                                                            n_new))
                                for fld_idx, fld in enumerate(self.maps[0].fields):
                                    new_map_fields[fld_idx].extend([fld[i]] * 2)
                                new_norm_vectors.extend([norm_vectors[i]] * 2)
898
                                newScalarMap.extend([i] * 2)
899
                                n_new += 4
900
                            else:
901
902
903
904
905
906
907
                                pass
                        else:
                            # singlePoint on keep 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)
908
909
910
911
912
913
                                new_points = np.concatenate((new_points, newP))
                                new_faces = np.concatenate((new_faces, newF +
                                                           n_new))
                                for fld_idx, fld in enumerate(self.maps[0].fields):
                                    new_map_fields[fld_idx].extend([fld[i]] * 1)
                                new_norm_vectors.extend([norm_vectors[i]] * 1)
914
                                newScalarMap.extend([i])
915
                                n_new += 3
916
917
918
                            else:
                                pass

919
920
921
922
923
924
925
                new_points = [[float(p[0]), float(p[1]), float(p[2])] for p in new_points]  # TODO:[map(float, p) for p in new_points]
                face_map = tfields.TensorFields(new_faces, *new_map_fields, dtype=int,
                                                coordSys=inst.coordSys)
                new_mesh = self.__class__(new_points, maps=[face_map],
                                          coordSys=inst.coordSys,
                                          faceScalars=new_map_fields)
                new_mesh.align_norms(new_norm_vectors)
926
927
                newScalarMap = np.array(newScalarMap).reshape((-1, 1)).astype(float)
                scalarMap = np.concatenate((scalarMap, newScalarMap))
928
            else:
929
930
931
932
933
934
935
936
                raise ValueError("Sympy expression is not splitable.")

            '''
            Merge parts of mesh that are clearly in the cuts (inst) with
            parts of mesh on the edge of the cuts, where new vertices and faces 
            have been defined
            '''
            inst = self.__class__.merged(inst, new_mesh)
937
938
939

        elif at_intersection == 'remove':
            pass
940
        else:
941
942
            raise AttributeError("No at_intersection method called {at_intersection} "
                                 "implemented".format(**locals()))
943
944
945
        template = inst.copy()
        template.faceScalars = scalarMap
        return inst, template
946
947

    def _cut_template(self, template):
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
        """
        Args:
            template (tfields.Mesh3D)

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

            Mesh
            >>> 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],
            ...                    fields=[[0.0, 0.1, 0.2, 0.3, 0.4],
            ...                            [0.0, -0.1, -0.2, -0.3, -0.4]],
            ...                    maps=[mmap])

            Template
            >>> tmap = tfields.TensorFields([[0, 3, 4], [0, 1, 2]],
            ...                             [1, 0])
            >>> t = tfields.Mesh3D([[0]*3, [-1]*3, [-2]*3, [-3]*3, [-4]*3],
            ...                    fields=[[1, 0, 3, 2, 4]],
            ...                    maps=[tmap])

            >>> 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]])
                                   
        """
        if template.fields:
            fields = [field[template.fields[0].astype(int)]
                      for field in self.fields]
        else:
            fields = []
        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 = []
            new_mp = tfields.TensorFields(template_mp,
                                          *mp_fields)
            maps.append(new_mp)

        inst = tfields.Mesh3D(template,
                              fields=fields,
                              maps=maps)
999
1000
1001
1002
        return inst

    def cut(self, expression, coordSys=None, at_intersection=None,
            return_template=False):
1003
1004
1005
        """
        cut method for Mesh3D.
        Args:
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
            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.
1016
1017
            coordSys (coordinate system to cut in):
            at_intersection (str): instruction on what to do, when a cut will intersect a triangle.
1018
1019
                Options:    "remove" (Default)
                            "split" - Create new triangles that make up the old one.
1020
1021
            return_template (bool): If True: return the template
                            to redo the same cut fast
1022
1023
        Examples:
            define the cut
1024
            >>> import tfields
1025
1026
1027
            >>> from sympy.abc import x,y,z
            >>> cutExpr = x > 1.5

1028
1029
1030
1031
            >>> m = tfields.Mesh3D.grid((0,3,4),
            ...                         (0,3,4),
            ...                         (0, 0, 1))
            >>> m.faceScalars = np.linspace(4, 8, 18)
1032
            >>> mNew = m.cut(cutExpr)
1033
            >>> len(mNew)
1034
            8
1035
            >>> mNew.nfaces()
1036
1037
1038
1039
1040
            6
            >>> float(mNew[:, 0].min())
            2.0

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

            Cuttin with a sympy BooleanFunction:
1050
1051
1052
1053
1054
1055
1056
1057
1058
            >>> 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')
            >>> m_split_bool.maps[0]
            
            >>> import mplTools as mpt
            >>> mpt.plotMesh(mSplit, mSplit.faces, color=mSplit.maps[0].fields[0], vmin=0, vmax=10)

            # >>> mpt.plotMesh(m_split_bool, m_split_bool.faces, color=m_split_bool.maps[0].fields[0], vmin=0, vmax=10)
            >>> mpt.plt.show()
1059
1060
1061
1062
1063

        Returns:
            copy of cut mesh

        """
1064
        with self.tmp_transform(coordSys or self.coordSys):
1065
1066
1067
1068
1069
1070
1071
1072
            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
1073

1074
    def align_norms(self, norm_vectors):
1075
        """
1076
1077
        Orientate the faces such, that their norm_vectors align to the
        norm_vectors given.
1078
1079
1080
        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]]);
1081
1082
            >>> newNorms = m.triangles.norms() * -1
            >>> m.align_norms(newNorms)
1083
1084
1085
1086
1087
1088
            >>> m.faces
            array([[0, 3, 1],
                   [1, 4, 3],
                   [1, 2, 3]])

        """
1089
        if not self.nfaces() == 0:
1090
            # vector product < 0
1091
            mask = np.einsum('...i,...i', self.triangles.norms(), norm_vectors) < 0
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
            """
            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


if __name__ == '__main__':
    import doctest

1106
    doctest.run_docstring_examples(Mesh3D.cut, globals())
1107
    # doctest.run_docstring_examples(Mesh3D._cut_template, globals())
1108
    quit()
1109
    doctest.testmod()