mesh3D.py 69.3 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
39
40
41
42
43
44
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):
    return [tfields.TensorFields(faces, *fields, dtype=int)]

def maps_to_faces(maps):
    return maps[0]


45
46
47
48
49
50
class Mesh3D(tfields.TensorMaps):
    # pylint: disable=R0904
    """
    Points3D child used as vertices combined with faces to build a geometrical mesh of triangles
    Examples:
        >>> m = tfields.Mesh3D([[1,2,3], [3,3,3], [0,0,0], [5,6,7]], faces=[[0, 1, 2], [1, 2, 3]])
51
52
53
54
55
56
57
        >>> m.equal([[1, 2, 3],
        ...          [3, 3, 3],
        ...          [0, 0, 0],
        ...          [5, 6, 7]])
        True
        >>> m.faces.equal([[0, 1, 2], [1, 2, 3]])
        True
58
59

        conversion to points only
60
61
62
63
64
        >>> tfields.Points3D(m).equal([[1, 2, 3],
        ...                            [3, 3, 3],
        ...                            [0, 0, 0],
        ...                            [5, 6, 7]])
        True
65
66
67
68
69
70
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]]);
        >>> m.triangles
        Triangles3D([[ 1.,  0.,  0.],
                     [ 0.,  1.,  0.],
                     [ 0.,  0.,  0.]])

        a list of scalars is assigned to each face
77
78
79
        >>> 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
80
81

        adding together two meshes:
82
        >>> m2 = tfields.Mesh3D([[1,0,0],[2,0,0],[0,3,0]], faces=[[0,1,2]], faceScalars=[.7])
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
        >>> msum = tfields.Mesh3D([mScalar, m2])
        >>> msum
        Mesh3D([[ 1.,  0.,  0.],
                [ 0.,  1.,  0.],
                [ 0.,  0.,  0.],
                [ 1.,  0.,  0.],
                [ 2.,  0.,  0.],
                [ 0.,  3.,  0.]])
        >>> msum.faces
        array([[0, 1, 2],
               [3, 4, 5]])

        Saving and reading
        >>> from tempfile import NamedTemporaryFile
        >>> outFile = NamedTemporaryFile(suffix='.npz')
        >>> m.savez(outFile.name)
        >>> _ = outFile.seek(0)
        >>> m1 = tfields.Mesh3D.createFromFile(outFile.name)
        >>> bool(np.all(m == m1))
        True
        >>> m1.faces
        array([[0, 1, 2]])

    """
    def __new__(cls, tensors, **kwargs):
108
        fields = kwargs.pop('fields', [])
109
110
        if not issubclass(type(tensors), Mesh3D):
            kwargs['dim'] = 3
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
140
141
142
143
144
145
146
        faces = kwargs.pop('faces', None)
        faceScalars = kwargs.pop('faceScalars', [])
        maps = kwargs.pop('maps', None)
        if maps and faces:
            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
    def faceScalars(self, faceScalars):
        self.maps[0].faces = scalars_to_fields(faceScalars)
