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

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

logger = loggingTools.Logger(__name__)


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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

    @faceScalars.setter
149
150
    def faceScalars(self, scalars):
        self.maps[0].fields = scalars_to_fields(scalars)
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287

    @classmethod
    def _updateSlotKwargs(cls, kwargs, skipCache=True):
        faces = kwargs.pop('faces', None)
        faceScalars = kwargs.pop('faceScalars', None)

        # Add faces
        if faces is None or len(faces) == 0:
            faces = np.empty((0, 3), dtype=int)
        faces = np.array(faces, dtype=int)
        kwargs['faces'] = faces

        # Add faceScalars
        if faceScalars is None or len(faceScalars) == 0:
            faceScalars = np.empty((len(faces), 0), dtype=float)
        if not len(faceScalars) == len(faces):
            raise ValueError("Length of faceScalars has to be the same as faces lenght "
                             "({0}) but is {1}.".format(len(faces), len(faceScalars)))
        # demand 2d structure of faceScalars
        faceScalars = np.array(faceScalars, dtype=float)
        if len(faceScalars.shape) == 1:
            faceScalars = faceScalars.reshape(faces.shape[0], -1)
        kwargs['faceScalars'] = faceScalars

        super(Mesh3D, cls)._updateSlotKwargs(kwargs, skipCache=skipCache)

    @classmethod
    def createFromObjFile(cls, filePath, *groupNames):
        """
        Factory method
        Given a filePath to a obj/wavefront file, construct the object
        """
        ioCls = ioTools.ObjFile
        with ioCls(filePath, 'r') as f:
            f.process()
            vertices, faces = f.getVerticesFaces(*groupNames, firstFace=0)

        log = logger.new()
        if len(vertices) == 0:
            return cls([])
        faceLenghts = [len(face) for face in faces]
        for i in reversed(range(len(faceLenghts))):
            length = faceLenghts[i]
            if length == 3:
                continue
            if length == 4:
                log.warning("Given a Rectangle. I will split it but "
                            "sometimes the order is different.")
                faces.insert(i + 1, faces[i][2:] + faces[i][:1])
                faces[i] = faces[i][:3]
            else:
                raise NotImplementedError()
        mesh = cls(vertices, faces=faces)
        if groupNames:
            mesh = mesh.clean()
        return mesh

    @classmethod
    def createFromInpFile(cls, filePath, **kwargs):
        """
        Factory method
        Given a filePath to a inp file, construct the object
        """
        import transcoding as tc
        transcoding = tc.getTranscoding('inp')
        content = transcoding.read(filePath)
        part = content['parts'][0]
        vertices = np.array([part['x'], part['y'], part['z']]).T / 1000
        indices = np.array(part['nodeIndex']) - 1
        if not list(indices) == range(len(indices)):
            raise ValueError("node index skipped")
        faces = np.array([part['nodeIndex{i}'.format(i=i)] for i in range(3)]).T - 1
        return cls(vertices, faces=faces)

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

        indices = [0, -1]
        coords = range(3)
        baseLengthsAbove1 = [len(b) > 1 for b in baseVectors]
        # 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

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

                mParts.append(cls.createMeshPlane(*basePart))
        inst = cls.__new__(cls, mParts, **kwargs)
        return inst

    @classmethod
    def createMeshPlane(cls, *baseVectors, **kwargs):
        points = tfields.Points3D.createMeshGrid(*baseVectors)
        fixCoord = None
        for coord in range(3):
            if len(baseVectors[coord]) > 1:
                continue
            if len(baseVectors[coord]) == 0:
                continue
            fixCoord = coord

        variableCoords = list(range(3))
        variableCoords.pop(variableCoords.index(fixCoord))

        faces = []
        base0, base1 = baseVectors[variableCoords[0]], baseVectors[variableCoords[1]]
        for i1 in range(len(base1) - 1):
            for i0 in range(len(base0) - 1):
                pointIdxTopLeft = len(base1) * (i0 + 0) + (i1 + 0)
                pointIdxTopRight = len(base1) * (i0 + 0) + (i1 + 1)
                pointIdxBotLeft = len(base1) * (i0 + 1) + (i1 + 0)
                pointIdxBotRight = len(base1) * (i0 + 1) + (i1 + 1)
                faces.append([pointIdxTopLeft, pointIdxTopRight, pointIdxBotLeft])
                faces.append([pointIdxTopRight, pointIdxBotLeft, pointIdxBotRight])
        inst = cls.__new__(cls, points, faces=faces, **kwargs)
        return inst

    @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([])
