mesh3D.py 39.6 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
    @classmethod
    def plane(cls, *base_vectors, **kwargs):
244
245
246
247
248
249
250
        """
        Alternative constructor for creating a plane from
        Args:
            *base_vectors: see grid constructors in core. One base_vector has to
                be one-dimensional
            **kwargs: forwarded to __new__
        """
251
        vertices = tfields.Tensors.grid(*base_vectors)
252
253
254

        base_vectors = tfields.grid.ensure_complex(*base_vectors)
        base_vectors = tfields.grid.to_base_vectors(*base_vectors)
255
256
257
258
259
260
261
        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
262
263
        if fix_coord is None:
            raise ValueError("Describe a plane with one variable fiexed")
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282

        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):
283
284
285
        """
        Construct 'cuboid' along base_vectors
        """
286
287
288
        if not len(base_vectors) == 3:
            raise AttributeError("3 base_vectors vectors required")

289
290
291
        base_vectors = tfields.grid.ensure_complex(*base_vectors)
        base_vectors = tfields.grid.to_base_vectors(*base_vectors)

292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
        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

315
316
317
318
319
320
321
322
323
324
325
326
327
    @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
328
329
    def faceScalars(self, scalars):
        self.maps[0].fields = scalars_to_fields(scalars)
330
331
332
333
334
335
336
337
338

    @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([])
339
340
341
342
        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)
343
344
345
346
347

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

350
    def nfaces(self):
351
352
        return self.faces.shape[0]

353
    def in_faces(self, points, delta, assign_multiple=False):
354
355
356
        """
        Check whether points lie within triangles with Barycentric Technique
        """
357
358
        masks = self.triangles.in_triangles(points, delta,
                                            assign_multiple=assign_multiple)
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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
        return masks

    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
        """
407
        staleMask = np.full(len(self), False, dtype=bool)
408
        used = set(self.faces.flatten())
409
        for i in range(len(self)):
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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
            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)
487
            mesh = mesh.cleaned(duplicates=False)
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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
            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)]
547
            >>> mesh = tfields.Mesh3D.grid(*base).cleaned()
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567

            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)

568
        norms = self.triangles.norms()
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
        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)]
607
            >>> mesh = tfields.Mesh3D.grid(*base).cleaned()
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631

            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

632
        norms = self.triangles.norms()
633
634
635
636
637
638
639
640
641
642
643
        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

644
    def template(self, sub_mesh, delta=1e-9):
645
646
        """
        Returns:
647
648
            Mesh3D: template (see cut), can be used as template to retrieve
                sub_mesh from self instance
649
650
651
652
653
        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
654
655
            >>> mCut, mapMesh = m.cut(y < 1.5, at_intersection='split')
            >>> mm = m.template(mCut)
656
657
658
659
660
661
662
663
664
            >>> 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])
665
        cents = tfields.Points3D(sub_mesh.getCentroids())
666
667
668
        scalars = []
        mask = self.pointsInMesh(cents, delta=delta)
        scalars = [faceIndices[faceMask] for faceMask in mask]
669
        inst = sub_mesh.copy()
670
671
672
        inst.setScalarArray(0, scalars)
        return inst

673
    def _cut_sympy(self, expression, at_intersection="remove", _in_recursion=False):
674
        """
675
        Partition the mesh with the cuts given and return the template
676
677

        """
678
679
680
681
682
        eps = 0.000000001
        # direct return if self is empty
        if len(self) == 0:
            return self.copy(), self.copy()

683
684
685
686
687
688
689
690
691
692
693
        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))))

694
        # mask for points that do not fulfill the cut expression
695
        mask = inst.evalf(expression)
696
        # remove the points
697
698

        if not any(~mask) or all(~mask):
699
            inst = inst[mask]
700
701
        elif at_intersection == 'split' or at_intersection == 'splitRough':
            '''
702
            add vertices and faces that are at the border of the cuts
703
            '''
704
            expression_parts = tfields.lib.symbolics.split_expression(expression)
705
            if len(expression_parts) > 1:
706
                new_mesh = inst.copy()
