mesh3D.py 43.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
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
    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(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:
        tuple: points, faces
    """
    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)

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

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

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

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







140
141
142
143
144
145
146
147
148
149
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):
150
    return [tfields.TensorFields(faces, *fields, dtype=int, dim=3)]
151

152

153
def maps_to_faces(maps):
154
155
156
157
158
    if len(maps) == 0:
        return np.array([])
    elif len(maps) > 1:
        raise NotImplementedError("Multiple maps")
    return np.array(maps[0])
159
160


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

        conversion to points only
178
179
180
181
182
        >>> tfields.Points3D(m).equal([[1, 2, 3],
        ...                            [3, 3, 3],
        ...                            [0, 0, 0],
        ...                            [5, 6, 7]])
        True
183
184
185
186
187
188

        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]]);
189
190
191
        >>> assert m.triangles.equal(tfields.Triangles3D([[ 1.,  0.,  0.],
        ...                                               [ 0.,  1.,  0.],
        ...                                               [ 0.,  0.,  0.]]))
192
193

        a list of scalars is assigned to each face
194
195
196
        >>> 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
197
198

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

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

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

247

248
249
250
    @classmethod
    def plane(cls, *base_vectors, **kwargs):
        vertices = tfields.Tensors.grid(*base_vectors)
251
252
253

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

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

285
286
287
        base_vectors = tfields.grid.ensure_complex(*base_vectors)
        base_vectors = tfields.grid.to_base_vectors(*base_vectors)

288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
        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

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

    @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([])
335
336
337
338
        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)
339
340
341
342
343

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

346
    def nfaces(self):
347
348
        return self.faces.shape[0]

349
    def in_faces(self, points, delta, assign_multiple=False):
350
351
352
        """
        Check whether points lie within triangles with Barycentric Technique
        """
353
354
        masks = self.triangles.in_triangles(points, delta,
                                            assign_multiple=assign_multiple)
355
356
        return masks

357
    def cutScalars(self, expression, coords=None,
358
359
360
361
                   replaceValue=np.nan, scalarIndex=None, inplace=False):
        """
        Set a threshold to the scalars.
        Args:
362
            expression (sympy cut expression or list of those):
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
                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()

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

417
418
                maskBelow = tfields.evalf(scalarArrays,
                                            expression=expression,
419
420
421
422
                                            coords=[coords[scalarIndex]])
                scalarArrays[maskBelow] = replaceValue
                inst.faceScalars[:, scalarIndex:scalarIndex + 1] = scalarArrays
            else:
423
424
                maskBelow = tfields.evalf(scalarArrays,
                                            expression=expression,
425
426
427
428
429
430
431
432
433
434
435
436
437
                                            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
438
            >>> vertexMask = m.evalf(z < 6)
439
440
441
442
443
444
445
446
            >>> 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)
447
        indices = np.array(range(len(self)))
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
        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
        """
503
        staleMask = np.full(len(self), False, dtype=bool)
504
        used = set(self.faces.flatten())
505
        for i in range(len(self)):
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
            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)
583
            mesh = mesh.cleaned(duplicates=False)
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
            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)]
643
            >>> mesh = tfields.Mesh3D.grid(*base).cleaned()
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663

            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)

664
        norms = self.triangles.norms()
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
        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)]
703
            >>> mesh = tfields.Mesh3D.grid(*base).cleaned()
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727

            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

728
        norms = self.triangles.norms()
729
730
731
732
733
734
735
736
737
738
739
        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

740
    def template(self, sub_mesh, delta=1e-9):
741
742
        """
        Returns:
743
744
            Mesh3D: template (see cut), can be used as template to retrieve
                sub_mesh from self instance
745
746
747
748
749
        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
750
751
            >>> mCut, mapMesh = m.cut(y < 1.5, at_intersection='split')
            >>> mm = m.template(mCut)
752
753
754
755
756
757
758
759
760
            >>> 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])
761
        cents = tfields.Points3D(sub_mesh.getCentroids())
762
763
764
        scalars = []
        mask = self.pointsInMesh(cents, delta=delta)
        scalars = [faceIndices[faceMask] for faceMask in mask]
765
        inst = sub_mesh.copy()
766
767
768
        inst.setScalarArray(0, scalars)
        return inst

769
    def _cut_sympy(self, expression, at_intersection="remove", _in_recursion=False):
770
        """
771
        Partition the mesh with the cuts given and return the template
772
773

        """
774
775
776
777
778
        eps = 0.000000001
        # direct return if self is empty
        if len(self) == 0:
            return self.copy(), self.copy()

779
780
781
782
783
784
785
786
787
788
789
        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))))

790
        # mask for points that do not fulfill the cut expression
791
        mask = inst.evalf(expression)
792
        # remove the points
793
794
795
796
797
798
799
800
801
802
803
804
805
        inst_pre_mask = inst.copy()
        inst = inst[mask]

        if not any(~mask) or all(~mask):
            pass
        elif at_intersection == 'split' or at_intersection == 'splitRough':
            # add points and faces intersecting with the plane
            expression_parts = tfields.lib.symbolics.split_expression(expression)
            '''
            define a new mesh that will be merged with the existing one
            the new mesh will describe the faces that are at the border of the
            cuts
            '''
