Skip to content
Snippets Groups Projects
functions.py 70.9 KiB
Newer Older
  • Learn to ignore specific revisions
  • 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 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874
        Algorithm is taken from Gimp's color-to-alpha function in plug-ins/common/colortoalpha.c
        Credit:
            /*
            * Color To Alpha plug-in v1.0 by Seth Burgess, sjburges@gimp.org 1999/05/14
            *  with algorithm by clahey
            */
        
        """
        data = data.astype(float)
        if data.shape[-1] == 3:  ## add alpha channel if needed
            d2 = np.empty(data.shape[:2]+(4,), dtype=data.dtype)
            d2[...,:3] = data
            d2[...,3] = 255
            data = d2
        
        color = color.astype(float)
        alpha = np.zeros(data.shape[:2]+(3,), dtype=float)
        output = data.copy()
        
        for i in [0,1,2]:
            d = data[...,i]
            c = color[i]
            mask = d > c
            alpha[...,i][mask] = (d[mask] - c) / (255. - c)
            imask = d < c
            alpha[...,i][imask] = (c - d[imask]) / c
        
        output[...,3] = alpha.max(axis=2) * 255.
        
        mask = output[...,3] >= 1.0  ## avoid zero division while processing alpha channel
        correction = 255. / output[...,3][mask]  ## increase value to compensate for decreased alpha
        for i in [0,1,2]:
            output[...,i][mask] = ((output[...,i][mask]-color[i]) * correction) + color[i]
            output[...,3][mask] *= data[...,3][mask] / 255.  ## combine computed and previous alpha values
        
        #raise Exception()
        return np.clip(output, 0, 255).astype(np.ubyte)
        
    
    
    #def isosurface(data, level):
        #"""
        #Generate isosurface from volumetric data using marching tetrahedra algorithm.
        #See Paul Bourke, "Polygonising a Scalar Field Using Tetrahedrons"  (http://local.wasp.uwa.edu.au/~pbourke/geometry/polygonise/)
        
        #*data*   3D numpy array of scalar values
        #*level*  The level at which to generate an isosurface
        #"""
        
        #facets = []
        
        ### mark everything below the isosurface level
        #mask = data < level
        
        #### make eight sub-fields 
        #fields = np.empty((2,2,2), dtype=object)
        #slices = [slice(0,-1), slice(1,None)]
        #for i in [0,1]:
            #for j in [0,1]:
                #for k in [0,1]:
                    #fields[i,j,k] = mask[slices[i], slices[j], slices[k]]
        
        
        
        ### split each cell into 6 tetrahedra
        ### these all have the same 'orienation'; points 1,2,3 circle 
        ### clockwise around point 0
        #tetrahedra = [
            #[(0,1,0), (1,1,1), (0,1,1), (1,0,1)],
            #[(0,1,0), (0,1,1), (0,0,1), (1,0,1)],
            #[(0,1,0), (0,0,1), (0,0,0), (1,0,1)],
            #[(0,1,0), (0,0,0), (1,0,0), (1,0,1)],
            #[(0,1,0), (1,0,0), (1,1,0), (1,0,1)],
            #[(0,1,0), (1,1,0), (1,1,1), (1,0,1)]
        #]
        
        ### each tetrahedron will be assigned an index
        ### which determines how to generate its facets.
        ### this structure is: 
        ###    facets[index][facet1, facet2, ...]
        ### where each facet is triangular and its points are each 
        ### interpolated between two points on the tetrahedron
        ###    facet = [(p1a, p1b), (p2a, p2b), (p3a, p3b)]
        ### facet points always circle clockwise if you are looking 
        ### at them from below the isosurface.
        #indexFacets = [
            #[],  ## all above
            #[[(0,1), (0,2), (0,3)]],  # 0 below
            #[[(1,0), (1,3), (1,2)]],   # 1 below
            #[[(0,2), (1,3), (1,2)], [(0,2), (0,3), (1,3)]],   # 0,1 below
            #[[(2,0), (2,1), (2,3)]],   # 2 below
            #[[(0,3), (1,2), (2,3)], [(0,3), (0,1), (1,2)]],   # 0,2 below
            #[[(1,0), (2,3), (2,0)], [(1,0), (1,3), (2,3)]],   # 1,2 below
            #[[(3,0), (3,1), (3,2)]],   # 3 above
            #[[(3,0), (3,2), (3,1)]],   # 3 below
            #[[(1,0), (2,0), (2,3)], [(1,0), (2,3), (1,3)]],   # 0,3 below
            #[[(0,3), (2,3), (1,2)], [(0,3), (1,2), (0,1)]],   # 1,3 below
            #[[(2,0), (2,3), (2,1)]], # 0,1,3 below
            #[[(0,2), (1,2), (1,3)], [(0,2), (1,3), (0,3)]],   # 2,3 below
            #[[(1,0), (1,2), (1,3)]], # 0,2,3 below
            #[[(0,1), (0,3), (0,2)]], # 1,2,3 below
            #[]  ## all below
        #]
        
        #for tet in tetrahedra:
            
            ### get the 4 fields for this tetrahedron
            #tetFields = [fields[c] for c in tet]
            
            ### generate an index for each grid cell
            #index = tetFields[0] + tetFields[1]*2 + tetFields[2]*4 + tetFields[3]*8
            
            ### add facets
            #for i in xrange(index.shape[0]):                 # data x-axis
                #for j in xrange(index.shape[1]):             # data y-axis
                    #for k in xrange(index.shape[2]):         # data z-axis
                        #for f in indexFacets[index[i,j,k]]:  # faces to generate for this tet
                            #pts = []
                            #for l in [0,1,2]:      # points in this face
                                #p1 = tet[f[l][0]]  # tet corner 1
                                #p2 = tet[f[l][1]]  # tet corner 2
                                #pts.append([(p1[x]+p2[x])*0.5+[i,j,k][x]+0.5 for x in [0,1,2]]) ## interpolate between tet corners
                            #facets.append(pts)
    
        #return facets
        
    
    def isocurve(data, level, connected=False, extendToEdge=False, path=False):
        """
        Generate isocurve from 2D data using marching squares algorithm.
        
        ============= =========================================================
        Arguments
        data          2D numpy array of scalar values
        level         The level at which to generate an isosurface
        connected     If False, return a single long list of point pairs
                      If True, return multiple long lists of connected point 
                      locations. (This is slower but better for drawing 
                      continuous lines)
        extendToEdge  If True, extend the curves to reach the exact edges of 
                      the data. 
        path          if True, return a QPainterPath rather than a list of 
                      vertex coordinates. This forces connected=True.
        ============= =========================================================
        
        This function is SLOW; plenty of room for optimization here.
        """    
        
        if path is True:
            connected = True
        
        if extendToEdge:
            d2 = np.empty((data.shape[0]+2, data.shape[1]+2), dtype=data.dtype)
            d2[1:-1, 1:-1] = data
            d2[0, 1:-1] = data[0]
            d2[-1, 1:-1] = data[-1]
            d2[1:-1, 0] = data[:, 0]
            d2[1:-1, -1] = data[:, -1]
            d2[0,0] = d2[0,1]
            d2[0,-1] = d2[1,-1]
            d2[-1,0] = d2[-1,1]
            d2[-1,-1] = d2[-1,-2]
            data = d2
        
        sideTable = [
        [],
        [0,1],
        [1,2],
        [0,2],
        [0,3],
        [1,3],
        [0,1,2,3],
        [2,3],
        [2,3],
        [0,1,2,3],
        [1,3],
        [0,3],
        [0,2],
        [1,2],
        [0,1],
        []
        ]
        
        edgeKey=[
        [(0,1), (0,0)],
        [(0,0), (1,0)],
        [(1,0), (1,1)],
        [(1,1), (0,1)]
        ]
        
        
        lines = []
        
        ## mark everything below the isosurface level
        mask = data < level
        
        ### make four sub-fields and compute indexes for grid cells
        index = np.zeros([x-1 for x in data.shape], dtype=np.ubyte)
        fields = np.empty((2,2), dtype=object)
        slices = [slice(0,-1), slice(1,None)]
        for i in [0,1]:
            for j in [0,1]:
                fields[i,j] = mask[slices[i], slices[j]]
                #vertIndex = i - 2*j*i + 3*j + 4*k  ## this is just to match Bourk's vertex numbering scheme
                vertIndex = i+2*j
                #print i,j,k," : ", fields[i,j,k], 2**vertIndex
                index += fields[i,j] * 2**vertIndex
                #print index
        #print index
        
        ## add lines
        for i in range(index.shape[0]):                 # data x-axis
            for j in range(index.shape[1]):             # data y-axis     
                sides = sideTable[index[i,j]]
                for l in range(0, len(sides), 2):     ## faces for this grid cell
                    edges = sides[l:l+2]
                    pts = []
                    for m in [0,1]:      # points in this face
                        p1 = edgeKey[edges[m]][0] # p1, p2 are points at either side of an edge
                        p2 = edgeKey[edges[m]][1]
                        v1 = data[i+p1[0], j+p1[1]] # v1 and v2 are the values at p1 and p2
                        v2 = data[i+p2[0], j+p2[1]]
                        f = (level-v1) / (v2-v1)
                        fi = 1.0 - f
                        p = (    ## interpolate between corners
                            p1[0]*fi + p2[0]*f + i + 0.5, 
                            p1[1]*fi + p2[1]*f + j + 0.5
                            )
                        if extendToEdge:
                            ## check bounds
                            p = (
                                min(data.shape[0]-2, max(0, p[0]-1)),
                                min(data.shape[1]-2, max(0, p[1]-1)),                        
                            )
                        if connected:
                            gridKey = i + (1 if edges[m]==2 else 0), j + (1 if edges[m]==3 else 0), edges[m]%2
                            pts.append((p, gridKey))  ## give the actual position and a key identifying the grid location (for connecting segments)
                        else:
                            pts.append(p)
                    
                    lines.append(pts)
    
        if not connected:
            return lines
                    
        ## turn disjoint list of segments into continuous lines
    
        #lines = [[2,5], [5,4], [3,4], [1,3], [6,7], [7,8], [8,6], [11,12], [12,15], [11,13], [13,14]]
        #lines = [[(float(a), a), (float(b), b)] for a,b in lines]
        points = {}  ## maps each point to its connections
        for a,b in lines:
            if a[1] not in points:
                points[a[1]] = []
            points[a[1]].append([a,b])
            if b[1] not in points:
                points[b[1]] = []
            points[b[1]].append([b,a])
    
        ## rearrange into chains
        for k in points.keys():
            try:
                chains = points[k]
            except KeyError:   ## already used this point elsewhere
                continue
            #print "===========", k
            for chain in chains:
                #print "  chain:", chain
                x = None
                while True:
                    if x == chain[-1][1]:
                        break ## nothing left to do on this chain
                        
                    x = chain[-1][1]
                    if x == k:  
                        break ## chain has looped; we're done and can ignore the opposite chain
                    y = chain[-2][1]
                    connects = points[x]
                    for conn in connects[:]:
                        if conn[1][1] != y:
                            #print "    ext:", conn
                            chain.extend(conn[1:])
                    #print "    del:", x
                    del points[x]
                if chain[0][1] == chain[-1][1]:  # looped chain; no need to continue the other direction
                    chains.pop()
                    break
                    
    
        ## extract point locations 
        lines = []
        for chain in points.values():
            if len(chain) == 2:
                chain = chain[1][1:][::-1] + chain[0]  # join together ends of chain
            else:
                chain = chain[0]
            lines.append([p[0] for p in chain])
        
        if not path:
            return lines ## a list of pairs of points
        
        path = QtGui.QPainterPath()
        for line in lines:
            path.moveTo(*line[0])
            for p in line[1:]:
                path.lineTo(*p)
        
        return path
        
        
    def traceImage(image, values, smooth=0.5):
        """
        Convert an image to a set of QPainterPath curves.
        One curve will be generated for each item in *values*; each curve outlines the area
        of the image that is closer to its value than to any others.
        
        If image is RGB or RGBA, then the shape of values should be (nvals, 3/4)
        The parameter *smooth* is expressed in pixels.
        """
        import scipy.ndimage as ndi
        if values.ndim == 2:
            values = values.T
        values = values[np.newaxis, np.newaxis, ...].astype(float)
        image = image[..., np.newaxis].astype(float)
        diff = np.abs(image-values)
        if values.ndim == 4:
            diff = diff.sum(axis=2)
            
        labels = np.argmin(diff, axis=2)
        
        paths = []
        for i in range(diff.shape[-1]):    
            d = (labels==i).astype(float)
            d = ndi.gaussian_filter(d, (smooth, smooth))
            lines = isocurve(d, 0.5, connected=True, extendToEdge=True)
            path = QtGui.QPainterPath()
            for line in lines:
                path.moveTo(*line[0])
                for p in line[1:]:
                    path.lineTo(*p)
            
            paths.append(path)
        return paths
        
        
        
    IsosurfaceDataCache = None
    def isosurface(data, level):
        """
        Generate isosurface from volumetric data using marching cubes algorithm.
        See Paul Bourke, "Polygonising a Scalar Field"  
        (http://paulbourke.net/geometry/polygonise/)
        
        *data*   3D numpy array of scalar values
        *level*  The level at which to generate an isosurface
        
        Returns an array of vertex coordinates (Nv, 3) and an array of 
        per-face vertex indexes (Nf, 3)    
        """
        ## For improvement, see:
        ## 
        ## Efficient implementation of Marching Cubes' cases with topological guarantees.
        ## Thomas Lewiner, Helio Lopes, Antonio Wilson Vieira and Geovan Tavares.
        ## Journal of Graphics Tools 8(2): pp. 1-15 (december 2003)
        
        ## Precompute lookup tables on the first run
        global IsosurfaceDataCache
        if IsosurfaceDataCache is None:
            ## map from grid cell index to edge index.
            ## grid cell index tells us which corners are below the isosurface,
            ## edge index tells us which edges are cut by the isosurface.
            ## (Data stolen from Bourk; see above.)
            edgeTable = np.array([
            0x0  , 0x109, 0x203, 0x30a, 0x406, 0x50f, 0x605, 0x70c,
            0x80c, 0x905, 0xa0f, 0xb06, 0xc0a, 0xd03, 0xe09, 0xf00,
            0x190, 0x99 , 0x393, 0x29a, 0x596, 0x49f, 0x795, 0x69c,
            0x99c, 0x895, 0xb9f, 0xa96, 0xd9a, 0xc93, 0xf99, 0xe90,
            0x230, 0x339, 0x33 , 0x13a, 0x636, 0x73f, 0x435, 0x53c,
            0xa3c, 0xb35, 0x83f, 0x936, 0xe3a, 0xf33, 0xc39, 0xd30,
            0x3a0, 0x2a9, 0x1a3, 0xaa , 0x7a6, 0x6af, 0x5a5, 0x4ac,
            0xbac, 0xaa5, 0x9af, 0x8a6, 0xfaa, 0xea3, 0xda9, 0xca0,
            0x460, 0x569, 0x663, 0x76a, 0x66 , 0x16f, 0x265, 0x36c,
            0xc6c, 0xd65, 0xe6f, 0xf66, 0x86a, 0x963, 0xa69, 0xb60,
            0x5f0, 0x4f9, 0x7f3, 0x6fa, 0x1f6, 0xff , 0x3f5, 0x2fc,
            0xdfc, 0xcf5, 0xfff, 0xef6, 0x9fa, 0x8f3, 0xbf9, 0xaf0,
            0x650, 0x759, 0x453, 0x55a, 0x256, 0x35f, 0x55 , 0x15c,
            0xe5c, 0xf55, 0xc5f, 0xd56, 0xa5a, 0xb53, 0x859, 0x950,
            0x7c0, 0x6c9, 0x5c3, 0x4ca, 0x3c6, 0x2cf, 0x1c5, 0xcc ,
            0xfcc, 0xec5, 0xdcf, 0xcc6, 0xbca, 0xac3, 0x9c9, 0x8c0,
            0x8c0, 0x9c9, 0xac3, 0xbca, 0xcc6, 0xdcf, 0xec5, 0xfcc,
            0xcc , 0x1c5, 0x2cf, 0x3c6, 0x4ca, 0x5c3, 0x6c9, 0x7c0,
            0x950, 0x859, 0xb53, 0xa5a, 0xd56, 0xc5f, 0xf55, 0xe5c,
            0x15c, 0x55 , 0x35f, 0x256, 0x55a, 0x453, 0x759, 0x650,
            0xaf0, 0xbf9, 0x8f3, 0x9fa, 0xef6, 0xfff, 0xcf5, 0xdfc,
            0x2fc, 0x3f5, 0xff , 0x1f6, 0x6fa, 0x7f3, 0x4f9, 0x5f0,
            0xb60, 0xa69, 0x963, 0x86a, 0xf66, 0xe6f, 0xd65, 0xc6c,
            0x36c, 0x265, 0x16f, 0x66 , 0x76a, 0x663, 0x569, 0x460,
            0xca0, 0xda9, 0xea3, 0xfaa, 0x8a6, 0x9af, 0xaa5, 0xbac,
            0x4ac, 0x5a5, 0x6af, 0x7a6, 0xaa , 0x1a3, 0x2a9, 0x3a0,
            0xd30, 0xc39, 0xf33, 0xe3a, 0x936, 0x83f, 0xb35, 0xa3c,
            0x53c, 0x435, 0x73f, 0x636, 0x13a, 0x33 , 0x339, 0x230,
            0xe90, 0xf99, 0xc93, 0xd9a, 0xa96, 0xb9f, 0x895, 0x99c,
            0x69c, 0x795, 0x49f, 0x596, 0x29a, 0x393, 0x99 , 0x190,
            0xf00, 0xe09, 0xd03, 0xc0a, 0xb06, 0xa0f, 0x905, 0x80c,
            0x70c, 0x605, 0x50f, 0x406, 0x30a, 0x203, 0x109, 0x0   ], dtype=np.uint16)
            
            ## Table of triangles to use for filling each grid cell.
            ## Each set of three integers tells us which three edges to
            ## draw a triangle between.
            ## (Data stolen from Bourk; see above.)
            triTable = [
                [],
                [0, 8, 3],
                [0, 1, 9],
                [1, 8, 3, 9, 8, 1],
                [1, 2, 10],
                [0, 8, 3, 1, 2, 10],
                [9, 2, 10, 0, 2, 9],
                [2, 8, 3, 2, 10, 8, 10, 9, 8],
                [3, 11, 2],
                [0, 11, 2, 8, 11, 0],
                [1, 9, 0, 2, 3, 11],
                [1, 11, 2, 1, 9, 11, 9, 8, 11],
                [3, 10, 1, 11, 10, 3],
                [0, 10, 1, 0, 8, 10, 8, 11, 10],
                [3, 9, 0, 3, 11, 9, 11, 10, 9],
                [9, 8, 10, 10, 8, 11],
                [4, 7, 8],
                [4, 3, 0, 7, 3, 4],
                [0, 1, 9, 8, 4, 7],
                [4, 1, 9, 4, 7, 1, 7, 3, 1],
                [1, 2, 10, 8, 4, 7],
                [3, 4, 7, 3, 0, 4, 1, 2, 10],
                [9, 2, 10, 9, 0, 2, 8, 4, 7],
                [2, 10, 9, 2, 9, 7, 2, 7, 3, 7, 9, 4],
                [8, 4, 7, 3, 11, 2],
                [11, 4, 7, 11, 2, 4, 2, 0, 4],
                [9, 0, 1, 8, 4, 7, 2, 3, 11],
                [4, 7, 11, 9, 4, 11, 9, 11, 2, 9, 2, 1],
                [3, 10, 1, 3, 11, 10, 7, 8, 4],
                [1, 11, 10, 1, 4, 11, 1, 0, 4, 7, 11, 4],
                [4, 7, 8, 9, 0, 11, 9, 11, 10, 11, 0, 3],
                [4, 7, 11, 4, 11, 9, 9, 11, 10],
                [9, 5, 4],
                [9, 5, 4, 0, 8, 3],
                [0, 5, 4, 1, 5, 0],
                [8, 5, 4, 8, 3, 5, 3, 1, 5],
                [1, 2, 10, 9, 5, 4],
                [3, 0, 8, 1, 2, 10, 4, 9, 5],
                [5, 2, 10, 5, 4, 2, 4, 0, 2],
                [2, 10, 5, 3, 2, 5, 3, 5, 4, 3, 4, 8],
                [9, 5, 4, 2, 3, 11],
                [0, 11, 2, 0, 8, 11, 4, 9, 5],
                [0, 5, 4, 0, 1, 5, 2, 3, 11],
                [2, 1, 5, 2, 5, 8, 2, 8, 11, 4, 8, 5],
                [10, 3, 11, 10, 1, 3, 9, 5, 4],
                [4, 9, 5, 0, 8, 1, 8, 10, 1, 8, 11, 10],
                [5, 4, 0, 5, 0, 11, 5, 11, 10, 11, 0, 3],
                [5, 4, 8, 5, 8, 10, 10, 8, 11],
                [9, 7, 8, 5, 7, 9],
                [9, 3, 0, 9, 5, 3, 5, 7, 3],
                [0, 7, 8, 0, 1, 7, 1, 5, 7],
                [1, 5, 3, 3, 5, 7],
                [9, 7, 8, 9, 5, 7, 10, 1, 2],
                [10, 1, 2, 9, 5, 0, 5, 3, 0, 5, 7, 3],
                [8, 0, 2, 8, 2, 5, 8, 5, 7, 10, 5, 2],
                [2, 10, 5, 2, 5, 3, 3, 5, 7],
                [7, 9, 5, 7, 8, 9, 3, 11, 2],
                [9, 5, 7, 9, 7, 2, 9, 2, 0, 2, 7, 11],
                [2, 3, 11, 0, 1, 8, 1, 7, 8, 1, 5, 7],
                [11, 2, 1, 11, 1, 7, 7, 1, 5],
                [9, 5, 8, 8, 5, 7, 10, 1, 3, 10, 3, 11],
                [5, 7, 0, 5, 0, 9, 7, 11, 0, 1, 0, 10, 11, 10, 0],
                [11, 10, 0, 11, 0, 3, 10, 5, 0, 8, 0, 7, 5, 7, 0],
                [11, 10, 5, 7, 11, 5],
                [10, 6, 5],
                [0, 8, 3, 5, 10, 6],
                [9, 0, 1, 5, 10, 6],
                [1, 8, 3, 1, 9, 8, 5, 10, 6],
                [1, 6, 5, 2, 6, 1],
                [1, 6, 5, 1, 2, 6, 3, 0, 8],
                [9, 6, 5, 9, 0, 6, 0, 2, 6],
                [5, 9, 8, 5, 8, 2, 5, 2, 6, 3, 2, 8],
                [2, 3, 11, 10, 6, 5],
                [11, 0, 8, 11, 2, 0, 10, 6, 5],
                [0, 1, 9, 2, 3, 11, 5, 10, 6],
                [5, 10, 6, 1, 9, 2, 9, 11, 2, 9, 8, 11],
                [6, 3, 11, 6, 5, 3, 5, 1, 3],
                [0, 8, 11, 0, 11, 5, 0, 5, 1, 5, 11, 6],
                [3, 11, 6, 0, 3, 6, 0, 6, 5, 0, 5, 9],
                [6, 5, 9, 6, 9, 11, 11, 9, 8],
                [5, 10, 6, 4, 7, 8],
                [4, 3, 0, 4, 7, 3, 6, 5, 10],
                [1, 9, 0, 5, 10, 6, 8, 4, 7],
                [10, 6, 5, 1, 9, 7, 1, 7, 3, 7, 9, 4],
                [6, 1, 2, 6, 5, 1, 4, 7, 8],
                [1, 2, 5, 5, 2, 6, 3, 0, 4, 3, 4, 7],
                [8, 4, 7, 9, 0, 5, 0, 6, 5, 0, 2, 6],
                [7, 3, 9, 7, 9, 4, 3, 2, 9, 5, 9, 6, 2, 6, 9],
                [3, 11, 2, 7, 8, 4, 10, 6, 5],
                [5, 10, 6, 4, 7, 2, 4, 2, 0, 2, 7, 11],
                [0, 1, 9, 4, 7, 8, 2, 3, 11, 5, 10, 6],
                [9, 2, 1, 9, 11, 2, 9, 4, 11, 7, 11, 4, 5, 10, 6],
                [8, 4, 7, 3, 11, 5, 3, 5, 1, 5, 11, 6],
                [5, 1, 11, 5, 11, 6, 1, 0, 11, 7, 11, 4, 0, 4, 11],
                [0, 5, 9, 0, 6, 5, 0, 3, 6, 11, 6, 3, 8, 4, 7],
                [6, 5, 9, 6, 9, 11, 4, 7, 9, 7, 11, 9],
                [10, 4, 9, 6, 4, 10],
                [4, 10, 6, 4, 9, 10, 0, 8, 3],
                [10, 0, 1, 10, 6, 0, 6, 4, 0],
                [8, 3, 1, 8, 1, 6, 8, 6, 4, 6, 1, 10],
                [1, 4, 9, 1, 2, 4, 2, 6, 4],
                [3, 0, 8, 1, 2, 9, 2, 4, 9, 2, 6, 4],
                [0, 2, 4, 4, 2, 6],
                [8, 3, 2, 8, 2, 4, 4, 2, 6],
                [10, 4, 9, 10, 6, 4, 11, 2, 3],
                [0, 8, 2, 2, 8, 11, 4, 9, 10, 4, 10, 6],
                [3, 11, 2, 0, 1, 6, 0, 6, 4, 6, 1, 10],
                [6, 4, 1, 6, 1, 10, 4, 8, 1, 2, 1, 11, 8, 11, 1],
                [9, 6, 4, 9, 3, 6, 9, 1, 3, 11, 6, 3],
                [8, 11, 1, 8, 1, 0, 11, 6, 1, 9, 1, 4, 6, 4, 1],
                [3, 11, 6, 3, 6, 0, 0, 6, 4],
                [6, 4, 8, 11, 6, 8],
                [7, 10, 6, 7, 8, 10, 8, 9, 10],
                [0, 7, 3, 0, 10, 7, 0, 9, 10, 6, 7, 10],
                [10, 6, 7, 1, 10, 7, 1, 7, 8, 1, 8, 0],
                [10, 6, 7, 10, 7, 1, 1, 7, 3],
                [1, 2, 6, 1, 6, 8, 1, 8, 9, 8, 6, 7],
                [2, 6, 9, 2, 9, 1, 6, 7, 9, 0, 9, 3, 7, 3, 9],
                [7, 8, 0, 7, 0, 6, 6, 0, 2],
                [7, 3, 2, 6, 7, 2],
                [2, 3, 11, 10, 6, 8, 10, 8, 9, 8, 6, 7],
                [2, 0, 7, 2, 7, 11, 0, 9, 7, 6, 7, 10, 9, 10, 7],
                [1, 8, 0, 1, 7, 8, 1, 10, 7, 6, 7, 10, 2, 3, 11],
                [11, 2, 1, 11, 1, 7, 10, 6, 1, 6, 7, 1],
                [8, 9, 6, 8, 6, 7, 9, 1, 6, 11, 6, 3, 1, 3, 6],
                [0, 9, 1, 11, 6, 7],
                [7, 8, 0, 7, 0, 6, 3, 11, 0, 11, 6, 0],
                [7, 11, 6],
                [7, 6, 11],
                [3, 0, 8, 11, 7, 6],
                [0, 1, 9, 11, 7, 6],
                [8, 1, 9, 8, 3, 1, 11, 7, 6],
                [10, 1, 2, 6, 11, 7],
                [1, 2, 10, 3, 0, 8, 6, 11, 7],
                [2, 9, 0, 2, 10, 9, 6, 11, 7],
                [6, 11, 7, 2, 10, 3, 10, 8, 3, 10, 9, 8],
                [7, 2, 3, 6, 2, 7],
                [7, 0, 8, 7, 6, 0, 6, 2, 0],
                [2, 7, 6, 2, 3, 7, 0, 1, 9],
                [1, 6, 2, 1, 8, 6, 1, 9, 8, 8, 7, 6],
                [10, 7, 6, 10, 1, 7, 1, 3, 7],
                [10, 7, 6, 1, 7, 10, 1, 8, 7, 1, 0, 8],
                [0, 3, 7, 0, 7, 10, 0, 10, 9, 6, 10, 7],
                [7, 6, 10, 7, 10, 8, 8, 10, 9],
                [6, 8, 4, 11, 8, 6],
                [3, 6, 11, 3, 0, 6, 0, 4, 6],
                [8, 6, 11, 8, 4, 6, 9, 0, 1],
                [9, 4, 6, 9, 6, 3, 9, 3, 1, 11, 3, 6],
                [6, 8, 4, 6, 11, 8, 2, 10, 1],
                [1, 2, 10, 3, 0, 11, 0, 6, 11, 0, 4, 6],
                [4, 11, 8, 4, 6, 11, 0, 2, 9, 2, 10, 9],
                [10, 9, 3, 10, 3, 2, 9, 4, 3, 11, 3, 6, 4, 6, 3],
                [8, 2, 3, 8, 4, 2, 4, 6, 2],
                [0, 4, 2, 4, 6, 2],
                [1, 9, 0, 2, 3, 4, 2, 4, 6, 4, 3, 8],
                [1, 9, 4, 1, 4, 2, 2, 4, 6],
                [8, 1, 3, 8, 6, 1, 8, 4, 6, 6, 10, 1],
                [10, 1, 0, 10, 0, 6, 6, 0, 4],
                [4, 6, 3, 4, 3, 8, 6, 10, 3, 0, 3, 9, 10, 9, 3],
                [10, 9, 4, 6, 10, 4],
                [4, 9, 5, 7, 6, 11],
                [0, 8, 3, 4, 9, 5, 11, 7, 6],
                [5, 0, 1, 5, 4, 0, 7, 6, 11],
                [11, 7, 6, 8, 3, 4, 3, 5, 4, 3, 1, 5],
                [9, 5, 4, 10, 1, 2, 7, 6, 11],
                [6, 11, 7, 1, 2, 10, 0, 8, 3, 4, 9, 5],
                [7, 6, 11, 5, 4, 10, 4, 2, 10, 4, 0, 2],
                [3, 4, 8, 3, 5, 4, 3, 2, 5, 10, 5, 2, 11, 7, 6],
                [7, 2, 3, 7, 6, 2, 5, 4, 9],
                [9, 5, 4, 0, 8, 6, 0, 6, 2, 6, 8, 7],
                [3, 6, 2, 3, 7, 6, 1, 5, 0, 5, 4, 0],
                [6, 2, 8, 6, 8, 7, 2, 1, 8, 4, 8, 5, 1, 5, 8],
                [9, 5, 4, 10, 1, 6, 1, 7, 6, 1, 3, 7],
                [1, 6, 10, 1, 7, 6, 1, 0, 7, 8, 7, 0, 9, 5, 4],
                [4, 0, 10, 4, 10, 5, 0, 3, 10, 6, 10, 7, 3, 7, 10],
                [7, 6, 10, 7, 10, 8, 5, 4, 10, 4, 8, 10],
                [6, 9, 5, 6, 11, 9, 11, 8, 9],
                [3, 6, 11, 0, 6, 3, 0, 5, 6, 0, 9, 5],
                [0, 11, 8, 0, 5, 11, 0, 1, 5, 5, 6, 11],
                [6, 11, 3, 6, 3, 5, 5, 3, 1],
                [1, 2, 10, 9, 5, 11, 9, 11, 8, 11, 5, 6],
                [0, 11, 3, 0, 6, 11, 0, 9, 6, 5, 6, 9, 1, 2, 10],
                [11, 8, 5, 11, 5, 6, 8, 0, 5, 10, 5, 2, 0, 2, 5],
                [6, 11, 3, 6, 3, 5, 2, 10, 3, 10, 5, 3],
                [5, 8, 9, 5, 2, 8, 5, 6, 2, 3, 8, 2],
                [9, 5, 6, 9, 6, 0, 0, 6, 2],
                [1, 5, 8, 1, 8, 0, 5, 6, 8, 3, 8, 2, 6, 2, 8],
                [1, 5, 6, 2, 1, 6],
                [1, 3, 6, 1, 6, 10, 3, 8, 6, 5, 6, 9, 8, 9, 6],
                [10, 1, 0, 10, 0, 6, 9, 5, 0, 5, 6, 0],
                [0, 3, 8, 5, 6, 10],
                [10, 5, 6],
                [11, 5, 10, 7, 5, 11],
                [11, 5, 10, 11, 7, 5, 8, 3, 0],
                [5, 11, 7, 5, 10, 11, 1, 9, 0],
                [10, 7, 5, 10, 11, 7, 9, 8, 1, 8, 3, 1],
                [11, 1, 2, 11, 7, 1, 7, 5, 1],
                [0, 8, 3, 1, 2, 7, 1, 7, 5, 7, 2, 11],
                [9, 7, 5, 9, 2, 7, 9, 0, 2, 2, 11, 7],
                [7, 5, 2, 7, 2, 11, 5, 9, 2, 3, 2, 8, 9, 8, 2],
                [2, 5, 10, 2, 3, 5, 3, 7, 5],
                [8, 2, 0, 8, 5, 2, 8, 7, 5, 10, 2, 5],
                [9, 0, 1, 5, 10, 3, 5, 3, 7, 3, 10, 2],
                [9, 8, 2, 9, 2, 1, 8, 7, 2, 10, 2, 5, 7, 5, 2],
                [1, 3, 5, 3, 7, 5],
                [0, 8, 7, 0, 7, 1, 1, 7, 5],
                [9, 0, 3, 9, 3, 5, 5, 3, 7],
                [9, 8, 7, 5, 9, 7],
                [5, 8, 4, 5, 10, 8, 10, 11, 8],
                [5, 0, 4, 5, 11, 0, 5, 10, 11, 11, 3, 0],
                [0, 1, 9, 8, 4, 10, 8, 10, 11, 10, 4, 5],
                [10, 11, 4, 10, 4, 5, 11, 3, 4, 9, 4, 1, 3, 1, 4],
                [2, 5, 1, 2, 8, 5, 2, 11, 8, 4, 5, 8],
                [0, 4, 11, 0, 11, 3, 4, 5, 11, 2, 11, 1, 5, 1, 11],
                [0, 2, 5, 0, 5, 9, 2, 11, 5, 4, 5, 8, 11, 8, 5],
                [9, 4, 5, 2, 11, 3],
                [2, 5, 10, 3, 5, 2, 3, 4, 5, 3, 8, 4],
                [5, 10, 2, 5, 2, 4, 4, 2, 0],
                [3, 10, 2, 3, 5, 10, 3, 8, 5, 4, 5, 8, 0, 1, 9],
                [5, 10, 2, 5, 2, 4, 1, 9, 2, 9, 4, 2],
                [8, 4, 5, 8, 5, 3, 3, 5, 1],
                [0, 4, 5, 1, 0, 5],
                [8, 4, 5, 8, 5, 3, 9, 0, 5, 0, 3, 5],
                [9, 4, 5],
                [4, 11, 7, 4, 9, 11, 9, 10, 11],
                [0, 8, 3, 4, 9, 7, 9, 11, 7, 9, 10, 11],
                [1, 10, 11, 1, 11, 4, 1, 4, 0, 7, 4, 11],
                [3, 1, 4, 3, 4, 8, 1, 10, 4, 7, 4, 11, 10, 11, 4],
                [4, 11, 7, 9, 11, 4, 9, 2, 11, 9, 1, 2],
                [9, 7, 4, 9, 11, 7, 9, 1, 11, 2, 11, 1, 0, 8, 3],
                [11, 7, 4, 11, 4, 2, 2, 4, 0],
                [11, 7, 4, 11, 4, 2, 8, 3, 4, 3, 2, 4],
                [2, 9, 10, 2, 7, 9, 2, 3, 7, 7, 4, 9],
                [9, 10, 7, 9, 7, 4, 10, 2, 7, 8, 7, 0, 2, 0, 7],
                [3, 7, 10, 3, 10, 2, 7, 4, 10, 1, 10, 0, 4, 0, 10],
                [1, 10, 2, 8, 7, 4],
                [4, 9, 1, 4, 1, 7, 7, 1, 3],
                [4, 9, 1, 4, 1, 7, 0, 8, 1, 8, 7, 1],
                [4, 0, 3, 7, 4, 3],
                [4, 8, 7],
                [9, 10, 8, 10, 11, 8],
                [3, 0, 9, 3, 9, 11, 11, 9, 10],
                [0, 1, 10, 0, 10, 8, 8, 10, 11],
                [3, 1, 10, 11, 3, 10],
                [1, 2, 11, 1, 11, 9, 9, 11, 8],
                [3, 0, 9, 3, 9, 11, 1, 2, 9, 2, 11, 9],
                [0, 2, 11, 8, 0, 11],
                [3, 2, 11],
                [2, 3, 8, 2, 8, 10, 10, 8, 9],
                [9, 10, 2, 0, 9, 2],
                [2, 3, 8, 2, 8, 10, 0, 1, 8, 1, 10, 8],
                [1, 10, 2],
                [1, 3, 8, 9, 1, 8],
                [0, 9, 1],
                [0, 3, 8],
                []
            ]    
            edgeShifts = np.array([  ## maps edge ID (0-11) to (x,y,z) cell offset and edge ID (0-2)
                [0, 0, 0, 0],   
                [1, 0, 0, 1],
                [0, 1, 0, 0],
                [0, 0, 0, 1],
                [0, 0, 1, 0],
                [1, 0, 1, 1],
                [0, 1, 1, 0],
                [0, 0, 1, 1],
                [0, 0, 0, 2],
                [1, 0, 0, 2],
                [1, 1, 0, 2],
                [0, 1, 0, 2],
                #[9, 9, 9, 9]  ## fake
            ], dtype=np.ubyte)
            nTableFaces = np.array([len(f)/3 for f in triTable], dtype=np.ubyte)
            faceShiftTables = [None]
            for i in range(1,6):
                ## compute lookup table of index: vertexes mapping
                faceTableI = np.zeros((len(triTable), i*3), dtype=np.ubyte)
                faceTableInds = np.argwhere(nTableFaces == i)
                faceTableI[faceTableInds[:,0]] = np.array([triTable[j] for j in faceTableInds])
                faceTableI = faceTableI.reshape((len(triTable), i, 3))
                faceShiftTables.append(edgeShifts[faceTableI])
                
            ## Let's try something different:
            #faceTable = np.empty((256, 5, 3, 4), dtype=np.ubyte)   # (grid cell index, faces, vertexes, edge lookup)
            #for i,f in enumerate(triTable):
                #f = np.array(f + [12] * (15-len(f))).reshape(5,3)
                #faceTable[i] = edgeShifts[f]
            
            
            IsosurfaceDataCache = (faceShiftTables, edgeShifts, edgeTable, nTableFaces)
        else:
            faceShiftTables, edgeShifts, edgeTable, nTableFaces = IsosurfaceDataCache
    
    
        
        ## mark everything below the isosurface level
        mask = data < level
        
        ### make eight sub-fields and compute indexes for grid cells
        index = np.zeros([x-1 for x in data.shape], dtype=np.ubyte)
        fields = np.empty((2,2,2), dtype=object)
        slices = [slice(0,-1), slice(1,None)]
        for i in [0,1]:
            for j in [0,1]:
                for k in [0,1]:
                    fields[i,j,k] = mask[slices[i], slices[j], slices[k]]
                    vertIndex = i - 2*j*i + 3*j + 4*k  ## this is just to match Bourk's vertex numbering scheme
                    index += fields[i,j,k] * 2**vertIndex
        
        ### Generate table of edges that have been cut
        cutEdges = np.zeros([x+1 for x in index.shape]+[3], dtype=np.uint32)
        edges = edgeTable[index]
        for i, shift in enumerate(edgeShifts[:12]):        
            slices = [slice(shift[j],cutEdges.shape[j]+(shift[j]-1)) for j in range(3)]
            cutEdges[slices[0], slices[1], slices[2], shift[3]] += edges & 2**i
        
        ## for each cut edge, interpolate to see where exactly the edge is cut and generate vertex positions
        m = cutEdges > 0
        vertexInds = np.argwhere(m)   ## argwhere is slow!
        vertexes = vertexInds[:,:3].astype(np.float32)
        dataFlat = data.reshape(data.shape[0]*data.shape[1]*data.shape[2])
        
        ## re-use the cutEdges array as a lookup table for vertex IDs
        cutEdges[vertexInds[:,0], vertexInds[:,1], vertexInds[:,2], vertexInds[:,3]] = np.arange(vertexInds.shape[0])
        
        for i in [0,1,2]:
            vim = vertexInds[:,3] == i
            vi = vertexInds[vim, :3]
            viFlat = (vi * (np.array(data.strides[:3]) / data.itemsize)[np.newaxis,:]).sum(axis=1)
            v1 = dataFlat[viFlat]
            v2 = dataFlat[viFlat + data.strides[i]/data.itemsize]
            vertexes[vim,i] += (level-v1) / (v2-v1)
        
        ### compute the set of vertex indexes for each face. 
        
        ## This works, but runs a bit slower.
        #cells = np.argwhere((index != 0) & (index != 255))  ## all cells with at least one face
        #cellInds = index[cells[:,0], cells[:,1], cells[:,2]]
        #verts = faceTable[cellInds]
        #mask = verts[...,0,0] != 9
        #verts[...,:3] += cells[:,np.newaxis,np.newaxis,:]  ## we now have indexes into cutEdges
        #verts = verts[mask]
        #faces = cutEdges[verts[...,0], verts[...,1], verts[...,2], verts[...,3]]  ## and these are the vertex indexes we want.
        
        
        ## To allow this to be vectorized efficiently, we count the number of faces in each 
        ## grid cell and handle each group of cells with the same number together.
        ## determine how many faces to assign to each grid cell
        nFaces = nTableFaces[index]
        totFaces = nFaces.sum()
        faces = np.empty((totFaces, 3), dtype=np.uint32)
        ptr = 0
        #import debug
        #p = debug.Profiler('isosurface', disabled=False)
        
        ## this helps speed up an indexing operation later on
        cs = np.array(cutEdges.strides)/cutEdges.itemsize
        cutEdges = cutEdges.flatten()
    
        ## this, strangely, does not seem to help.
        #ins = np.array(index.strides)/index.itemsize
        #index = index.flatten()
    
        for i in range(1,6):
            ### expensive:
            #p.mark('1')
            cells = np.argwhere(nFaces == i)  ## all cells which require i faces  (argwhere is expensive)
            #p.mark('2')
            if cells.shape[0] == 0:
                continue
            #cellInds = index[(cells*ins[np.newaxis,:]).sum(axis=1)]
            cellInds = index[cells[:,0], cells[:,1], cells[:,2]]   ## index values of cells to process for this round
            #p.mark('3')
            
            ### expensive:
            verts = faceShiftTables[i][cellInds]
            #p.mark('4')
            verts[...,:3] += cells[:,np.newaxis,np.newaxis,:]  ## we now have indexes into cutEdges
            verts = verts.reshape((verts.shape[0]*i,)+verts.shape[2:])
            #p.mark('5')
            
            ### expensive:
            #print verts.shape
            verts = (verts * cs[np.newaxis, np.newaxis, :]).sum(axis=2)
            #vertInds = cutEdges[verts[...,0], verts[...,1], verts[...,2], verts[...,3]]  ## and these are the vertex indexes we want.
            vertInds = cutEdges[verts]
            #p.mark('6')
            nv = vertInds.shape[0]
            #p.mark('7')
            faces[ptr:ptr+nv] = vertInds #.reshape((nv, 3))
            #p.mark('8')
            ptr += nv
            
        return vertexes, faces
    
    
        
    def invertQTransform(tr):
        """Return a QTransform that is the inverse of *tr*.
        Rasises an exception if tr is not invertible.
        
        Note that this function is preferred over QTransform.inverted() due to
        bugs in that method. (specifically, Qt has floating-point precision issues
        when determining whether a matrix is invertible)
        """
        if not HAVE_SCIPY:
            inv = tr.inverted()
            if inv[1] is False:
                raise Exception("Transform is not invertible.")
            return inv[0]
        arr = np.array([[tr.m11(), tr.m12(), tr.m13()], [tr.m21(), tr.m22(), tr.m23()], [tr.m31(), tr.m32(), tr.m33()]])
        inv = scipy.linalg.inv(arr)
        return QtGui.QTransform(inv[0,0], inv[0,1], inv[0,2], inv[1,0], inv[1,1], inv[1,2], inv[2,0], inv[2,1])
        
        
    def pseudoScatter(data, spacing=None, shuffle=True):
        """
        Used for examining the distribution of values in a set.
        
        Given a list of x-values, construct a set of y-values such that an x,y scatter-plot
        will not have overlapping points (it will look similar to a histogram).
        """
        inds = np.arange(len(data))
        if shuffle:
            np.random.shuffle(inds)
            
        data = data[inds]
        
        if spacing is None:
            spacing = 2.*np.std(data)/len(data)**0.5
        s2 = spacing**2
        
        yvals = np.empty(len(data))
        yvals[0] = 0
        for i in range(1,len(data)):
            x = data[i]     # current x value to be placed
            x0 = data[:i]   # all x values already placed
            y0 = yvals[:i]  # all y values already placed
            y = 0
            
            dx = (x0-x)**2  # x-distance to each previous point
            xmask = dx < s2  # exclude anything too far away
            
            if xmask.sum() > 0:
                dx = dx[xmask]
                dy = (s2 - dx)**0.5   
                limits = np.empty((2,len(dy)))  # ranges of y-values to exclude
                limits[0] = y0[xmask] - dy
                limits[1] = y0[xmask] + dy    
                
                while True:
                    # ignore anything below this y-value
                    mask = limits[1] >= y
                    limits = limits[:,mask]
                    
                    # are we inside an excluded region?
                    mask = (limits[0] < y) & (limits[1] > y)
                    if mask.sum() == 0:
                        break
                    y = limits[:,mask].max()
            
            yvals[i] = y
        
        return yvals[np.argsort(inds)]  ## un-shuffle values before returning