288
289
290
291
        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)
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315

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

    def saveTxt(self, filePath):
        if self.coordSys != self.CARTESIAN:
            cpy = self.copy()
            cpy.coordinateTransform(self.CARTESIAN)
        else:
            cpy = self
        with ioTools.TextFile(filePath, 'w') as f:
            matrix = []
            for i, face in enumerate(self.faces):
                matrix.append(self.faceScalars[i, :])
                matrix.extend(self[face])
            f.writeMatrix(matrix, seperator=' ', lineBreak='\n')

    @classmethod
    def createFromTxtFile(cls, filePath):
        return tfields.Triangles3D.createFromTxtFile(filePath).getMesh3D()

316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
    # def __getattr__(self, name):
    #     """
    #     getter methods are forwarded to self.triangles
    #     Examples:
    #         >>> m = tfields.Mesh3D([]);
    #         >>> m.getAreas
    #         <bound method Triangles3D.getAreas of Triangles3D([], shape=(0, 3), dtype=float64)>

    #     """
    #     if name.startswith('get'):
    #         if not hasattr(tfields.Triangles3D, name) or name == 'getMask':
    #             raise AttributeError("Could not forward attribute {0}".format(name))
    #         else:
    #             return getattr(self.triangles, name)
    #     else:
    #         raise AttributeError("No attribute with name {0}".format(name))
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358

    def getNFaces(self):
        return self.faces.shape[0]

    def getMean(self, *args, **kwargs):
        """
        Forward this manually since getMean is derived already.
        """
        return self.triangles.getMean(*args, **kwargs)

    def getStd(self, *args, **kwargs):
        """
        Forward this manually since getStd is derived already.
        """
        return self.triangles.getStd(*args, **kwargs)

    def getScalars(self):
        return self.faceScalars

    def getScalarArrays(self):
        return self.faceScalars.T

    def getScalarDepth(self):
        return self.faceScalars.shape[1]

    def setScalarArray(self, scalarIndex, scalarArray):
        """
359
360
361
362
363
            >>> 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]])
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
            >>> m.setScalarArray(1, [42, 84])
            >>> m.faceScalars
            array([[  1.,  42.,   3.,   4.,   5.],
                   [  6.,  84.,   8.,   9.,   0.]])

        """
        if scalarIndex == self.getScalarDepth():
            self.appendScalars(scalarArray)
        else:
            self.faceScalars[:, scalarIndex] = scalarArray
            # try:
            #     self.faceScalars[:, scalarIndex] = scalarArray
            # except:
            #     tfields.saveNested("~/tmp/bug1e-6.nest.npz", (self, scalarArray,
            #                                               scalarIndex))
            #     raise

    def removeScalars(self, scalarIndex=None):
        if scalarIndex is not None:
            raise NotImplementedError()
        self.faceScalars = np.empty(self.faceScalars.shape[0],
                                    dtype=self.faceScalars.dtype)

    def appendScalars(self, scalars):
        """
        Similar to list.append but in axis 1
        """
        self.faceScalars = np.concatenate([self.faceScalars, np.array([scalars]).T], 1)

    def stackScalars(self, *stack, **kwargs):
        """
        add all faceScalars of stack meshes to self.faceScalars.
        Args:
            *stack (Mesh3D): input meshes are required to have the
                same or simiar faces. This is not tested for time reasons
                though.
            **kwargs:
                mapping (str):
                    'centroid':  Use centroids for check
                        which face belongs to which.
                    'order': Assume all faces are in the same order.
        Examples:
            >>> m = tfields.Mesh3D([[1,0,0],[0,1,0],[0,0,1], [0,0,0]],
            ...                    [[0,1,2], [2,3,0], [2,3,1]],
            ...                    faceScalars=[1,2,3])
            >>> c = m.copy()

            If you exactly know, the two meshes are the same:
            >>> m.stackScalars(c, mapping='order')
            >>> all(m.getScalarArrays()[0, :] == [2.,4.,6.])
            True

            Using the default compares centroids
            >>> m = c.copy()
            >>> m.stackScalars(c, mapping='centroid')
            >>> all(m.getScalarArrays()[0, :] == [2.,4.,6.])
            True

        """
        mapping = kwargs.pop('mapping', 'centroid')
        for stackObj in stack:
            """
            faceMap is a list of tuples: first meshFaceIndex second
            selfFaceIndex
            """
            if mapping == 'order':
                if not isinstance(stackObj, Mesh3D):
                    raise NotImplementedError()
                faceRange = range(stackObj.getNFaces())
                faceMap = [(i, i) for i in faceRange]
                objScalars = stackObj.faceScalars
            elif mapping == 'centroid':
                if isinstance(stackObj, Mesh3D):
                    faceRange = range(stackObj.getNFaces())
                    centroids = stackObj.getCentroids()
                    objScalars = stackObj.faceScalars
                elif isinstance(stackObj, tfields.ScalarField3D):
                    faceRange = range(stackObj.getNPoints())
                    centroids = stackObj
                    if mapping != 'centroid':
                        raise NotImplementedError()
                    objScalars = stackObj.scalars
                else:
                    raise NotImplementedError()
                closestCentroidIndices = \
                    centroids.closestPoints(self.getCentroids())
                faceMap = [(i, j) for j, i in zip(faceRange, closestCentroidIndices)]
            else:
                raise NotImplementedError()
            faceMap = np.array(faceMap)

            """
            Rearrange scalars according to faceMap
            This is the part that takes longest
            """
            scalars = np.full(self.faceScalars.shape,
                              0.,
                              dtype=objScalars.dtype)
            for i in set(faceMap[:, 0]):
                scalars[i] = objScalars[faceMap[faceMap[:, 0] == i,
                                                1]].sum(axis=0)

            """
            Add all scalars
            """
            self.faceScalars = self.faceScalars + scalars

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

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

        """
        with self.tempCoordSys(self.CYLINDER):
            dropCut = (-2 * np.pi / 10 < y) & (y < 2 * np.pi / 10)
            if mirrorZ:
                dropCut = dropCut & (z > 0)
            dropCutMask = self.getMask(dropCut)
            faceKeepMask = self.getFaceMask(dropCutMask)
            excludedMesh = self.copy()
            self.removeFaces(~faceKeepMask)
            excludedMesh.removeFaces(faceKeepMask)
            # remove 0 faces to be faster
            from sympy.abc import s
            zeroMask = tfields.getMask(excludedMesh.faceScalars,
                                       cutExpression=(s == 0),
                                       coords=[s] * excludedMesh.getScalarDepth())
            excludedMesh.removeFaces(zeroMask)

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

        self.stackScalars(centroidSF)

    def pickScalars(self, *scalarIndices):
        """
        Reduces the faceScalars to only the indices given.
        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]])
            >>> m.pickScalars(1, 3, 4)
            >>> m.faceScalars
            array([[ 2.,  4.,  5.],
                   [ 7.,  9.,  0.]])

        """
        self.faceScalars = self.faceScalars[:, list(scalarIndices)]

    def pointsInMesh(self, points, delta, method='baryc', assignMultiple=False):
        """
        Check whether points lie within triangles with Barycentric Technique
        """
        masks = self.triangles.pointsInTriangles(points, delta, method='baryc',
                                                 assignMultiple=assignMultiple)
        return masks

    def convertNaN(self, value=0.):
        super(Mesh3D, self).convertNaN(value)
        nanIndicesScalars = np.isnan(self.faceScalars)
        self.faceScalars[nanIndicesScalars] = value

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

        if isinstance(cutExpression, list):
            if scalarIndex is not None:
                raise ValueError("scalarIndex must be None, "
                                 "if cutExpression is list of cutExpressions")
            if not len(cutExpression) == inst.getScalarDepth():
                raise ValueError("lenght of cutExpression must meet scalar depth")
            for si, ce in enumerate(cutExpression):
                inst.cutScalars(ce, coords=coords,
                                replaceValue=replaceValue,
                                scalarIndex=si, inplace=True)
        else:
            if coords is None:
                freeSymbols = cutExpression.free_symbols
                if len(freeSymbols) > 1:
                    raise ValueError('coords must be given if multiple variables are given')
                elif len(freeSymbols) == 0:
                    raise NotImplementedError("Expressiongs like {cutExpression} "
                                              "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]

                maskBelow = tfields.getMask(scalarArrays,
                                            cutExpression=cutExpression,
                                            coords=[coords[scalarIndex]])
                scalarArrays[maskBelow] = replaceValue
                inst.faceScalars[:, scalarIndex:scalarIndex + 1] = scalarArrays
            else:
                maskBelow = tfields.getMask(scalarArrays,
                                            cutExpression=cutExpression,
                                            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
            >>> vertexMask = m.getMask(z < 6)
            >>> 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)
        indices = np.array(range(self.getNPoints()))
        deleteIndices = set(indices[~mask])  # set speeds up everything
        for i, face in enumerate(self.faces):
            for index in face:
                if index in deleteIndices:
                    faceDeleteMask[i] = True
                    break

        return ~faceDeleteMask

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

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

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

        # correct faces:
        deleteIndices = np.arange(self.getNPoints())[vertexDeleteMask]
        for p in deleteIndices:
            moveUpCounter[self.faces > p] -= 1

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

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

        Returns:
            copy of self without stale vertices and duplicat points
        """
        log = logger.new()
        log.verbose("Cleaning up.")
        # remove stale vertices
        if stale:
            vertexDeleteMask = self.staleVertices()
        else:
            vertexDeleteMask = np.full(self.shape[0], False, dtype=bool)
        # remove duplicates in order to not have any artificial separations
        inst = self
        if duplicates:
            inst = self.copy()
            log.verbose("Finding Duplicates")
            dups = tfields.duplicates(self, axis=0)
            for i, dupi in zip(range(self.shape[0]), dups):
                if dupi != i:
                    log.verbose("Found Duplicate point @ index {0}".format(i))
                    vertexDeleteMask[i] = True
                    # redirect faces
                    log.verbose("Run trough all faces to let it point to the"
                                "original")
                    for f in range(self.getNFaces()):
                        if i in self.faces[f]:
                            index = tfields.index(self.faces[f], i)
                            inst.faces[f][index] = dupi

        return inst.getRemovedVertices(vertexDeleteMask)

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

    def getScalarMap(self, mask):
        """
        Return copy of self without vertices where mask is True
        Copy because self is immutable
        """
        # built instance that only contains the vaild points
        faceKeepMask = self.getFaceMask(mask)
        scalarMap = np.arange(self.getNFaces())[faceKeepMask]
        return scalarMap

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

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

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

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

        for ind in faceIndices:
            faceMask[ind] = True

        self.removeFaces(~faceMask)

    def staleVertices(self):
        """
        Returns:
            Mask for all vertices that are stale i.e. are not refered by faces
        """
        staleMask = np.full(self.getNPoints(), False, dtype=bool)
        used = set(self.faces.flatten())
        for i in range(self.getNPoints()):
            if i not in used:
                staleMask[i] = True
        return staleMask

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

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

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

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

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

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

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

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

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

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

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

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

        faceIndices = list(self._inputToFaceIndices(seedFace))

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

        norms = self.triangles.getNormVectors()
        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.