707
708
709
710
711
712
713
714
                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.
                    """
715
716
                    faceIntersMask = np.full((inst.faces.shape[0]), False, dtype=bool)
                    for i, face in enumerate(inst.faces):
717
718
                        vertices_rejected = [-mask[f] for f in face]
                        face_on_edge = any(vertices_rejected) and not all(vertices_rejected)
719
                        if face_on_edge:
720
                            faceIntersMask[i] = True
721
                    new_mesh.removeFaces(-faceIntersMask)
722

723
                for exprPart in expression_parts:
724
725
726
                    inst, _ = inst._cut_sympy(exprPart,
                                              at_intersection='split',
                                              _in_recursion=True)
727
            elif len(expression_parts) == 1:
728
                # TODO maps[0] -> smthng like inst.get_map(dim=3)
729
730
731
                points = [sympy.symbols('x0, y0, z0'),
                          sympy.symbols('x1, y1, z1'),
                          sympy.symbols('x2, y2, z2')]
732
                plane_sympy = tfields.lib.symbolics.to_plane(expression)
733
734
735
                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}
736

737
                norm_vectors = inst.triangles.norms()
738
739
                new_points = np.empty((0, 3))
                new_faces = np.empty((0, 3))
740
741
742
743
                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]
744
                new_norm_vectors = []
745
                newScalarMap = []
746
                n_new = 0
747

748
749
750
751
752
753
754
                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]):
755
                    """
756
                    vertices_rejected is a mask for each face that is True, where
757
758
                    a Point is on the rejected side of the plane
                    """
759
                    vertices_rejected = [~mask[f] for f in face]
760
761
762
763
764
                    if any(vertices_rejected):
                        # delete face
                        face_delete_indices.add(i)
                    if any(vertices_rejected) and not all(vertices_rejected):
                        # face on edge
765
                        nTrue = vertices_rejected.count(True)
766
                        lonely_bool = True if nTrue == 1 else False
767

768
                        triangle_points = [inst[f] for f in face]
769
                        """
770
                        Add the intersection points and faces
771
                        """
772
773
774
                        newP = _intersect(triangle_points, plane, vertices_rejected)
                        last_idx = len(vertices) - 1
                        for tri_list in newP:
775
                            new_face = []
776
777
778
                            for item in tri_list:
                                if isinstance(item, int):
                                    # reference to old vertex
779
                                    new_face.append(face[item])
780
781
782
                                elif isinstance(item, complex):
                                    # reference to new vertex that has been
                                    # concatenated already
783
                                    new_face.append(last_idx + int(item.imag))
784
785
                                else:
                                    # new vertex
786
                                    new_face.append(len(vertices))
787
788
789
790
791
792
793
                                    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]
794
                            faces = np.append(faces, [new_face], axis=0)
795
                            faces_fields = [np.append(field,
796
                                                      [field[i]],
797
798
799
800
801
                                                      axis=0)
                                            for field in faces_fields]
                            faces_fields[-1][-1] = i

                face_map = tfields.TensorFields(faces, *faces_fields,
802
                                                dtype=int,
803
804
805
806
807
808
809
810
811
812
                                                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]
813
            else:
814
                raise ValueError("Sympy expression is not splitable.")
815
            inst = inst.cleaned()
816
        elif at_intersection == 'remove':
817
            inst = inst[mask]
818
        else:
819
820
            raise AttributeError("No at_intersection method called {at_intersection} "
                                 "implemented".format(**locals()))
821
822
823
824
825
826
827
828
829
830
831
832
833

        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)
834
        return inst, template
835
836

    def _cut_template(self, template):
837
838
839
840
841
842
843
844
        """
        Args:
            template (tfields.Mesh3D)

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

845
            Build mesh
846
847
848
            >>> 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],
849
850
            ...                    [0.0, 0.1, 0.2, 0.3, 0.4],
            ...                    [0.0, -0.1, -0.2, -0.3, -0.4],
851
852
            ...                    maps=[mmap])

853
            Build template