147
148
149
150
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351

    @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([])
        return tfields.Triangles3D(self[self.faces.flatten()], triangleScalars=self.faceScalars)

    @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()

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

    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):
        """
352
353
354
355
356
            >>> 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]])
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
            >>> 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.
        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)]
            >>> mesh = tfields.Mesh3D.createMeshGrid(*base).cleaned()

            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

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

    def getMeshMap(self, subMesh, delta=1e-9):
        """
        Returns:
            Mesh3D: meshMap (see mapToCut), can be used as meshMap to retrieve
                subMesh from self instance
        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
            >>> mCut, mapMesh = m.mapToCut(y < 1.5, atIntersection='split')
            >>> mm = m.getMeshMap(mCut)
            >>> bool((mm == mapMesh).all())
            True
            >>> bool((mm.faceScalars == mapMesh.faceScalars).all())
            True
            >>> bool((mm.faces == mapMesh.faces).all())
            True

        """
        # log = logger.new()
        faceIndices = np.arange(self.faces.shape[0])
        cents = tfields.Points3D(subMesh.getCentroids())
        scalars = []
        # nCents = cents.shape[0]
        # for i in range(nCents):
        #     faceMask = self.pointsInMesh(cents[i: i + 1], delta=delta)[0]
        #     if True not in faceMask:
        #         log.warning("No point face was assigned to this. I will retry.")
        #         faceMask = self.pointsInMesh(cents[i: i + 1], delta=delta * 100)[0]
        #         if True not in faceMask:
        #             raise ValueError()
        #     else:
        #         log.info("Centroid {i} / {nCents}".format(**locals()))
        #     scalars.append(faceIndices[faceMask])
        mask = self.pointsInMesh(cents, delta=delta)
        scalars = [faceIndices[faceMask] for faceMask in mask]
        inst = subMesh.copy()
        inst.setScalarArray(0, scalars)
        return inst


    def _distFromPlane(self, point, plane):
        return plane['normal'].dot(point) + plane['d']

    def _getSegmentPlaneIntersection(self, p0, p1, plane):
        distance0 = self._distFromPlane(p0, plane)
        distance1 = self._distFromPlane(p1, plane)
        p0OnPlane = abs(distance0) < np.finfo(float).eps
        p1OnPlane = abs(distance1) < np.finfo(float).eps
        outPoints = []
        direction = 0
        if p0OnPlane:
            outPoints.append(p0)

        if p1OnPlane:
            outPoints.append(p1)
        # remove duplicate points
        if len(outPoints) > 1:
            outPoints = tfields.Points3D(np.unique(outPoints, axis=0))
        if p0OnPlane and p1OnPlane:
            return outPoints, direction

        if distance0 * distance1 > np.finfo(float).eps:
            return outPoints, direction

        direction = np.sign(distance0)
        if abs(distance0) < np.finfo(float).eps:
            return outPoints, direction
        elif abs(distance1) < np.finfo(float).eps:
            return outPoints, direction
        if abs(distance0 - distance1) > np.finfo(float).eps:
            t = distance0 / (distance0 - distance1)
        else:
            return outPoints, direction

        outPoints.append(p0 + t * (p1 - p0))
        # remove duplicate points
        if len(outPoints) > 1:
            outPoints = tfields.Points3D(np.unique(outPoints, axis=0))
        return outPoints, direction

    def _intersect(self, triangle, plane, facePointsRejected):
        nTrue = facePointsRejected.count(True)
        lonelyBool = True if nTrue == 1 else False
        index = facePointsRejected.index(lonelyBool)
        s0, d0 = self._getSegmentPlaneIntersection(triangle[0], triangle[1], plane)
        s1, d1 = self._getSegmentPlaneIntersection(triangle[1], triangle[2], plane)
        s2, d2 = self._getSegmentPlaneIntersection(triangle[2], triangle[0], plane)

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

        # TODO handle special cases. For now triangles with at least two points on plane are excluded
        newPoints = 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 lonelyBool:
            # one new triangle
            if len(s0) == 1 and len(s1) == 1:
                newPoints = 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:
                newPoints = 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:
                newPoints = 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:
                newPoints = np.array([singlePoint, s0[0], s1[0]])
                faces = np.array([[0, 2, 1]])
            elif len(s1) == 1 and len(s2) == 1:
                newPoints = np.array([singlePoint, s1[0], s2[0]])
                faces = np.array([[0, 2, 1]])
            elif len(s0) == 1 and len(s2) == 1:
                newPoints = np.array([singlePoint, s0[0], s2[0]])
                faces = np.array([[0, 1, 2]])
            else:
                return None, None
        return newPoints, faces

    def mapToCut(self, cutOrMeshMap, coordSys=None, atIntersection="remove"):
        """
        Partition the mesh with the cuts given
        Args:
            cutOrMeshMaps (cutExpression or meshMap):
                if cutOrMeshMap is a cutExpression: cut like in self.cut but also return
                a map from new to old faces
                if cutOrMeshMap is a meshMap: map without cutting according to the map given
            coordSys (str): coordSys for cutExpression
            atIntersection (str): option switch for cutExpression (see
                tfields.Mesh3D.cut)
        Examples:
            Cut away the first face / select the last face only
            >>> m = tfields.Mesh3D([[1,2,3], [3,3,3], [0,0,0], [5,6,7]],
            ...            faces=[[0, 1, 2], [1, 2, 3]],
            ...            faceScalars=[[1,2], [6,7]])
            >>> mNew = tfields.Mesh3D([[3,3,3], [0,0,0], [5,6,7]], [[0, 1, 2]], faceScalars=[[1]])
            >>> mCut, _ = m.mapToCut(mNew)
            >>> mCut.faceScalars
            array([[ 6.,  7.]])

            Cut with condition will return the manual/instruction on how to
            conduct the cut fast (mapMesh)
            >>> from sympy.abc import y
            >>> m = tfields.Mesh3D([[0,0,0], [1,0,0], [1,1,0], [0,1,0], [0,2,0], [1,2,0]],
            ...            faces=[[0,1,2],[2,3,0],[3,2,5],[5,4,3]],
            ...            faceScalars=[[1],[2],[3],[4]])
            >>> mCut, mapMesh = m.mapToCut(y < 1.5, atIntersection='split')
            >>> mCut.faceScalars.T
            array([[ 1.,  2.,  3.,  3.,  4.]])

            Applying the mapMesh results in the same result as applying the cut
            with the condition
            >>> mCut2, _ = m.mapToCut(mapMesh)
            >>> bool((mCut == mCut2).all())
            True
            >>> bool((mCut.faceScalars == mCut2.faceScalars).all())
            True

        """
        cutExpression = None
        meshMap = None
        # check what cutOrMeshMap is and set it
        if isinstance(cutOrMeshMap, Mesh3D):
            meshMap = cutOrMeshMap
        else:
            cutExpression = cutOrMeshMap

        if cutExpression is not None:
            eps = 0.000000001
            # direct return if self is empty
            if len(self) == 0:
                return self.copy(), self.copy()

            # mask for points that do not fulfill the cut expression
            mask = self.getMask(cutExpression, coordSys=coordSys)
            # remove the points
            inst = self.getRemovedVertices(~mask)
            scalarMap = self.getScalarMap(mask)
            scalarMap = scalarMap.reshape((-1, 1)).astype(float)

            if not any(~mask):
                # no faces have been removed.
                return inst, Mesh3D([inst], faceScalars=scalarMap)

            if all(~mask):
                # all faces have been removed)
                return inst, inst.copy()

            # add points and faces intersecting with the plane
            if atIntersection == 'split' or atIntersection == 'splitRough':
                cutExpressionParts = symTools.getExpressionParts(cutExpression)
                if len(cutExpressionParts) > 1:
                    onEdgeMesh = self.copy()
                    if atIntersection == 'splitRough':
                        """
                        the following is, to speed up the process. Problem is, that
                        triangles can exist, where all points lie outside the cut,
                        but part of the area
                        still overlaps with the cut.
                        These are at the intersection line between two cuts.
                        """
                        faceIntersMask = np.full((self.faces.shape[0]), False, dtype=bool)
                        for i, face in enumerate(self.faces):
                            facePointsRejected = [-mask[f] for f in face]
                            faceOnEdge = any(facePointsRejected) and not all(facePointsRejected)
                            if faceOnEdge:
                                faceIntersMask[i] = True
                        onEdgeMesh.removeFaces(-faceIntersMask)

                    for exprPart in cutExpressionParts:
                        onEdgeMesh = onEdgeMesh.cut(exprPart, atIntersection='split')
                    newMesh = onEdgeMesh
                elif len(cutExpressionParts) == 1:

                    points = [sympy.symbols('x0, y0, z0'), sympy.symbols('x1, y1, z1'), sympy.symbols('x2, y2, z2')]
                    fpr = sympy.symbols('fpr2, fpr1, fpr2')
                    planeSympy = symTools.getPlane(cutExpression)
                    n = np.array(planeSympy.normal_vector).astype(float)
                    d = -n.dot(np.array(planeSympy.p1).astype(float))
                    plane = {'normal': n, 'd': d}

                    normVectors = self.getNormVectors()
                    newPoints = np.empty((0, 3))
                    newFaces = np.empty((0, 3))
                    newFaceScalars = []
                    newNormVectors = []
                    newScalarMap = []
                    nNew = 0
                    for i, face in enumerate(self.faces):
                        """
                        facePointsRejected is a mask for each face that is True, where
                        a Point is on the rejected side of the plane
                        """
                        facePointsRejected = [~mask[f] for f in face]
                        faceOnEdge = any(facePointsRejected) and not all(facePointsRejected)
                        if faceOnEdge:
                            """
                            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)
                            """
                            nTrue = facePointsRejected.count(True)
                            # the bool that occures on
                            lonelyBool = True if nTrue == 1 else False

                            triangle_points = [self[f] for f in face]
                            """
                            Add the intersection points and faces
                            """
                            # tick = time()
                            if lonelyBool:
                                # singlePoint on cut away side
                                newP, newF = self._intersect(triangle_points, plane, facePointsRejected)
                                if newP is not None:
                                    newP = np.array(newP)
                                    np.place(newP, np.logical_and(0 < newP, newP <= eps), 0.0)
                                    newPoints = np.concatenate((newPoints, newP))
                                    newFaces = np.concatenate((newFaces, newF + nNew))
                                    newFaceScalars.extend([self.faceScalars[i]] * 2)
                                    newNormVectors.extend([normVectors[i]] * 2)
                                    newScalarMap.extend([i] * 2)
                                    nNew += 4
                                else:
                                    pass
                            else:
                                # singlePoint on keep side
                                newP, newF = self._intersect(triangle_points, plane, facePointsRejected)
                                if newP is not None:
                                    newP = np.array(newP)
                                    np.place(newP, np.logical_and(0 < newP, newP <= eps), 0.0)
                                    newPoints = np.concatenate((newPoints, newP))
                                    newFaces = np.concatenate((newFaces, newF + nNew))
                                    newFaceScalars.extend([self.faceScalars[i]] * 1)
                                    newNormVectors.extend([normVectors[i]] * 1)
                                    newScalarMap.extend([i])
                                    nNew += 3
                                else:
                                    pass

                    newPoints = [[float(p[0]), float(p[1]), float(p[2])] for p in newPoints]
                    newMesh = self.__class__(newPoints, faces=newFaces,
                                             coordSys=inst.getCoordSys(),
                                             faceScalars=newFaceScalars)
                    newMesh.alignNormVectors(newNormVectors)
                    newScalarMap = np.array(newScalarMap).reshape((-1, 1)).astype(float)
                    scalarMap = np.concatenate((scalarMap, newScalarMap))
                    inst = self.__class__([inst, newMesh])
                else:
                    raise ValueError("CutExpression is not splitable.")

            elif atIntersection == 'remove':
                pass
            else:
                raise AttributeError("No atIntersection method called {atIntersection} "
                                     "implemented".format(**locals()))
            meshMap = inst.copy()
            meshMap.faceScalars = scalarMap
        elif meshMap is not None:
            if coordSys is not None or atIntersection != "remove":
                log = logger.new()
                log.warning("coordSys and atIntersection arguments are not default.")
            if len(meshMap) > 0:
                inst = Mesh3D(meshMap,
                              faces=meshMap.faces,
                              faceScalars=self.faceScalars[meshMap.getScalarArrays()[0].astype(int)],
                              coordSys=meshMap.coordSys)
            else:
                inst = Mesh3D([])
        else:
            raise TypeError("cutOrMeshMap is not understood.")
        return inst, meshMap

    def cut(self, cutExpression, coordSys=None, atIntersection="remove"):
        """
        cut method for Mesh3D.
        If the same cut to the same mesh should be applied multiple times with different scalars:
        use mapToCut!
        Args:
            see Points3D.cut
            additionally:

            atIntersection (str): instruction on what to do, when a cut will intersect a triangle.
                Options:    "remove" (Default)
                            "split" - Create new triangles that make up the old one.

        Examples:
            define the cut
            >>> from sympy.abc import x,y,z
            >>> cutExpr = x > 1.5

            >>> m = tfields.Mesh3D.createMeshGrid(np.linspace(0,3,4),
            ...                           np.linspace(0,3,4),
            ...                           np.linspace(0, 0, 1), faceScalars=np.linspace(4, 8, 18))
            >>> mNew = m.cut(cutExpr)
            >>> mNew.getNPoints()
            8
            >>> mNew.getNFaces()
            6
            >>> float(mNew[:, 0].min())
            2.0

            Cutting with the split option will create new triangles on the edge:
            >>> mSplit = m.cut(cutExpr, atIntersection='split')
            >>> float(mSplit[:, 0].min())
            1.5
            >>> mSplit.getNPoints()
            29
            >>> mSplit.getNFaces()
            15

            Cuttin with a sympy BooleanFunction:
            >>> cutExprBoolFun = (x > 1.5) & (y < 1.5) & (y >0.2) & (z > -0.5)
            >>> mSplit = m.cut(cutExprBoolFun, atIntersection='split')

        Returns:
            copy of cut mesh

        """
        inst, _ = self.mapToCut(cutExpression, coordSys=coordSys, atIntersection=atIntersection)
        return inst

    def _clusterDbscan(self, maxClusterDist=15, minSamples=20, outType=None):
        """
        runs DBSCAN alcorithm to find seperate mesh clusters
        KwArgs:
            outType (type): type of cluster-points. E.g. np.array / Points3D / list...
        Returns:
            clusters (list of pointsLists), excludedPoints (pointsList)
        """
        raise NotImplementedError("")
        clusters = [None]
        excluded = None
        return clusters, excluded

    def _clusterBox(self,
                    min0=None, max0=None, nSections0=None,
                    min1=None, max1=None, nSections1=None,
                    min2=None, max2=None, nSections2=None,
                    clusterMeshes=None, outType=None, cutTree=False, withTransform=False, **cutKwargs):
        log = logger.new()

        if withTransform:
            targetMesh, transformation, translate = self.transformDirections()
        else:
            targetMesh = self
            transformation = np.eye(3)
            translate = np.zeros(3, )

        if cutTree and (clusterMeshes is None):
            minmax = np.array([[min0, min1, min2], [max0, max1, max2]])
            xRange = list(np.linspace(minmax[0,0], minmax[1,0], nSections0 + 1))[1:-1]
            yRange = list(np.linspace(minmax[0,1], minmax[1,1], nSections1 + 1))[1:-1]
            zRange = list(np.linspace(minmax[0,2], minmax[1,2], nSections2 + 1))[1:-1]
            cuts = {'x': xRange, 'y': yRange, 'z': zRange}
            box = {'x': minmax[:,0], 'y': minmax[:,1], 'z': minmax[:,2]}
            log.info("Start creating cutting tree")
            atIntersection = cutKwargs.get('atIntersection', 'remove')
            cutTree = cuttingTree.Node(parent=None, mesh=targetMesh, remainingCuts=cuts,
                                       atIntersection=atIntersection, box=box)
            log.info("Done building the tree structure")

            leaves = cutTree.findLeaves()
            leaves = cuttingTree.Node.sortLeaves(leaves)

            clusterMeshes = [leaf.getGlobalCutMesh() for leaf in leaves]
            clusteredObjs = [leaf.mesh for leaf in leaves]

            # TODO exclude Mesh
            excludedObjs = Mesh3D([])
        else:
            clusteredObjs, excludedObjs, clusterMeshes, transformation = super(Mesh3D, self)._clusterBox(min0=min0, max0=max0,
                                                                                         nSections0=nSections0,
                                                                                         min1=min1, max1=max1,
                                                                                         nSections1=nSections1,
                                                                                         min2=min2, max2=max2,
                                                                                         nSections2=nSections2,
                                                                                         clusterMeshes=clusterMeshes,
                                                                                         outType=outType,
                                                                                         withTransform=withTransform,
                                                                                         **cutKwargs)
        return clusteredObjs, excludedObjs, clusterMeshes, transformation

    def _minimum_bounding_rectangle(self, points2D):
        """
        Find the smallest bounding rectangle for a set of points.
        Returns a set of points representing the corners of the bounding box.

        :param points: an nx2 matrix of coordinates
        :rval: an nx2 matrix of coordinates
        """
        from scipy.ndimage.interpolation import rotate
        pi2 = np.pi / 2.

        # get the convex hull for the points
        hull_points = points2D[ConvexHull(points2D).vertices]

        # calculate edge angles
        edges = np.zeros((len(hull_points) - 1, 2))
        edges = hull_points[1:] - hull_points[:-1]

        angles = np.zeros((len(edges)))
        angles = np.arctan2(edges[:, 1], edges[:, 0])

        angles = np.abs(np.mod(angles, pi2))
        angles = np.unique(angles)

        # find rotation matrices
        # XXX both work
        rotations = np.vstack([
            np.cos(angles),
            np.cos(angles - pi2),
            np.cos(angles + pi2),
            np.cos(angles)]).T
        #     rotations = np.vstack([
        #         np.cos(angles),
        #         -np.sin(angles),
        #         np.sin(angles),
        #         np.cos(angles)]).T
        rotations = rotations.reshape((-1, 2, 2))

        # apply rotations to the hull
        rot_points = np.dot(rotations, hull_points.T)

        # find the bounding points
        min_x = np.nanmin(rot_points[:, 0], axis=1)
        max_x = np.nanmax(rot_points[:, 0], axis=1)
        min_y = np.nanmin(rot_points[:, 1], axis=1)
        max_y = np.nanmax(rot_points[:, 1], axis=1)

        # find the box with the best area
        areas = (max_x - min_x) * (max_y - min_y)
        best_idx = np.argmin(areas)

        # return the best box
        x1 = max_x[best_idx]
        x2 = min_x[best_idx]
        y1 = max_y[best_idx]
        y2 = min_y[best_idx]
        r = rotations[best_idx]

        rval = np.zeros((4, 2))
        rval[0] = np.dot([x1, y2], r)
        rval[1] = np.dot([x2, y2], r)
        rval[2] = np.dot([x2, y1], r)
        rval[3] = np.dot([x1, y1], r)

        return rval, r

    def transformDirections(self):
        """
        Transforms the coordinate system such that it faces towards the mean of all triangle normals.
        This only works if the triangle normals mean is a reasonable choice for the problem.
        An improved version in the future should consider to weight the normals by triangle area
        The minimal value in this coordinate system is 0, the maximal value is 1
        :param inMesh: input mesh that the transformation is based on
        :return: normalized mesh with transformed vertices, faces and faceScalars as in inMesh,
        tranformationMatrix and translate transforms the normalizedMesh back to its original shape
        """

        zNormal = np.array([0.0, 0.0, 1.0])
        meanNormal = np.mean(self.getNormVectors(), axis=0)
        meanNormal = meanNormal / np.linalg.norm(meanNormal)

        cosMeanNormalZ = meanNormal.dot(zNormal)
        if cosMeanNormalZ == -1.0:
            # mean normal points in opposite direction as zNormal
            rotateMeanNormal = np.diag([1.0, 1.0, -1.0])
        elif cosMeanNormalZ == 1.0:
            # already in z direction
            rotateMeanNormal = np.eye(3)
        else:
            # calculate transformation matrix to let meanNormal be transformed to zNormal
            normalsCrossProduct = np.cross(zNormal, meanNormal)
            crossProductNorm = np.linalg.norm(normalsCrossProduct)
            cosMeanNormalZ = meanNormal.dot(zNormal)
            # skew-symmetric cross product matrix of normalsCrossProduct
            nux = np.array([[0, -normalsCrossProduct[2], normalsCrossProduct[1]],
                            [normalsCrossProduct[2], 0, -normalsCrossProduct[0]],
                            [-normalsCrossProduct[1], normalsCrossProduct[0], 0]])
            # formula found at
            # https://math.stackexchange.com/questions/180418/calculate-rotation-matrix-to-align-vector-a-to-vector-b-in-3d
            rotateMeanNormal = np.eye(3) + nux + nux.dot(nux) * (1 - cosMeanNormalZ) / (crossProductNorm ** 2)
        vertices3D = self.dot(rotateMeanNormal)
        unrotatedMesh = Mesh3D(vertices3D, faces=self.faces, faceScalars=self.faceScalars)

        vertices2D = vertices3D[:, :2]
        boundingRectangleVertices2D, rot = self._minimum_bounding_rectangle(vertices2D)

        rotatedRectangle = boundingRectangleVertices2D.dot(rot.T)

        # longer side rotated parallel to x-axis
        side0 = np.linalg.norm(rotatedRectangle[0, :] - rotatedRectangle[1, :])
        side1 = np.linalg.norm(rotatedRectangle[0, :] - rotatedRectangle[3, :])
        if side0 < side1:
            rot = rot.dot(np.array([[0, -1], [1, 0]]))
        rotMatrix3D = np.eye(3)
        rotMatrix3D[:2, :2] = rot.T

        vertices3D = vertices3D.dot(rotMatrix3D)

        # find mins and max for scaling
        mins = np.min(vertices3D, axis=0)
        maxs = np.max(vertices3D, axis=0)
        # scaling matrix
        scale = np.diag([1.0 / (ma - mi) if (abs(ma - mi) > np.finfo(float).eps) else 1.0
                         for ma, mi in zip(maxs, mins)])
        # translation vector
        translate = np.array([mi / (mi - ma) if (abs(ma - mi) > np.finfo(float).eps) else mi
                              for ma, mi in zip(maxs, mins)])
        normalizedVertices = vertices3D.dot(scale) + translate
        normalizedMesh = Mesh3D(normalizedVertices, faces=self.faces, faceScalars=self.faceScalars)
        tranformationMatrix = rotateMeanNormal.dot(rotMatrix3D.dot(scale))

        return normalizedMesh, tranformationMatrix, translate

    def alignNormVectors(self, normVectors):
        """
        Orientate the faces such, that their normVectors align to the normVectors given.
        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]]);
            >>> newNorms = m.getNormVectors() * -1
            >>> m.alignNormVectors(newNorms)
            >>> m.faces
            array([[0, 3, 1],
                   [1, 4, 3],
                   [1, 2, 3]])

        """
        if not self.getNFaces() == 0:
            # vector product < 0
            mask = np.einsum('...i,...i', self.getNormVectors(), normVectors) < 0
            """
            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

    def saveObj(self, filePath, **kwargs):
        """
        Save obj as wavefront/.obj file
        """
        obj = kwargs.pop('object', None)
        group = kwargs.pop('group', None)

        cmap = kwargs.pop('cmap', 'jet')
        faceScalarIndex = kwargs.pop('faceScalarIndex', None)

        filePath = filePath.replace('.obj', '')
        fileDir, fileName = os.path.split(filePath)

        if not (self.faceScalars.size == 0 or faceScalarIndex is None):
            scalars = self.faceScalars[:, faceScalarIndex]
            minScalar = scalars[-np.isnan(scalars)].min()
            maxScalar = scalars[-np.isnan(scalars)].max()
            vmin = kwargs.pop('vmin', minScalar)
            vmax = kwargs.pop('vmax', maxScalar)
            if vmin == vmax:
                if vmin == 0.:
                    vmax = 1.
                else:
                    vmin = 0.
            norm = colors.Normalize(vmin, vmax)
            colorMap = plt.get_cmap(cmap)
        else:
            # this is a switch for not coloring the triangles and thus not producing the materials
            norm = None

        if norm is not None:
            fileNameMat = fileName + '_frame_{0}.mat'.format(faceScalarIndex)
            scalars[np.isnan(scalars)] = minScalar - 1
            sortedScalars = scalars[scalars.argsort()]
            sortedScalars[sortedScalars == minScalar - 1] = np.nan
            sortedFaces = self.faces[scalars.argsort()]
            scalarSet = np.unique(sortedScalars)
            scalarSet[scalarSet == minScalar - 1] = np.nan
            with open(os.path.join(fileDir + fileNameMat), 'w') as mf:
                for s in scalarSet:
                    if np.isnan(s):
                        mf.write("newmtl nan")
                        mf.write("Kd 0 0 0\n\n")
                    else:
                        mf.write("newmtl mtl_{0}\n".format(s))
                        mf.write("Kd {c[0]} {c[1]} {c[2]}\n\n".format(c=colorMap(norm(s))))
        else:
            sortedFaces = self.faces

        # writing of the obj file
        with open(filePath + '.obj', 'w') as f:
            f.write("# File saved with tfields Mesh3D.saveObj method\n\n")
            if norm is not None:
                f.write("mtllib ./{0}\n\n".format(fileNameMat))
            if obj is not None:
                f.write("o {0}\n".format(obj))
            if group is not None:
                f.write("g {0}\n".format(group))
            for vertex in self:
                f.write("v {v[0]} {v[1]} {v[2]}\n".format(v=vertex))

            lastScalar = None
            for i, face in enumerate(sortedFaces + 1):
                if norm is not None:
                    if not lastScalar == sortedScalars[i]:
                        lastScalar = sortedScalars[i]
                        f.write("usemtl mtl_{0}\n".format(lastScalar))
                f.write("f {f[0]} {f[1]} {f[2]}\n".format(f=face))

    def plot(self, **kwargs):
        """
        Frowarding to plotTools.plotMesh
        """
        # old version with plotTools
        # import plotTools as pt
        # return pt.plotMesh(self, **kwargs)

        plotVertices = kwargs.pop('plotVertices', False)
        faceScalarIndex = kwargs.pop('faceScalarIndex', None)
        if faceScalarIndex is not None:
            warnings.warn("faceScalarIndex is renamed scalarIndex. Also default is not 0 any more.",
                          DeprecationWarning)
            kwargs['scalarIndex'] = kwargs.pop('scalarIndex', faceScalarIndex)

        scalarsDemanded = any([v in kwargs for v in ['vmin', 'vmax', 'cmap']])
        defaultScalarIndex = None if not scalarsDemanded else 0
        # defaultScalarIndex = None
        scalarIndex = kwargs.pop('scalarIndex', defaultScalarIndex)
        if scalarIndex is not None:
            if not self.faceScalars.shape[0] == 0:
                kwargs['color'] = self.faceScalars[:, scalarIndex]
        if plotVertices:
            return mplTools.plotArray(self, **kwargs)
        # deprecated dim=3 default. I want to go for 2 as everywhere
        dimDefined = False
        if 'axis' in kwargs:
            dimDefined = True
        if 'zAxis' in kwargs:
            if kwargs['zAxis'] is not None:
                kwargs['dim'] = 3
            else:
                kwargs['dim'] = 2
            dimDefined = True
        if 'dim' in kwargs:
            dimDefined = True

        if not dimDefined:
            warnings.warn("Dimension is not defined. I want to change"
                          " default dimension to 2. Keep 3 for now. "
                          "If you want 3 specify keyword 'dim'.",
                          DeprecationWarning)
            kwargs['dim'] = 3

        return mplTools.plotMesh(self, self.faces, **kwargs)


if __name__ == '__main__':
    import doctest

1756
1757
    doctest.run_docstring_examples(Mesh3D, globals())
    quit()
1758
    doctest.testmod()