806
            if len(expression_parts) > 1:
807
                new_mesh = inst_pre_mask.copy()
808
809
810
811
812
813
814
815
816
817
                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):
818
819
                        vertices_rejected = [-mask[f] for f in face]
                        face_on_edge = any(vertices_rejected) and not all(vertices_rejected)
820
                        if face_on_edge:
821
                            faceIntersMask[i] = True
822
                    new_mesh.removeFaces(-faceIntersMask)
823

824
                for exprPart in expression_parts:
825
826
827
                    new_mesh, _ = new_mesh._cut_sympy(exprPart,
                                                      at_intersection='split',
                                                      _in_recursion=True)
828
            elif len(expression_parts) == 1:
829
                # TODO maps[0] -> smthng like self.get_map(dim=3)
830
831
832
                points = [sympy.symbols('x0, y0, z0'),
                          sympy.symbols('x1, y1, z1'),
                          sympy.symbols('x2, y2, z2')]
833
                plane_sympy = tfields.lib.symbolics.to_plane(expression)
834
835
836
                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}
837
838

                norm_vectors = self.triangles.norms()
839
840
                new_points = np.empty((0, 3))
                new_faces = np.empty((0, 3))
841
842
843
844
                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]
845
                new_norm_vectors = []
846
                newScalarMap = []
847
                n_new = 0
848
849

                for i, face in enumerate(self.maps[0]):
850
                    """
851
                    vertices_rejected is a mask for each face that is True, where
852
853
                    a Point is on the rejected side of the plane
                    """
854
855
                    vertices_rejected = [~mask[f] for f in face]
                    face_on_edge = any(vertices_rejected) and not all(vertices_rejected)
856
                    if face_on_edge:
857
                        """
858
859
860
                        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)
861
                        """
862
                        nTrue = vertices_rejected.count(True)
863
                        # the bool that occures on
864
                        lonely_bool = True if nTrue == 1 else False
865
866

                        triangle_points = [self[f] for f in face]
867
                        """
868
                        Add the intersection points and faces
869
                        """
870
871
872
873
874
875
876
877
878
879
880
                        print "______________"
                        print triangle_points, vertices_rejected
                        newP, newF = _intersect(triangle_points, plane, vertices_rejected)
                        print newP, newF
                        if newP is not None:
                            if lonely_bool:
                                '''
                                singlePoint on cut away side
                                build two new triangles with two known and two new
                                points
                                '''
881
882
                                newP = np.array(newP)
                                np.place(newP, np.logical_and(0 < newP, newP <= eps), 0.0)
883
                                new_points = np.concatenate((new_points, newP))
884
885
886
                                new_fields = [tfields.Tensors.merged(field,
                                                                     np.full((4,) + field.shape[1:], np.nan))
                                              for field in new_fields]
887
888
                                new_faces = np.concatenate((new_faces, newF +
                                                            n_new))
889
890
891
892
                                for field_idx, field in enumerate(self.maps[0].fields):
                                    new_map_fields[field_idx].extend([field[i]] * 2)
                                if not _in_recursion:
                                    new_map_fields[-1].extend([i] * 2)
893
                                new_norm_vectors.extend([norm_vectors[i]] * 2)
894
                                newScalarMap.extend([i] * 2)
895
                                n_new += 4
896
                            else:
897
898
899
900
                                '''
                                singlePoint on keep side
                                build one new triangle with one known and two new points
                                '''
901
902
                                newP = np.array(newP)
                                np.place(newP, np.logical_and(0 < newP, newP <= eps), 0.0)
903
                                new_points = np.concatenate((new_points, newP))
904
905
906
                                new_fields = [tfields.Tensors.merged(field,
                                                                     np.full((3,) + field.shape[1:], np.nan))
                                              for field in new_fields]
907
908
                                new_faces = np.concatenate((new_faces, newF +
                                                           n_new))
909
910
911
912
                                for field_idx, field in enumerate(self.maps[0].fields):
                                    new_map_fields[field_idx].extend([field[i]] * 1)
                                if not _in_recursion:
                                    new_map_fields[-1].extend([i] * 1)
913
                                new_norm_vectors.extend([norm_vectors[i]] * 1)
914
                                newScalarMap.extend([i])
915
                                n_new += 3
916

917
918
919
                new_points = [map(float, p) for p in new_points]
                face_map = tfields.TensorFields(new_faces, *new_map_fields,
                                                dtype=int,
920
                                                coordSys=inst.coordSys)
921
922
923
924
                new_mesh = tfields.Mesh3D(new_points,
                                          *new_fields,
                                          maps=[face_map],
                                          coordSys=inst.coordSys)
925
                new_mesh.align_norms(new_norm_vectors)
926
            else:
927
928
929
930
                raise ValueError("Sympy expression is not splitable.")

            '''
            Merge parts of mesh that are clearly in the cuts (inst) with
931
            parts of mesh on the edge of the cuts, where new vertices and faces
932
933
            have been defined
            '''
934
935

            inst = tfields.Mesh3D.merged(inst, new_mesh)
936
937
938

        elif at_intersection == 'remove':
            pass
939
        else:
940
941
            raise AttributeError("No at_intersection method called {at_intersection} "
                                 "implemented".format(**locals()))
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956

        if _in_recursion:
            template = None
        else:
            print inst.fields
            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)
            print template.fields
957
        return inst, template
958
959

    def _cut_template(self, template):
960
961
962
963
964
965
966
967
        """
        Args:
            template (tfields.Mesh3D)

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

968
            Build mesh
969
970
971
            >>> 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],
972
973
            ...                    [0.0, 0.1, 0.2, 0.3, 0.4],
            ...                    [0.0, -0.1, -0.2, -0.3, -0.4],
974
975
            ...                    maps=[mmap])

976
            Build template
977
978
979
            >>> tmap = tfields.TensorFields([[0, 3, 4], [0, 1, 2]],
            ...                             [1, 0])
            >>> t = tfields.Mesh3D([[0]*3, [-1]*3, [-2]*3, [-3]*3, [-4]*3],
980
            ...                    [1, 0, 3, 2, 4]
981
982
            ...                    maps=[tmap])

983
            Use template as instruction to make a fast cut
984
985
986
987
988
989
990
991
992
            >>> 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]])
                                   
        """
993
        # Redirect fields
994
995
996
997
998
        if template.fields:
            fields = [field[template.fields[0].astype(int)]
                      for field in self.fields]
        else:
            fields = []
999
1000

        # Redirect maps fields
1001
1002
1003
1004
1005
1006
1007
        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 = []
1008
            new_mp = tfields.TensorFields(tfields.Tensors(template_mp),
1009
1010
1011
                                          *mp_fields)
            maps.append(new_mp)

1012
1013
        inst = tfields.Mesh3D(tfields.Tensors(template),
                              *fields,
1014
                              maps=maps)
1015
1016
1017
1018
        return inst

    def cut(self, expression, coordSys=None, at_intersection=None,
            return_template=False):
1019
1020
1021
        """
        cut method for Mesh3D.
        Args:
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
            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.
1032
1033
            coordSys (coordinate system to cut in):
            at_intersection (str): instruction on what to do, when a cut will intersect a triangle.
1034
1035
                Options:    "remove" (Default)
                            "split" - Create new triangles that make up the old one.
1036
1037
            return_template (bool): If True: return the template
                            to redo the same cut fast
1038
1039
        Examples:
            define the cut
1040
            >>> import tfields
1041
1042
1043
            >>> from sympy.abc import x,y,z
            >>> cutExpr = x > 1.5

1044
1045
            >>> m = tfields.Mesh3D.grid((0, 3, 4),
            ...                         (0, 3, 4),
1046
            ...                         (0, 0, 1))
1047
1048
1049
1050
1051
1052
            >>> 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]))))
1053
            >>> mNew = m.cut(cutExpr)
1054
            >>> len(mNew)
1055
            8
1056
            >>> mNew.nfaces()
1057
1058
1059
1060
1061
            6
            >>> float(mNew[:, 0].min())
            2.0

            Cutting with the split option will create new triangles on the edge:
1062
1063
            >>> m_split = m.cut(cutExpr, at_intersection='split')
            >>> float(m_split[:, 0].min())
1064
            1.5
1065
            >>> len(m_split)
1066
            29
1067
            >>> m_split.nfaces()
1068
1069
            15

1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
            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)
            >>> assert m_split.equal(m_split_2)
            >>> assert m_split.equal(m.cut(template))
            >>> m_split.fields
            >>> m.cut(template).fields

            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:
1089
1090
            >>> 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')
1091
1092
1093

        Returns:
            copy of cut mesh
1094
            * optional: template
1095
1096

        """
1097
        with self.tmp_transform(coordSys or self.coordSys):
1098
1099
1100
1101
1102
1103
1104
1105
            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
1106

1107
    def align_norms(self, norm_vectors):
1108
        """
1109
1110
        Orientate the faces such, that their norm_vectors align to the
        norm_vectors given.
1111
1112
1113
        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]]);
1114
1115
            >>> newNorms = m.triangles.norms() * -1
            >>> m.align_norms(newNorms)
1116
1117
1118
1119
1120
1121
            >>> m.faces
            array([[0, 3, 1],
                   [1, 4, 3],
                   [1, 2, 3]])

        """
1122
        if not self.nfaces() == 0:
1123
            # vector product < 0
1124
            mask = np.einsum('...i,...i', self.triangles.norms(), norm_vectors) < 0
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
            """
            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

1139
    doctest.run_docstring_examples(Mesh3D.cut, globals())
1140
    # doctest.run_docstring_examples(Mesh3D._cut_template, globals())
1141
    quit()
1142
    doctest.testmod()