854
855
856
            >>> tmap = tfields.TensorFields([[0, 3, 4], [0, 1, 2]],
            ...                             [1, 0])
            >>> t = tfields.Mesh3D([[0]*3, [-1]*3, [-2]*3, [-3]*3, [-4]*3],
857
            ...                    [1, 0, 3, 2, 4],
858
859
            ...                    maps=[tmap])

860
            Use template as instruction to make a fast cut
861
862
863
864
865
866
867
868
869
            >>> 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]])
                                   
        """
870
        # Redirect fields
871
        fields = []
872
        if template.fields:
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
            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)
889
890

        # Redirect maps fields
891
892
893
894
895
896
897
        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 = []
898
            new_mp = tfields.TensorFields(tfields.Tensors(template_mp),
899
900
901
                                          *mp_fields)
            maps.append(new_mp)

902
903
        inst = tfields.Mesh3D(tfields.Tensors(template),
                              *fields,
904
                              maps=maps)
905
906
907
908
        return inst

    def cut(self, expression, coordSys=None, at_intersection=None,
            return_template=False):
909
910
911
        """
        cut method for Mesh3D.
        Args:
912
913
914
915
916
917
918
919
920
921
            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.
922
923
            coordSys (coordinate system to cut in):
            at_intersection (str): instruction on what to do, when a cut will intersect a triangle.
924
925
                Options:    "remove" (Default)
                            "split" - Create new triangles that make up the old one.
926
927
            return_template (bool): If True: return the template
                            to redo the same cut fast
928
929
        Examples:
            define the cut
930
            >>> import tfields
931
932
933
            >>> from sympy.abc import x,y,z
            >>> cutExpr = x > 1.5

934
935
            >>> m = tfields.Mesh3D.grid((0, 3, 4),
            ...                         (0, 3, 4),
936
            ...                         (0, 0, 1))
937
938
939
940
941
942
            >>> 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]))))
943
            >>> mNew = m.cut(cutExpr)
944
            >>> len(mNew)
945
            8
946
            >>> mNew.nfaces()
947
948
949
950
951
            6
            >>> float(mNew[:, 0].min())
            2.0

            Cutting with the split option will create new triangles on the edge:
952
953
            >>> m_split = m.cut(cutExpr, at_intersection='split')
            >>> float(m_split[:, 0].min())
954
            1.5
955
            >>> len(m_split)
956
            15
957
            >>> m_split.nfaces()
958
959
            15

960
961
962
963
            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)
964
965
966
967
968
969
970
971
972
973
            >>> 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)
974
975
976
977
978
979
980
981
982
983
984

            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:
985
986
            >>> 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')
987
988
989

        Returns:
            copy of cut mesh
990
            * optional: template
991
992

        """
993
        with self.tmp_transform(coordSys or self.coordSys):
994
995
996
997
998
999
1000
1001
            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
1002

1003
    def align_norms(self, norm_vectors):
1004
        """
1005
1006
        Orientate the faces such, that their norm_vectors align to the
        norm_vectors given.
1007
1008
        Examples
            >>> m = tfields.Mesh3D([[0,0,0], [1,0,0], [-1,0,0], [0,1,0], [0,0,1]],
1009
            ...                    maps=[[[0, 1, 3], [1, 3, 4], [1, 3, 2]]]);
1010
1011
            >>> newNorms = m.triangles.norms() * -1
            >>> m.align_norms(newNorms)
1012
1013
1014
1015
1016
1017
            >>> m.faces
            array([[0, 3, 1],
                   [1, 4, 3],
                   [1, 2, 3]])

        """
1018
        if not self.nfaces() == 0:
1019
            # vector product < 0
1020
            mask = np.einsum('...i,...i', self.triangles.norms(), norm_vectors) < 0
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
            """
            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

1031
1032
1033
1034
1035
1036
    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()

1037
1038
1039
1040

if __name__ == '__main__':
    import doctest

1041
    # doctest.run_docstring_examples(Mesh3D.cut, globals())
1042
    # doctest.run_docstring_examples(Mesh3D._cut_template, globals())
1043
    # quit()
1044
    doctest.testmod()